Loops
Loops have four entry points: for iterates over iterable values, while over a condition, while val over a conditional binding, and repeat over a fixed count. The ways out are uniformly break and continue; complex nesting uses a label to name the jump target.
for
for pattern in iterable takes the elements one by one. The iteration-variable slot is a pattern, so it can destructure directly:
var sum = 0;
for i in 1..=10
{
sum += i;
}
print("sum", sum);sum 55Ranges are half-open or closed: 1..5 walks 1 through 4, 1..=5 walks through 5. Stepped iteration uses the step soft keyword:
for i in 0..10 step 3
{
print("step", i);
}step 0
step 3
step 6
step 9The iterated object is an Iterator-implementing collection, array, range, or string. Iteration over lists and maps is covered on the containers page in the Types part.
when Guards
for can carry a when condition; elements that fail it are skipped outright, equivalent to an if on the first line of the body:
for i in 1..=6 when i % 2 == 0
{
print("even", i);
}even 2
even 4
even 6repeat
A fixed-count loop, handy when no loop variable is needed:
repeat 3
{
print("knock");
}knock
knock
knockThe parenthesized form repeat (3) is equivalent.
while and while val
while cond tests the condition before each round. while val pattern = expression is a conditional-binding loop: each round re-evaluates the expression, tests and binds by the pattern, and exits when the match fails:
var n = 1;
while n < 100
{
n *= 3;
}
print("n", n);
var maybe: int? = 3;
var rounds = 0;
while val v = maybe
{
rounds += 1;
if v <= 1
{
maybe = null;
}
else
{
maybe = v - 1;
}
}
print("rounds", rounds);n 243
rounds 3Inside the loop body, v is narrowed to int. Once maybe is set to null, the next round’s match fails and the loop ends. while var works the same way.
break, continue, and Labels
break leaves the innermost loop; continue skips the rest of the round. To jump across levels in nested loops, put label name on the outer loop and give break / continue the same label to jump straight to it:
for i in 1..=3 label Outer
{
for j in 1..=3
{
if j == 2
{
continue;
}
if i == 2
{
break Outer;
}
print(i, j);
}
}1 1
1 3When i is 2, break Outer terminates both loops on the spot; the later 3 1 and 3 3 never run.
Notes
- Range literals are printable:
print(1..5)outputs1..5. - The while condition likewise accepts only a bool.
- Loop variables are invisible outside the loop; to carry a result out, accumulate it into an outer variable, like
sumabove.
