Nested optional
A player who has not played yet has no score, so this lesson's team sheet stores each score as an int?. Now look a player up by number. The answer can be missing for two quite different reasons — nobody wears that number, or the player exists but has no score yet. An optional of an optional, int??, keeps the two apart.
Three answers, one type
struct Player {
number: int;
score: int?;
}
A lookup that returns the player's score must also be able to say "not found", so its result wraps the int? in one more optional:
flowchart TD
r["`int??`"] --> n["`none`<br/>nobody wears that number"]
r --> s["`.Some(…)` — the player exists"]
s --> sn["`.Some(none)`<br/>no score yet"]
s --> ss["`.Some(.Some(score))`<br/>has scored"]Rux never squashes the two levels into one. In some languages "a missing missing value" collapses into plain "missing", and the difference is lost; here the two kinds of "nothing" stay different, and you can tell them apart.
Building one
player.score is an int?. Returned where an int?? is expected it becomes a present int?? on its own, even when the score inside is none — the same rule that turned an int into a present int? in Optional. Only the none at the bottom means "not found":
func ScoreOf(players: Player[..], number: int) -> int?? {
for player in players {
if player.number == number {
return player.score;
}
}
return none;
}
Opening one, level by level
Each .Some(…) in a pattern opens one level:
match ScoreOf(players, number) {
.Some(.Some(score)) => PrintLine("#{} scored {}", number, score),
.Some(none) => PrintLine("#{} has not played yet", number),
none => PrintLine("#{} is not on the team", number)
}
| Pattern | Meaning |
|---|---|
.Some(.Some(score)) | a present, present score |
.Some(none) | a present none: found, but no score yet |
none | the outer absence: not on the team |
The nesting in the pattern mirrors the nesting in the type: two .Somes for two levels.
The same three cases with is
ReportIf asks the same questions as a chain of if … is tests. The answer is looked up once and kept, and each test opens the levels just as the arms do:
let found = ScoreOf(players, number);
if found is .Some(.Some(score)) {
PrintLine("#{} scored {}", number, score);
} else if found is .Some(none) {
PrintLine("#{} has not played yet", number);
} else {
PrintLine("#{} is not on the team", number);
}
The final else is the outer none: by then both other cases have been ruled out.
?? opens one level too
?? removes exactly one level, so on an int?? its result is still an int?:
let once = ScoreOf(players, 9) ?? 0;
let twice = once ?? 0;
For #9 the outer level is present, so the fallback is not used, and once is the inner none. A second ?? deals with that one, and twice is a plain int, 0.
That first ?? 0 looks as if it gives an int, and it does compile — but only because the 0 is made into a present int? to match the inner level. once is an int?, which is why the program compares it with none instead of printing it.
The program
The whole lesson is one package in the Examples repository. Its comments explain every step.
// A player who has not played yet has no score, so the team sheet stores each
// score as an `int?`. Now look a player up by number. The answer can be
// missing for two different reasons:
//
// none nobody wears that number
// .Some(none) the player exists, but has no score yet
// .Some(.Some(score)) the player exists and has scored
//
// The type that holds all three is `int??`, an optional of an optional. Rux
// never squashes the two levels into one, so the two kinds of "nothing" stay
// different and you can tell them apart.
import Io::PrintLine;
struct Player {
number: int;
score: int?;
}
// `player.score` is an `int?`. Returned from here it becomes a present `int??`
// on its own, even when the score inside is `none`. Only the `none` at the
// bottom means "not found".
func ScoreOf(players: Player[..], number: int) -> int?? {
for player in players {
if player.number == number {
return player.score;
}
}
return none;
}
// Each `.Some(...)` in a pattern opens one level. `.Some(.Some(score))` is "a
// present, present score". `.Some(none)` is "a present `none`": the player was
// found but has no score. Plain `none` is the outer absence.
func Report(players: Player[..], number: int) {
match ScoreOf(players, number) {
.Some(.Some(score)) => PrintLine("#{} scored {}", number, score),
.Some(none) => PrintLine("#{} has not played yet", number),
none => PrintLine("#{} is not on the team", number)
}
}
// The same three cases as a chain of `is` tests. The answer is looked up
// once and kept, and each test opens the levels the same way the arms do.
func ReportIf(players: Player[..], number: int) {
let found = ScoreOf(players, number);
if found is .Some(.Some(score)) {
PrintLine("#{} scored {}", number, score);
} else if found is .Some(none) {
PrintLine("#{} has not played yet", number);
} else {
PrintLine("#{} is not on the team", number);
}
}
func Main() -> int {
let players = [
Player { number: 7, score: 12 },
Player { number: 9, score: none }
];
Report(players, 7);
Report(players, 9);
Report(players, 3);
ReportIf(players, 9);
// `??` opens just one level too. For #9 the outer level is present, so
// the fallback is not used and `once` is the inner `none`, still an
// `int?`. A second `??` deals with that one.
let once = ScoreOf(players, 9) ?? 0;
let twice = once ?? 0;
PrintLine("#9 opened once is still none: {}", once == none);
PrintLine("#9 opened twice: {}", twice);
// Watch out: that first `?? 0` looks as if it gives an `int`, and it does
// compile, but only because the `0` is made into a present `int?` to
// match the inner level. Try printing `once` directly: the compiler
// refuses, because an `int?` is not something `PrintLine` can show.
return 0;
}
Run it
cd Examples/Optionals/NestedOptional
rux run
#7 scored 12
#9 has not played yet
#3 is not on the team
#9 has not played yet
#9 opened once is still none: true
#9 opened twice: 0
Common mistakes
Try it yourself
- Add a player
Player { number: 11, score: 0 }and check that #11 is reported as having scored 0, not as "has not played yet". - Write
Played(players: Player[..], number: int) -> bool?that isnonefor an unknown number, andtrueorfalseotherwise. - Replace the three-arm match with
??: print-1for "not on the team" and0for "has not played yet".
Learn more
- Presence — the one-level patterns
.Some(score)andnone - Optional pointer — the same care with
(*T)?and*T?, in the Memory part - Nested fallible — an optional result from a function that throws,
-> int? throws E, in the Errors part
8.5 Optional propagate
Pass absence up to the caller with ? in a function that returns an optional.
Overview
Operations that can fail: -> T throws E. Sixteen lessons on throwing an error with throw, handling it with try and catch, passing it on with plain try, designing error types, and stopping the program with Panic and Assert when only a bug could be to blame.