<!-- Sum types and match · Tin · https://tin.ad/docs/learn/enums/ · generated from the built page -->

[Learn](https://tin.ad/docs/learn/) · The language · 6 of 34

# Sum types and match

**Goal.** Model a value that is one of several shapes and handle every case with `match`.

## 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.

*simple.tin · tin run simple.tin*

```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)
  }
}
```

<!-- output -->
```text
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:

*forgot.tin · tin check forgot.tin*

```tin
type Light = | Red | Amber | Green

fn action(l: Light): string => match l {
  Red => "stop"
  Green => "go"
}

fn main() {
  print(action(Amber))
}
```

<!-- compiler output -->
```text
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:

*payload.tin · tin run payload.tin*

```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))
}
```

<!-- output -->
```text
3.141592653589793
6.0
0.0
```

For one or two values, positions are often clearer than names:

*positional.tin · tin run positional.tin*

```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))
}
```

<!-- output -->
```text
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.

*values.tin · tin run values.tin*

```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"))
}
```

<!-- output -->
```text
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.

*guards.tin · tin run guards.tin*

```tin
type 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))
}
```

<!-- output -->
```text
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.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-1.solution.tin · tin run task-1.solution.tin*

```tin
type 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")
}
```

<!-- output -->
```text
46 cents
```

### Task 2: A tiny calculator · harder

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`.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-2.solution.tin · tin run task-2.solution.tin*

```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))))
}
```

<!-- output -->
```text
7
5
12
```

Because `Add` holds two `Expr`s, `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`.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-3.solution.tin · tin run task-3.solution.tin*

```tin
fn 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))
}
```

<!-- output -->
```text
A
B
C
F
```

## Recap

- A sum type lists its cases, and each may carry data.
- `match` must cover every case, or the program does not compile.
- Guards (`if` on an arm) refine a case.

In the reference: [Sum types and match](https://tin.ad/docs/ref/language/#sums)
