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)
Give this a try:
(0 /: l) { case (a, (b, c)) => b + a }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With