LYR-SEM0149
a 'loop' whose breaks give a value only in part
Some 'break's of one 'loop' carry a value and others carry none.
Explanation
The value of a loop is the value of the break that ends it. If one break gives a value and another gives none, the loop's value would be missing on one path. A loop gives a value through every break or through none.
Give every break a value — a sentinel or an optional (break null; with ?int) for the case without one — or give none and use a variable.
Wrong
fn indexOf(xs: int[], wanted: int): int {
var i = 0;
let at = loop {
if (i == xs.length()) { break; }
if (xs[i] == wanted) { break i; }
i += 1;
};
return at;
}
fn main(): void {
let _ = indexOf([1, 2], 2);
}
Right
fn indexOf(xs: int[], wanted: int): int {
var i = 0;
let at = loop {
if (i == xs.length()) { break -1; }
if (xs[i] == wanted) { break i; }
i += 1;
};
return at;
}
fn main(): void {
let _ = indexOf([1, 2], 2);
}