Phil
Phil

Reputation: 50346

Simplest way to sum two Lists in Scala?

I have two lists, I want to sum each element in list A with the element in list B, producing a new list.

I can do it with:

List(1,2).zip(List(5,5)).map(t => t._1 + t._2)

Is there any simpler or neater way to do this in Scala?

In Clojure I can just do:

(map + [1 2 3] [4 5 6])

Upvotes: 19

Views: 13742

Answers (4)

ZhekaKozlov
ZhekaKozlov

Reputation: 39526

In Scalaz:

List(1,2) merge List(5,5)

Works also for lists with different sizes: List(1,2,3) merge List(5,5) will return List(6,7,3)

Upvotes: 0

thoredge
thoredge

Reputation: 12591

Another way to simplify:

import Function.tupled
List(1,2).zip(List(5,5)) map tupled {_ + _}

Upvotes: 3

Heiko Seeberger
Heiko Seeberger

Reputation: 3722

missingfaktor's answer is what I would have recommended, too.

But you could even improve your snippet to get rid of using the clumsy _1, _2:

List(1,2) zip List(5,5) map { case (a, b) => a + b }

Upvotes: 10

missingfaktor
missingfaktor

Reputation: 92016

For two lists:

(List(1,2), List(5,5)).zipped.map(_ + _)

For three lists:

(List(1,2), List(5,5), List(9, 4)).zipped.map(_ + _ + _)

For n lists:

List(List(1, 2), List(5, 5), List(9, 4), List(6, 3)).transpose.map(_.sum)

Upvotes: 45

Related Questions