Apply a function to each item in one list, using an item from another list as an argument?

I'm not sure what to call it, but I want something like this.

val x = List(1,2,3,...) val y = List(4,5,6,...) //want a result of List(1+4, 5+6, 7+8,...) 

Is there an easy way to do this in scala? My current implementation involves using a loop from 0 to x.lenght, which is pretty ugly. And if possible, I would like a solution that could use more than the nth number of the list, and possibly with a different type of operator next to +.

Thanks!

+4
source share
1 answer

In response to β€œwhat if I have more than 3 lists?”:

 def combineAll[T](xss: Seq[T]*)(f: (T, T) => T) = xss reduceLeft ((_,_).zipped map f) 

Use this:

 scala> combineAll(List(1,2,3), List(2,2,2), List(4,5,6), List(10,10,10))(_+_) res5: Seq[Int] = List(17, 19, 21) 

edit: alternative

 def combineAll[T](xss: Seq[T]*)(f: (T, T) => T) = xss.transpose map (_ reduceLeft f) 

does the same and is probably more efficient.

+8
source

Source: https://habr.com/ru/post/1383804/


All Articles