raoulsson
raoulsson

Reputation: 16355

Iterating over more than three arrays in Scala

I have to turn a bunch of silly comma separated Strings into, finally, Objects. I first split the strings to Arrays. Then I need to iterate over all of them simultaneously and build an Object out of the four values.

val s1 = Array(1,2,3)
val s2 = Array("a","b","c")
val s3 = Array(10,20,30)
val s4 = Array("u","v","w")

The target Object looks like this:

case class Data(a: Int, b: String, c: Int, d: String)

The first Data object has to print

Data(1,a,10,u)

And so on. I found a solution for three items:

(s1, s2, s3).zipped foreach { (v1, v2, v3) =>
  println(v1, v2, v3)
}

Which prints:

(1,a,10)
(2,b,20)
(3,c,30)

With four arrays or more, this won't do it. Zipped is not defined for a 4-tuple:

error: value zipped is not a member of (Array[Int], Array[String], Array[Int], Array[String])

My Scala is a bit rusty so maybe I am missing the obvious (like an iteration with index or something).

Upvotes: 4

Views: 1282

Answers (4)

Rex Kerr
Rex Kerr

Reputation: 167871

Use indices?

for (i <- 0 until Seq(s1,s2,s3,s4).map(_.length).min)
yield Data(s1(i), s2(i), s3(i), s4(i))

This scales arbitrarily far, and handles length mismatches in the same way as zip/zipped (by truncation).

Upvotes: 5

pagoda_5b
pagoda_5b

Reputation: 7373

Similar to Marius Danila answer

val zipped = (s1 zip s2 zip s3 zip s4) map {
  case (((a, b), c), d) => Data(a, b, c, d)
}

Upvotes: 1

om-nom-nom
om-nom-nom

Reputation: 62835

It is not pretty, but should work (with arbitrary amount of row-lenghts)

val items: Array[Array[Any]] = Array (
  Array(1,2,3),
  Array("a","b","c"),
  Array(10,20,30),
  Array("u","v","w")
)

items.transpose.map {
  case Array(a: Int, b: String, c: Int, d: String) => Data(a,b,c,d)
}
// Array(Data(1,a,10,u), Data(2,b,20,v), Data(3,c,30,w))

Upvotes: 10

Marius Danila
Marius Danila

Reputation: 10401

This should do it:

((s1, s2, s3).zipped, s4).zipped foreach { case ((v1, v2, v3), v4) =>
  println(v1, v2, v3, v4)
}

Upvotes: 3

Related Questions