Presence
An int? holds either an int or nothing, and the program cannot do sums with it until it knows which. match is how you find out. It opens the optional and hands you what is inside — but only in the arm where something is actually there. Everything you learnt about patterns in Part 7 carries over, and if … is asks the same question when only one answer needs much code.
Two arms
The lesson's ScoreOf looks up the player wearing a number and returns their score, or none when nobody wears it. Opening its answer takes two arms:
match ScoreOf(players, number) {
.Some(score) => PrintLine("#{} scored {}", number, score),
none => PrintLine("#{} is not on the team", number)
}
| Arm | Taken when | Inside the arm |
|---|---|---|
.Some(score) => | the optional is present | score is the plain int it holds |
none => | the optional is absent | there is nothing to bind |
.Some(score) is a pattern, not a call. Read it as "a present …": "a present value, called score". An optional is a two-case type, much like a variant, and .Some is the name of its present case. The name inside the parentheses becomes an ordinary int, but only inside its own arm — there is no way to reach a score in the none arm, because there is none to reach.
if … is
When one case needs real work and the other little or none, a match can feel heavy. if … is tests the optional against the same pattern:
if ScoreOf(players, number) is .Some(score) {
PrintLine("#{} scored {}", number, score);
} else {
PrintLine("#{} is not on the team", number);
}
The pattern is the same .Some(score), and score exists only inside the braces that follow it. The else block plays the part of the none arm, and may be left out when absence needs nothing done.
Any pattern can be present
.Some(…) wraps any pattern, so a literal and a guard work as usual:
func Rating(players: Player[..], number: int) -> char8[..] {
return match ScoreOf(players, number) {
.Some(0) => "has not scored yet",
.Some(score) if score >= 20 => "is the top scorer",
.Some(_) => "is a regular",
none => "is not on the team"
};
}
.Some(0) is "a present 0", and .Some(_) is "present, whatever it holds". The arms are tried from the top, so the general .Some(_) arm comes after the specific ones, exactly as in Exhaustive.
flowchart LR
r["`ScoreOf(…)`"] --> q{"Present?"}
q -- "no" --> n["`none`<br/>is not on the team"]
q -- "yes" --> z{"Is it 0?"}
z -- "yes" --> a["`.Some(0)`<br/>has not scored yet"]
z -- "no" --> t{"`score >= 20?`"}
t -- "yes" --> b["`.Some(score) if …`<br/>is the top scorer"]
t -- "no" --> c["`.Some(_)`<br/>is a regular"]none cannot be forgotten
A match on an optional must be exhaustive, like a match on a variant — even when it is a statement. The none arm is required, because absence is the case the optional exists to make you handle, and so is an unguarded present arm. if … is needs no none arm, because the code after a false test simply carries on — or runs the else.
The program
The whole lesson is one package in the Examples repository. Its comments explain every step.
// An `int?` holds either an `int` or nothing, and the program cannot do sums
// with it until it knows which. `match` is how you find out. It opens the
// optional and hands you what is inside, but only in the arm where something
// is actually there.
//
// There are two arms to write:
//
// .Some(score) => ... present: `score` is the `int` inside
// none => ... absent: there is nothing to bind
//
// `.Some(score)` is a pattern, not a call. Read it as "a present ...". The
// name inside it becomes an ordinary `int`, but only inside its arm.
import Io::PrintLine;
struct Player {
number: int;
score: int;
}
// The score of the player wearing `number`, or `none` when nobody does.
func ScoreOf(players: Player[..], number: int) -> int? {
for player in players {
if player.number == number {
return player.score;
}
}
return none;
}
func Report(players: Player[..], number: int) {
match ScoreOf(players, number) {
.Some(score) => PrintLine("#{} scored {}", number, score),
none => PrintLine("#{} is not on the team", number)
}
}
// The same question with `if ... is`. The pattern is the same `.Some(score)`,
// and `score` exists only inside the braces that follow it; `else` is the
// `none` arm. It reads well when only one of the two cases needs much code.
func ReportIf(players: Player[..], number: int) {
if ScoreOf(players, number) is .Some(score) {
PrintLine("#{} scored {}", number, score);
} else {
PrintLine("#{} is not on the team", number);
}
}
// `.Some(...)` wraps any pattern, so a literal and a guard work as usual. The
// arms are tried from the top, so the general `.Some(score)` arm comes after
// the specific ones.
func Rating(players: Player[..], number: int) -> char8[..] {
return match ScoreOf(players, number) {
.Some(0) => "has not scored yet",
.Some(score) if score >= 20 => "is the top scorer",
.Some(_) => "is a regular",
none => "is not on the team"
};
}
func Main() -> int {
let players = [
Player { number: 4, score: 0 },
Player { number: 7, score: 12 },
Player { number: 10, score: 25 }
];
Report(players, 7);
Report(players, 9);
ReportIf(players, 10);
for number in [ 4, 7, 10, 9 ] {
let rating = Rating(players, number);
PrintLine("#{} {}", number, rating);
}
// Watch out: the `none` arm is required. If you leave it out, the
// compiler stops with "match on 'int?' is not exhaustive; missing none",
// because that is the case the optional exists to make you handle.
return 0;
}
Run it
cd Examples/Optionals/Presence
rux run
#7 scored 12
#9 is not on the team
#10 scored 25
#4 has not scored yet
#7 is a regular
#10 is the top scorer
#9 is not on the team
Common mistakes
Try it yourself
- Delete the
nonearm fromReportand read the error. - Give
Ratingan arm for players who scored exactly 1, reading"has scored once". Where does it go? - Write
Bench(players: Player[..], number: int) -> boolthat istruefor a player with no goals andfalseotherwise — including for numbers nobody wears. Try it once withmatchand once withif … is .Some(0).
Learn more
- Absence and presence patterns and
matchin the Rux Reference - Optional — what
int?is - Coalesce — when all you need is a fallback,
??is shorter than a match