ceylon/ceylon-spec — Issue #117: Changes to the `for` loop
Author: FroMage
Created: 2011-12-21 10:05:33+00:00
State: open
Labels: improvement, request for feedback

As mentioned on the mailing list, I think we should change our `for` loop a bit to better take care of two common use cases:

- iterating over a sequence to find one element
- dealing with empty sequences

The first case can be handled with the following syntax:

```java
for(n in seq){
if(n == 2){
// we found it!
break;
}
} then {
// we didn't find it
}
```

Where the `then` block is the same as the current `else` block, in the sense that it's only executed if you don't exit the loop prematurely with `break`, and it's also executed if the sequence is empty, because that's also a case of the element not being found.

The last use-case can be handled by the following syntax:

```java
for(n in seq){
// do something
} else {
// sequence was empty
}
```

Which is more what people expect of an `else` clause, and solves a very common use-case that would otherwise require every `for` loop where you care about empty sequences with an `if` that looks very boilerplaty.

As to whether to make the `then` and `else` block mutually exclusive or not, preventing them from both appearing on the same `for` loop makes sure that both branches can't be evaluated (on empty sequence) because that looks weird. And I don't quite see a use-case for wanting both.

What do you think?