tags:

views:

319

answers:

2
scala> val l = List((1,2), (2,3))
l: List[(Int, Int)] = List((1,2), (2,3))

I can do

scala>  (0 /: l) {(a, i) => i._1 + a}
res20: Int = 3

But I want to be able to name the tuple's elements. Something like:

scala> (0 /: l) {(a, (b,c)) => b + a}
<console>:1: error: not a legal formal parameter
       (0 /: l) {(a, (b,c)) => b + a}
                     ^

I know I can do:

scala> (0 /: l) {(a, i) => val (b, c) = i; b + a}
res0: Int = 3

But is there a way of making the code more concise (my real code involves several such folds and I don't like needing to invent a variable name ('i' in the example above) for each)

+7  A: 

Give this a try:

(0 /: l) { case (a, (b, c)) => b + a }
Walter Chang
+2  A: 

Note that, in addition to Walter's answer, you can use the underscore _ instead of c in the pattern match:

val i = (0 /: l) { case (a, (b, _)) => b + a }

It acts as an anything goes placeholder in the Tuple2 pattern and (to my mind) makes it clearer that you don't actually use the value in your calculation.

Also, in 2.8 you would be able to do:

val i = l.map(_._1).sum
oxbow_lakes