Examples · 24 of 339
24-patterns
Nested patterns.
tin run examples/24-patterns.tin// Nested patterns. Any field or value inside a pattern is itself a pattern: a variant,
// a literal, a name or _. The compiler checks that a match covers every case, however deep,
// and names the one you forgot.
//
// tin run examples/24-patterns.tin
type Reading = | Value(float) | TooLow | TooHigh | Offline { since: int }
type Cmd =
| Move { dx: int, dy: int }
| Grip(bool)
| Stop
fn describe(r: Result<Reading, string>): string => match r {
Ok(Value(v)) => "reading {v}"
Ok(TooLow) => "below range"
Ok(TooHigh) => "above range"
Ok(Offline { since: 0 }) => "never connected"
Ok(Offline { since }) => "offline since tick {since}"
Err(why) => "sensor error: {why}"
}
fn plan(c: Cmd): string => match c {
Move { dx: 0, dy: 0 } => "stay"
Move { dx: 0, dy } => "vertical {dy}"
Move { dx, dy: 0 } => "horizontal {dx}"
Move { dx, dy } => "diagonal {dx},{dy}"
Grip(true) => "close the gripper"
Grip(false) => "open the gripper"
Stop => "stop"
}
fn main() {
let readings: Result<Reading, string>[] = [Ok(Value(21.5)), Ok(TooHigh), Ok(Offline { since: 0 }), Ok(Offline { since: 42 }), Err("bus timeout")]
for r in readings { print(describe(r)) }
for c in [Move { dx: 0, dy: 0 }, Move { dx: 0, dy: 3 }, Move { dx: 2, dy: 2 }, Grip(true), Stop] { print(plan(c)) }
} reading 21.5
above range
never connected
offline since tick 42
sensor error: bus timeout
stay
vertical 3
diagonal 2,2
close the gripper
stop