Michael
Michael

Reputation: 42100

How to sum a few vectors in Scala?

Suppose I need to sum three vectors:

val sum3: (Vector[Int], Vector[Int], Vector[Int]) => Vector[Int] = (v1, v2, v3) => 
  (v1 zip v2 zip v3) map {case ((x1, x2), x3) => x1 + x2 + x3}

if I am summing 5-6 vectors this way I am ending up with 4-5 nested tuples. Is there a better way to sum a few vectors ?

Upvotes: 1

Views: 1123

Answers (2)

Victor Moroz
Victor Moroz

Reputation: 9225

Beware of memory allocation, depending on your vector size it may not be what you want. One way to avoid it is to go fully imperative or do something like this:

def sum(v: Vector[Int], vs: Vector[Int]*): Vector[Int] = {
  val ixs = 0 until v.length
  for {
    _ <- v.slice(0, 1) // Hint for CanBuildFrom
    ix <- ixs
  } yield vs.foldLeft(v(ix))(_ + _(ix))
}

scala> sum(Vector(1,2,3), Vector(4,5,6), Vector(7, 8, 9))
res0: Vector[Int] = Vector(12, 15, 18)

Upvotes: 1

Pascal Soucy
Pascal Soucy

Reputation: 1317

Vector(v1, v2, v3).transpose.map(_.sum)

Upvotes: 5

Related Questions