Apply function on each elements in one list using element from others list as argument?

I am not sure how to call this 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 involving using looping from 0 to x.lenght which is pretty ugly. And if it is possible, I would like the solution that could use over nth number of list and maybe with other type of operator beside +.

Thanks !

Answers


In response to "what if I have more than 3 list?":

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

Use like 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: alternatively

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

does the same and is probably more efficient.


Need Your Help

How to get the 2D Array length

java

I create method to display element in the 2D array. but I can't specify the array length for each dimension. this is my code

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.