USchneider
USchneider

Reputation: 153

functional style to multiply two lists with Scala

I'm using Scala 2.9, and would like to construct a list based on some operations.

Consider the following, I have two simple lists:


    val l1 = List(2,3)
    val l2 = List(List(4,5,6),List(7,8,9))

The behavior I want is as follows, an operation with both lists, like this:


    (2*4)+(3*7)
    (2*5)+(3*8)
    (2*6)+(3*9)

And I'd like to have as a result another list with these values:

29,34,39

I've already try to solve with the source code above. I'm probably thinking about this completely the wrong way, but I'm struggling to come up with an elegant solution.

    val lr = (l1,l2).zipped.map( (t1:Int, t2:List[Int]) =>
        ...
    )    
    println (lr) // should print List(29, 34, 39)

However, I’m not even sure if I’m in the right way or how should I continuous. Can anyone think of an elegant solution to my problem?

Upvotes: 5

Views: 4153

Answers (1)

Eastsun
Eastsun

Reputation: 18859

Here is one possible way, but I am not sure if it is elegant:

l2.transpose.map(sl => (l1, sl).zipped.map{ case(x,y) => x*y }.sum)
res: List[Int] = List(29, 34, 39)

According to @Tharabas and @michael_s's comments, we finally have a more compact solution:

l2.transpose.map((l1,_).zipped.map(_*_).sum)

Upvotes: 12

Related Questions