4

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 !

Tg.
  • 5,608
  • 7
  • 39
  • 52
  • 2
    http://stackoverflow.com/questions/1157564/mapping-over-multiple-seq-in-scala, http://stackoverflow.com/questions/7068031/most-concise-way-to-combine-sequence-elements – Luigi Plinge Nov 30 '11 at 07:02
  • Yeah, it's a duplicate. zipWith is still not in Scala, and Martin's answer still works - and is easy. – Julian Fondren Nov 30 '11 at 07:15
  • Thanks, but what if I have more than 3 list ? It seems those solution limit itself to tuple, which pretty much could do only over three list. – Tg. Nov 30 '11 at 07:17
  • 1
    (List(1,2,3), List(4,5,6), List(7,8,9)).zipped map (_ + _ + _) // yields List(12, 15, 18) (EDIT: oops, I read '2 lists' there somehow. You're right, this doesn't extend to a fourth list.) – Julian Fondren Nov 30 '11 at 07:24
  • 5+6, 7+8 or 2+5, 3+6...? – user unknown Nov 30 '11 at 08:20

1 Answers1

8

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.

Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180