when vs while
when is while plus a completion decision. Anywhere you would write a while
loop and then ask "did it finish, or did something bail out?", when expresses
that intent directly.
The pattern when replaces
Without when, you thread a boolean through the body:
// while + manual completion flag
bool:broke = false;
while (i < n) {
if (should_stop) {
broke = true;
break;
}
i = i + 1i32;
}
if (broke) {
// short-circuit handling
} else {
// clean-exit handling
}
The same logic with when:
when (i < n) {
if (should_stop) { break; }
i = i + 1i32;
} then {
// clean-exit handling
} end {
// short-circuit handling
}
The flag, the post-loop if, and the bookkeeping all collapse into the two
completion blocks. The compiler tracks the equivalent of broke (and the
completed flag for the zero-iteration case) for you.
Equivalence table
while idiom |
when equivalent |
|---|---|
clean exit handler (else branch of a post-loop flag check) |
then { ... } |
break / empty-loop handler (the flag's if branch) |
end { ... } |
| no post-loop handling | bare when (just use while) |
When to prefer while
- You have no completion handling at all — a bare
whenis just awhilewith extra keywords; usewhile. - You need a handler that runs on every exit regardless of how the loop
stopped — put it after the loop, not in
then/end(remember the zero-iteration case routes toend, see then and end semantics).
When to prefer when
- You branch on "completed vs cut short" after the loop.
- You want loan scoping for the two paths handled separately (a borrow in
thenand one inendnever conflict). - You want the early-exit handling to sit visually adjacent to the loop rather
than in a detached post-loop
if.