JetBrains/kotlin — pull request #525 by jgl87 (2014-11-08 04:21:58+00:00)
Title: For-Comprehensions: Basic Support

This PR introduces basic support of for-comprehensions as well as for-expressions with multiple clauses. Here is a brief summary.

### Syntactic changes ###
There are two major syntactic changes. First, for-expressions support multiple clauses each having distinct parameter(s) and range:
``` kotlin
for (i in 1..10, j in 1..i) sum += i*j
```
Individual clauses are separated with commas.

Second, there is a new kind of expression signified by ```yield``` keyword (soft):
``` kotlin
yield foo(i)
```
or
``` kotlin
yield {
doSomething()
foo(i)
}
```
Preceding the body with ```yield``` turns for-statement to expression (for-comprehension) which can be passed around like any other expression with value, e.g.
``` kotlin
val list = for (i in 1..5, j in i..i*2) yield i + j
```

### Multi-clause For Iteration Semantics ###
If a given for-expression is not a comprehension, its multiple clauses basically correspond to the nested sequence of single-claused for-expressions. Namely,

``` kotlin
for (clause1,..., clauseN) e
```

is replaced with

``` kotlin
for (clause1)
...
for (clauseN) e
```

### For Comprehension Semantics ###
Semantics of for-comprehensions is defined by recursive transformation to calls involving map()/flatMap() operations.

1) Single-clause expression of the form
``` kotlin
for (p in a) yield e
```
is transformed to
``` kotlin
a.map { p -> e }
```

Similarly, single-clause expression of the form
``` kotlin
for (val (p1,...,pN) in a) yield e
```
is transformed to
``` kotlin
a.map { q ->
val (p1,...,pN) = q
e
}
```
where ```q``` is a fresh name which does not occur in the enclosing scope of for-expression

2) Multiple-clause expression of the form
``` kotlin
for (i in a, clause1,..., clauseN) yield e
```
is transformed to
``` kotlin
a.flatMap { i -> for (clause1,..., clauseN) yield e }
```
Multi-declaration case is treated in a similar fashion

P.S. **Happy birthday**, by the way!