func half(n: Int): Result<Int, Str> {
if n % 2 == 0 {
return Result.Ok(n / 2)
}
return Result.Error("{n} is not even")
}
func describe(n: Int): Str {
answer := half(n)
if answer is Result.Ok(v) {
return "half: {v}"
} else if answer is Result.Error(why) {
return why
}
}
proc main(): void {
echo describe(4) // half: 2
echo describe(5) // 5 is not even
if half(40) is Result.Ok(v) && v > 10 {
echo "a big half: {v}"
}
}Result is how every fallible operation reports itself: Result.Ok(value) when it worked, Result.Error(payload) when it did not. It is the language's one built-in generic union, written Result<Int, Str> for an Int or a Str explaining why not.
r is Result.Ok(v) is a Bool that is true when r holds an Ok, and binds v to what it carries for the branch it guards, and for the rest of the same condition after &&. An if/else if chain testing one subject for both Ok and Error covers every case, so a function can end on it without a dead else. A branch that adds a condition of its own, answer is Result.Ok(v) && v > 10, covers nothing: it can be false with an Ok in hand. The slides on pattern matching show everything else is can do.