python uses for in list expressions and generator expressions. They are very similar to the scala for expression:
this is python
>>> letters = ['a', 'b', 'c', 'd'] >>> ints = [0, 1, 2, 3] >>> [l + str(i) for l in letters for i in ints if i % 2 == 0] ['a0', 'a2', 'b0', 'b2', 'c0', 'c2', 'd0', 'd2']
this is scala
scala> val letters = List('a', 'b', 'c', 'd') scala> val ints = List(0, 1, 2, 3) scala> for (l <- letters; i <- ints if i % 2 == 0) yield l.toString + i res0: List[java.lang.String] = List(a0, a2, b0, b2, c0, c2, d0, d2)
Each construct can take several generators / iterators, apply filter expressions and give a combined expression. In python (expr for v1 in gen1 if expr1 for v2 in gen2 if expr2) roughly equivalent:
for v1 in gen1: if expr1: for v2 in gen2: if expr2: yield expr
In scala for (v1 <- gen1 if expr1; v2 <- gen2 if expr2) yield expr roughly equivalent:
gen1.withFilter(expr1).flatMap(v1 => gen2.withFilter(expr2).map(v2 => expr))
If you like the python for x in xs syntax, you will most likely like the scala for expression.
Scala has some additional syntax and translation twists. The wise for syntax can be used with curly braces so you can put statements on separate lines. You can also perform value assignments.
val res = for { i <- 1 to 20; i2 = i*i j <- 1 to 20; j2 = j*j k <- 1 to 20; k2 = k*k if i2 + j2 == k2 } yield (i, j, k)
Also v1 <- gen1 does indeed match case v1 => gen1 . If there is no match, these elements are ignored in the iteration.
scala> val list = List(Some(1), None, Some(2)) scala> for (Some(i) <- list) yield i res2: List[Int] = List(1, 2)
I think that for occupies an important place in this language. I can tell from the fact that in this book you read the whole chapter (23)!