typestar

For comprehensions in Scala

Orchard rows turned into new collections with for and yield.

// for-yield walks a collection and builds a new one from the results
val rows: List[Int] = List(1, 2, 3, 4)
val spaced: List[Int] = for row <- rows yield row * 3

// a guard sits after the generator and drops what it rejects
val evenRows: List[Int] = for row <- rows if row % 2 == 0 yield row

// two generators nest, the second running once per outer element,
// and the yield sees both bindings at once
val plots: List[(Int, String)] =
  for
    row <- rows
    tree <- List("plum", "quince")
  yield (row, tree)

// the result follows the first generator, so a Set yields a Set
val grafts: Set[Int] = for tag <- Set(3, 1, 3) yield tag + 100

How it works

  1. for row <- rows yield row * 3 walks the list and gathers each result into a new list.
  2. for row <- rows if row % 2 == 0 yield row puts a guard after the generator, dropping the elements it rejects before the yield runs.
  3. Two generators, row <- rows and tree <- List("plum", "quince"), nest to yield (row, tree) pairs, and for tag <- Set(3, 1, 3) yield tag + 100 gives back a Set because its first generator is one.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
632
Tokens
112
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 90 seconds.

Type this snippet

Step 3 of 3 in Transformations, step 15 of 27 in Language basics.

← Previous Next →