Examples · 3 of 339
03-shapes
Sum types and exhaustive match.
tin run examples/03-shapes.tin// Sum types and exhaustive `match`.
// Remove an arm below and the compiler tells you which shape you forgot.
type Shape =
| Circle { r: float }
| Rect { w: float, h: float }
| Triangle { base: float, height: float }
fn area(s: Shape): float => match s {
Circle { r } => PI * r * r
Rect { w, h } => w * h
Triangle { base, height } => base * height / 2
}
fn describe(s: Shape): string => match s {
Circle { r } => "a circle of radius {r}"
Rect { w, h } => if w == h { "a {w} square" } else { "a {w} by {h} rectangle" }
Triangle { base, height } => "a triangle {base} wide and {height} tall"
}
fn main() {
let shapes = [
Circle { r: 1.0 },
Rect { w: 3.0, h: 4.0 },
Rect { w: 2.0, h: 2.0 },
Triangle { base: 6.0, height: 2.0 },
]
for s in shapes {
print("{describe(s)} has area {area(s).fixed(2)}")
}
let total = shapes |> map(area) |> sum
print("total: {total.fixed(2)}")
} a circle of radius 1.0 has area 3.14
a 3.0 by 4.0 rectangle has area 12.00
a 2.0 square has area 4.00
a triangle 6.0 wide and 2.0 tall has area 6.00
total: 25.14