I would like to create a collection with tuples containing all pairwise combinations of two lists. Something like:
for ( x <- xs )
for ( y <- ys )
yield (x,y)
In Python this would work, in Scala apparently for
yields only for the last loop (so this evaluates to Unit
)
What is the cleanest way to implement it in Scala?
You were almost there:
scala> val xs = List (1,2,3)
xs: List[Int] = List(1, 2, 3)
scala> val ys = List (4,5,6)
ys: List[Int] = List(4, 5, 6)
scala> for (x <- xs; y <- ys) yield (x,y)
res3: List[(Int, Int)] = List((1,4), (1,5), (1,6), (2,4), (2,5), (2,6), (3,4), (3,5), (3,6))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With