← Back to AILP Home

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

When to prefer when