Search code examples
scalafoldleft

foldLeft on List of Tuples: strange unexpected results


I am having a list of tuples which elements I want to be summed:

val t = Seq(1,2,3,4,5).map(el => (el,1))
t: Seq[(Int, Int)] = List((1,1), (2,1), (3,1), (4,1), (5,1))

t.foldLeft(0,0){ case ((a,b),(c,d)) => (a+b,c+d)}
res3: (Int, Int) = (14,6)

The answer (14,6) is unexpected indeed (expected one was (15,5)).

What puzzles me even more:

t.foldLeft(0,1){ case ((a,b),(c,d)) => (a+b,c+d)}
res3: (Int, Int) = (15,6)

My questions are what do parameters in foldLeft(x,y) correspond to (are they initiation params for 1st and 2nd folds???) and how to get the desired sums over 1st and 2nd elements of tuple.


Solution

  • You have an error in your folding function. Your accumulator is in (a,b) and element is in (c,d). In order to sum you should return (a+c, b+d)