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
for row <- rows yield row * 3walks the list and gathers each result into a new list.for row <- rows if row % 2 == 0 yield rowputs a guard after the generator, dropping the elements it rejects before the yield runs.- Two generators,
row <- rowsandtree <- List("plum", "quince"), nest to yield(row, tree)pairs, andfor tag <- Set(3, 1, 3) yield tag + 100gives back aSetbecause its first generator is one.
Keywords and builtins used here
IntListSetStringforifvalyield
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.
Step 3 of 3 in Transformations, step 15 of 27 in Language basics.