0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Multiple Generators

Nested iteration.

Multiple Generators is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Nested iteration made flat

A for-comprehension can have several generators. Each one is a <- line that iterates over a collection. Together they produce every combination, a kind of nested loop written flatly.

object Main {
  def main(args: Array[String]): Unit = {
    val pairs = for {
      x <- List(1, 2)
      y <- List('a', 'b')
    } yield (x, y)
    println(pairs)
  }
}

It is a cartesian product

Two generators of sizes m and n produce m × n results, the full cartesian product. The first generator is the outer loop, the second the inner loop.

object Main {
  def main(args: Array[String]): Unit = {
    val grid = for {
      row <- 1 to 3
      col <- 1 to 3
    } yield s"r$row-c$col"
    println(grid.mkString(", "))
  }
}

Inner generator can depend on outer

A later generator can use values bound by earlier ones. This is impossible with a plain cartesian product and is one reason for-comprehensions are so flexible.

object Main {
  def main(args: Array[String]): Unit = {
    val upperTriangle = for {
      i <- 1 to 4
      j <- i to 4
    } yield (i, j)
    println(upperTriangle)
  }
}

Three or more generators

You can stack as many generators as you like. With three generators you get a triple-nested loop, producing tuples or computed values.

object Main {
  def main(args: Array[String]): Unit = {
    val triples = for {
      a <- 1 to 2
      b <- 1 to 2
      c <- 1 to 2
    } yield (a, b, c)
    println(triples.size + " combinations")
    triples.foreach(println)
  }
}

The classic Pythagorean example

A famous use: find Pythagorean triples. We iterate three numbers and keep only those where a*a + b*b == c*c, combining multiple generators with a guard.

object Main {
  def main(args: Array[String]): Unit = {
    val triples = for {
      a <- 1 to 20
      b <- a to 20
      c <- b to 20
      if a * a + b * b == c * c
    } yield (a, b, c)
    triples.foreach(println)
  }
}

How it desugars

Multiple generators become nested flatMap calls with a final map:

  • xs.flatMap(x => ys.flatMap(y => zs.map(z => ...)))

Each extra generator adds one more nested level.

object Main {
  def main(args: Array[String]): Unit = {
    val sugar = for {
      x <- List(1, 2)
      y <- List(3, 4)
    } yield x * y
    val desugared = List(1, 2).flatMap(x => List(3, 4).map(y => x * y))
    println(sugar == desugared)
  }
}

Mixing generators and guards

You can interleave generators and guards freely. A guard placed between two generators prunes outer values before the inner loop even runs.

object Main {
  def main(args: Array[String]): Unit = {
    val result = for {
      x <- 1 to 5
      if x % 2 == 1
      y <- 1 to 5
      if y > x
    } yield (x, y)
    println(result)
  }
}

Flattening nested collections

When you have a collection of collections, two generators flatten it naturally: the first iterates the outer, the second iterates each inner.

object Main {
  def main(args: Array[String]): Unit = {
    val matrix = List(List(1, 2), List(3, 4), List(5, 6))
    val flat = for {
      row <- matrix
      value <- row
    } yield value
    println(flat)
  }
}

Building a string grid

Multiple generators are great for generating structured output, like coordinates or a multiplication table.

object Main {
  def main(args: Array[String]): Unit = {
    val table = for {
      i <- 1 to 3
      j <- 1 to 3
    } yield s"$i*$j=${i * j}"
    println(table.grouped(3).map(_.mkString("  ")).mkString("\n"))
  }
}

Combining different collection sizes

Generators need not be the same length. Each combination of one element from each is produced.

object Main {
  def main(args: Array[String]): Unit = {
    val sizes = List("S", "M", "L")
    val colors = List("red", "blue")
    val products = for {
      s <- sizes
      c <- colors
    } yield s"$c-$s"
    println(products)
  }
}

Order affects the output sequence

Swapping generator order keeps the same set of combinations but changes their order, because the last generator varies fastest.

object Main {
  def main(args: Array[String]): Unit = {
    val ab = for { x <- List(1, 2); y <- List(9, 8) } yield (x, y)
    val ba = for { y <- List(9, 8); x <- List(1, 2) } yield (x, y)
    println(ab)
    println(ba)
  }
}

Quick Check

How many tuples does for { x <- List(1,2,3); y <- List('a','b') } yield (x, y) produce?

Recap

You learned about multiple generators:

  • Each <- line adds a level of nested iteration
  • Together they produce the cartesian product
  • Inner generators can depend on outer bound values
  • They desugar to nested flatMap + a final map
  • Generator order changes the result ordering

Frequently asked questions

Is the “Multiple Generators” lesson free?

Yes — the full text of “Multiple Generators” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.

What will I learn in “Multiple Generators”?

Nested iteration. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Scala for Backend Engineering & Functional Programming?

No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Multiple Generators” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?

Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Desugaring for
  2. Filtering with if
  3. Multiple Generators
  4. Using with Option and Future
← Back to Scala for Backend Engineering & Functional Programming