Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fold list of tuples in scala with destructuring

Tags:

scala

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)

like image 981
IttayD Avatar asked Nov 09 '09 13:11

IttayD


1 Answers

Give this a try:

(0 /: l) { case (a, (b, c)) => b + a }
like image 187
Walter Chang Avatar answered Oct 28 '22 17:10

Walter Chang