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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With