Which is the fastest idiomatic way to add all vectors (in the math sense) inside a Scala list?

Posted by davips on Stack Overflow See other posts from Stack Overflow or by davips
Published on 2013-11-08T04:50:15Z Indexed on 2013/11/08 15:55 UTC
Read the original article Hit count: 159

Filed under:
|

I have two solutions, but one doesn't compile and the other, I think, could be better:

object Foo extends App {
     val vectors = List(List(1,2,3), List(2,2,3), List(1,2,2)) //just a stupid example

     //transposing
     println("vectors = " + vectors.transpose.map (_.sum)) //it prints vectors = List(4, 6, 8)

     //folding
     vectors.reduce {
        case (a, b) => (a zip b) map {
           case (x, y) => x + y
        }
     } //compiler says: missing parameter type for exp. function; arg. types must be fully known
} 

© Stack Overflow or respective owner

Related posts about list

Related posts about scala