Wei Ma
Wei Ma

Reputation: 3165

Scala add contents of two lists

For the first assignment for the course https://www.coursera.org/course/progfun I would like to do the following

   val l1 = List(1,2,3)
   val l2 = List(4,5,6)

   val lSum = l1.someOperation(l2)
   RES: lSum=List(5,7,9)  

I could implement someOperation with a loop, but that does not look very scalarish, I am wondering if there is a built in function to achieve this.

Upvotes: 1

Views: 877

Answers (3)

Seth Tisue
Seth Tisue

Reputation: 30508

In addition to zip, the standard library also supplies zipped which avoids the need to deconstruct any tuples:

(l1, l2).zipped.map(_ + _)

Upvotes: 9

Jörg W Mittag
Jörg W Mittag

Reputation: 369594

This is probably more Scalaish than @om-nom-nom's code. Although Scala is, as languages go, still pretty young, so there is actually still debate about what actually is and isn't Scalaish:

l1 zip l2 map { case (a, b) => a + b }

Upvotes: 1

om-nom-nom
om-nom-nom

Reputation: 62855

You may zip them and perform addition as usually in map:

l1.zip(l2).map(x => x._1 + x._2)

Upvotes: 6

Related Questions