4

Very novice Scala programmer so hopefully this is pretty simple.

I have an array of tuples that looks like this:

Array((1,Array(1.0,0.0,5.2,0.0), 
      (1,Array(1.0,0.0,6.3,0.0),
      (2,Array(0.0,1.0,0.0,1.2),
      (2,Array(0.0,1.0,0.0,2.5))

I want to sum up the corresponding values in the second part of the tuple based on the key in the first. So the result would look like this:

Array((1,(2.0,0.0,11.5,0.0),
      (2,(0.0,2.0,0.0,3.7))

The function I came up with is:

def sumByKeys[A](tuples: Array[(String, Array[Double])]) = {
    tuples.groupBy(_._1).mapValues(_.map(_._2).sum)
}

There error I get is

error: could not find implicit value for parameter num: Numeric[Array[Double]]
       tuples.groupBy(_._1).mapValues(_.map(_._2).sum)
                                                  ^

I'm hoping this is something simple where I am just messing up the data types.

Thanks.

1
  • 1
    why didn't you just use a Map instead? Commented Sep 26, 2014 at 15:56

1 Answer 1

4
scala> a.groupBy(_._1).mapValues(_.map(_._2).transpose.map(_.sum)).toArray
res2: Array[(Int, Array[Double])] = Array((2,Array(0.0, 2.0, 0.0, 3.7)),
                                          (1,Array(2.0, 0.0, 11.5, 0.0)))
Sign up to request clarification or add additional context in comments.

1 Comment

This does it exactly. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.