Learn Tin · Part 1: The language · Chapter 6
Sum types and match
A value that is one of several shapes, and a match that handles every one.
A value that is one of several
A struct is "this and that". A sum type is "this or that": the type lists every possible
case, separated by |, and a value is exactly one of them. Other languages call these enums or
tagged unions.
tin run simple.tin// A sum type: a value that is exactly one of these.
type Light = | Red | Amber | Green
fn next(l: Light): Light => match l {
Red => Green
Green => Amber
Amber => Red
}
fn main() {
var light = Red
for i in 0..4 {
print(light)
light = next(light)
}
} Red
Green
Amber
Red match looks at a value and runs the arm for its case. Like if, it is an
expression, so next is just the match.
The compiler checks every case
A match must handle every case. Forget one and the program doesn't compile, and the error
names the case you missed:
tin check forgot.tintype Light = | Red | Amber | Green
fn action(l: Light): string => match l {
Red => "stop"
Green => "go"
}
fn main() {
print(action(Amber))
} error: match is not exhaustive: missing Amber
--> forgot.tin:3:32
|
3 | fn action(l: Light): string => match l {
| ^^^^^^^^^
= note: add the missing arms, or a catch-all `_ => ...`
= fix: add an arm for Amber This is the real reason to use sum types. When you add a fourth light later, the compiler lists every
match in the program that needs a new arm. There is no case you forget to handle.
Cases that carry data
Each case can carry its own fields. A circle has a radius and a rectangle has a width and a height,
and the match arm takes them out by name:
tin run payload.tin// Each variant can carry its own data.
type Shape =
| Circle { radius: float }
| Rect { width: float, height: float }
| Point
fn area(s: Shape): float => match s {
Circle { radius } => PI * radius * radius
Rect { width, height } => width * height
Point => 0.0
}
fn main() {
print(area(Circle { radius: 1.0 }))
print(area(Rect { width: 2.0, height: 3.0 }))
print(area(Point))
} 3.141592653589793
6.0
0.0 For one or two values, positions are often clearer than names:
tin run positional.tin// Variants can also carry values by position, like a function call.
type Command = | Move(int, int) | Say(string) | Quit
fn run(c: Command): string => match c {
Move(dx, dy) => "move by ({dx}, {dy})"
Say(text) => "say '{text}'"
Quit => "bye"
}
fn main() {
print(run(Move(3, -1)))
print(run(Say("hello")))
print(run(Quit))
} move by (3, -1)
say 'hello'
bye Matching numbers and strings
match also compares against plain values. There are endless ints and strings, so these need a
final catch-all arm: _ matches anything, and a name matches anything and keeps the value.
tin run values.tin// match works on ints and strings too. _ matches anything else.
fn dayName(n: int): string => match n {
0 => "Sunday"
6 => "Saturday"
_ => "a weekday"
}
fn reply(word: string): string => match word {
"hi" => "hello!"
"bye" => "see you"
other => "I don't know '{other}'" // a name also matches anything, and keeps the value
}
fn main() {
print(dayName(6))
print(dayName(3))
print(reply("hi"))
print(reply("thanks"))
} Saturday
a weekday
hello!
I don't know 'thanks' Guards
An arm can add if condition. It matches only when the condition is true, otherwise
match tries the next arm. Arms are tried from top to bottom.
tin run guards.tintype Reading = | Temp(float) | Offline
fn describe(r: Reading): string => match r {
Temp(c) if c > 30.0 => "hot: {c}" // a guard: this arm matches only when it holds
Temp(c) if c < 5.0 => "cold: {c}"
Temp(c) => "fine: {c}"
Offline => "no data"
}
fn main() {
print(describe(Temp(34.5)))
print(describe(Temp(1.0)))
print(describe(Temp(20.0)))
print(describe(Offline))
} hot: 34.5
cold: 1.0
fine: 20.0
no data Tasks
●○○ Task 1: Count the coins
Declare Coin with Penny, Nickel, Dime and
Quarter, write cents(c: Coin): int, and add up a quarter, two dimes and a penny.
Solution
tin run task-1.solution.tintype Coin = | Penny | Nickel | Dime | Quarter
fn cents(c: Coin): int => match c {
Penny => 1
Nickel => 5
Dime => 10
Quarter => 25
}
fn main() {
var total = 0
for c in [Quarter, Dime, Dime, Penny] {
total += cents(c)
}
print("{total} cents")
} 46 cents ●●● Task 2: A tiny calculator
Declare Expr: a number, the sum of two expressions, or the product of two expressions. Yes,
a case can contain the type itself. Write eval and compute (1 + 2) * 4.
Solution
tin run task-2.solution.tin// A sum type can contain itself: an expression is a number, or two expressions combined.
type Expr =
| Num(int)
| Add(Expr, Expr)
| Mul(Expr, Expr)
fn eval(e: Expr): int => match e {
Num(n) => n
Add(a, b) => eval(a) + eval(b)
Mul(a, b) => eval(a) * eval(b)
}
fn main() {
print(eval(Num(7)))
print(eval(Add(Num(2), Num(3))))
// (1 + 2) * 4
print(eval(Mul(Add(Num(1), Num(2)), Num(4))))
} 7
5
12 Because Add holds two Exprs, eval calls itself
on each one. Every compiler starts out with a type like this one, Tin's included.
●●○ Task 3: Grades with guards
Write grade(score: int): string as a single match with guards: 90 and up is
A, 75 and up B, 50 and up C, anything else F.
Solution
tin run task-3.solution.tinfn grade(score: int): string => match score {
s if s >= 90 => "A"
s if s >= 75 => "B"
s if s >= 50 => "C"
_ => "F"
}
fn main() {
print(grade(95))
print(grade(80))
print(grade(60))
print(grade(20))
} A
B
C
F What's next
Next: Option, Result and ?. No null and no exceptions: missing values and failures are ordinary values.
In the reference: Sum types and match