Mapping over multiple Seq in Scala
Posted
by bsdfish
on Stack Overflow
See other posts from Stack Overflow
or by bsdfish
Published on 2009-07-21T06:29:03Z
Indexed on
2010/04/04
6:13 UTC
Read the original article
Hit count: 216
Suppose I have
val foo : Seq[Double] = ...
val bar : Seq[Double] = ...
and I wish to produce a seq where the baz(i) = foo(i) + bar(i). One way I can think of to do this is
val baz : Seq[Double] = (foo.toList zip bar.toList) map ((f: Double, b : Double) => f+b)
However, this feels both ugly and inefficient -- I have to convert both seqs to lists (which explodes with lazy lists), create this temporary list of tuples, only to map over it and let it be GCed. Maybe streams solve the lazy problem, but in any case, this feels like unnecessarily ugly. In lisp, the map function would map over multiple sequences. I would write
(mapcar (lambda (f b) (+ f b)) foo bar)
And no temporary lists would get created anywhere. Is there a map-over-multiple-lists function in Scala, or is zip combined with destructuring really the 'right' way to do this?
© Stack Overflow or respective owner