scala: yield pairwise combinations of two loops

11,801

Solution 1

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))

Solution 2

A little bit more explicit according to Nicolas:
In Scala you can use multiple generators in a single for-comprehension.

val xs = List(1,2,3)
val ys = List(4,5)

for {
  x <- xs
  y <- ys
} yield (x,y)

res0: List[(Int, Int)] = List((1,4), (1,5), (2,4), (2,5), (3,4), (3,5))

You can even evaluate in the comprehension.

for {
  x <- xs
  y <- ys
  if (x + y == 6)
} yield (x,y)

res1: List[(Int, Int)] = List((1,5), (2,4))

Or make an assignment.

for {
  x <- xs
  y <- ys
  val z = x + y
} yield (x,y,z)

res2: List[(Int,Int,Int)] = List((1,4,5), (1,5,6), (2,4,6), (2,5,7), (3,4,7), (3,5,8))
Share:
11,801

Related videos on Youtube

Jakub M.
Author by

Jakub M.

Updated on September 14, 2022

Comments

  • Jakub M.
    Jakub M. over 1 year

    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?

    • Didier Dupont
      Didier Dupont over 11 years
      Nicolas's answer is the correct one, but note that for evaluates to Unit only when there is no yield. Check for(x <- xs) yield for (y <- ys) yield (x,y), it returns something interesting, but not exactly what you wants.
  • Jakub M.
    Jakub M. over 11 years
    And what if I would like to loop xs and ys and increment come counter cnt at every iteration? Like: for(x<-xs; y<-ys; cnt++) yield(x,y,cnt) ?
  • tgr
    tgr over 11 years
    val concatenator = for { x <- xs, y <- ys } yield (x, y); concatenator.zipWithIndex. You might flatten this result but it is counted.
  • Alex
    Alex over 11 years
    for- comprehensions are cool, i am discovering them for myself as well, and really like them especially with scalaz's validations