Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a sum of arrays of tuples in scala

Tags:

scala

I have a simple array of tuples

val arr = Array((1,2), (3,4),(5,6),(7,8),(9,10))

I wish to get (1+3+5+7+9, 2+4+6+8+10) tuple as the answer

What is the best way to get the sum as tuples, similar to regular arrays. I tried

val res = arr.foldLeft(0,0)(_ + _)

This does not work.

Sorry about not writing the context. I was using it in scalding with algebird. Algebird allows sums of tuples and I assumed this would work. That was my mistake.

like image 827
trialcritic Avatar asked Jul 11 '14 17:07

trialcritic


2 Answers

There is no such thing as Tuple addition, so that can't work. You would have to operate on each ordinate of the Tuple:

val res = arr.foldLeft(0,0){ case (sum, next) => (sum._1 + next._1, sum._2 + next._2) }

res: (Int, Int) = (25,30)
like image 154
Michael Zajac Avatar answered Sep 19 '22 21:09

Michael Zajac


This should work nicely:

arr.foldLeft((0,0)){ case ((a0,b0),(a1,b1)) => (a0+a1,b0+b1) }

Addition isn't defined for tuples.

like image 34
Timothy Shields Avatar answered Sep 22 '22 21:09

Timothy Shields