Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala: yield pairwise combinations of two loops

Tags:

scala

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?

like image 664
Jakub M. Avatar asked Jul 30 '12 12:07

Jakub M.


1 Answers

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))
like image 186
Nicolas Avatar answered Nov 15 '22 23:11

Nicolas