Stacking a tuple list with Scala

What is wrong with this simple scala code?

val l = List(("a", 1), ("b", 2), ("c", 3), ("d", 4), ("e", 5)) l.fold(0) {(acc: Int, tup: (String, Int)) => acc + tup._2} 

: 9: error: type of non-compliance; found: (Int, (String, Int)) => Int required: (Any, Any) => Any l.fold (0) {(acc: Int, tup: (String, Int)) => acc + tup. _2}

In other functional languages ​​(e.g. f #) this works:

 let l = [("a", 1); ("b", 2); ("c", 3); ("d", 4)];; List.fold(fun accm tup -> accm + (snd tup)) 0 l;; val it : int = 10 
+5
source share
1 answer

The fold method assumes an associative operator and can theoretically (for example, when using parallelism) be executed in random order. Thus, the signature makes it clear that the type of accumulation must be a supertype of the collection element:

 def fold[A1 >: A](z: A1)(op: (A1, A1) ⇒ A1): A1 

The deduced supertype (String, Int) and Int is Any .

All of this is described in the API documentation .


What you want is foldLeft or foldRight , which do not have this type restriction:

 def foldLeft[B](z: B)(f: (B, A) ⇒ B): B 

Thus:

 l.foldLeft(0) { (acc, tup) => acc + tup._2 } 

or

 (0 /: l) { case (acc, (_, n)) => acc + n } 
+12
source

Source: https://habr.com/ru/post/1209584/


All Articles