The Zeno Book Zeno 0.1 zeno-lang.org

12 Enums and match

Some values are one of a short list of choices: a traffic light is red, amber or green; a motor is stopped, running or faulty. An enum (short for enumeration) is a type that lists the choices, and match is how a program does something different for each.

12.1 An enum of plain choices

enum Light {
    Red
    Amber
    Green
}

let now = Red
print(now, now == Red, Amber != Green)
Red true true

Each choice is a case. A case is written by its name, and a value of Light can only ever be one of the three. Compare that with keeping the light in an int where 0 is red, 1 amber and 2 green: nothing would stop a 7, and nothing would tell a reader what 1 means.

12.2 match

match takes a value and runs the block of the first case that fits it:

enum Light {
    Red
    Amber
    Green
}

function next(light: Light) -> Light {
    match light {
        case Red { return Green }
        case Green { return Amber }
        case Amber { return Red }
    }
}

var light = Red
for turn in range(4) {
    print(light)
    light = next(light)
}
Red
Green
Amber
Red

Every case must be handled

A match on an enum must say what to do for every case. Leave one out and the program does not run, and the message names the case that is missing:

enum Light {
    Red
    Amber
    Green
}

function stop_here(light: Light) -> bool {
    match light {
        case Red { return true }
        case Amber { return true }
    }
}
error: this `match` does not handle Green. Add a `case` for it, or a final `case _`
 --> main.zeno:8:5
  |
8 |     match light {
  |     ^

1 error found. Nothing was run.

This is the main reason to use an enum. When a new case is added a year later, say Flashing, every match in the program that does not yet know about it becomes an error, and the compiler lists them. Nothing falls through in silence.

A final case _ stands for every case not named above it, when they all mean the same:

enum Light {
    Red
    Amber
    Green
}

function may_go(light: Light) -> bool {
    match light {
        case Green { return true }
        case _ { return false }
    }
}
print(may_go(Green), may_go(Amber))
true false

"A reading is either a value or a fault code" is one of the most common shapes in real programs, and most languages make it awkward. An enum says it directly, and a match that must name every case is the check that a C switch never gave. (Decision 3.11.)

12.3 Cases that carry values

A case can carry values of its own, named and typed like the parameters of a function. Then the case is written like a call:

enum Shape {
    Circle(radius: float)
    Rect(width: float, height: float)
    Dot
}

let shapes = [Circle(1.0), Rect(2.0, 3.0), Dot]
print(shapes)
[Circle(1.0), Rect(2.0, 3.0), Dot]

All three are Shapes, so they can go in one list. Each carries what that case needs and nothing more: a circle has a radius, a rectangle two sides, and a dot nothing at all.

match takes the values out again. The names in brackets after a case are new names, given the values that case carries, in order:

enum Shape {
    Circle(radius: float)
    Rect(width: float, height: float)
    Dot
}

function area(shape: Shape) -> float {
    match shape {
        case Circle(r) { return 3.14159 * r * r }
        case Rect(w, h) { return w * h }
        case Dot { return 0.0 }
    }
}

for shape in [Circle(1.0), Rect(2.0, 3.0), Dot] {
    print(shape, area(shape))
}
Circle(1.0) 3.14159
Rect(2.0, 3.0) 6.0
Dot 0.0

A value that is not needed is written _: case Rect(w, _) takes the width and leaves the height.

A value read straight off the enum, such as shape.radius, would be a mistake whenever the shape turned out to be a Rect, so the checker refuses it and points to match. Inside case Circle(r), r is there for certain, because the case has already been found to fit.

12.4 match on numbers and text

A match can also take a number or a piece of text, and compare it with each case in turn:

function describe(code: int) -> str {
    match code {
        case 200 { return "ok" }
        case 404 { return "not found" }
        case _ { return "something else" }
    }
}
print(describe(200), describe(404), describe(500))
ok not found something else

There is no way to list every int or every str, so such a match needs a final case _:

let answer = "yes"
match answer {
    case "yes" { print("agreed") }
    case "no" { print("refused") }
}
error: this `match` needs a final `case _` to handle every other value
 --> main.zeno:2:1
  |
2 | match answer {
  | ^

1 error found. Nothing was run.

Giving the value a name

A plain name as the last case fits anything, like _, and gives the value that name inside the block:

for word in ["start", "stop", "jump"] {
    match word {
        case "start" { print("starting") }
        case "stop" { print("stopping") }
        case other { print("no such command:", other) }
    }
}
starting
stopping
no such command: jump

12.5 Blocks, not arrows

Each case is case something, then a block in braces. A case whose block is short can sit on one line, as above; a longer one is laid out like any other block:

let level = 3
match level {
    case 0 { print("off") }
    case 3 {
        print("high")
        print("check the fan")
    }
    case _ { print("on") }
}
high
check the fan

Every other block in Zeno is a keyword, something, and braces: if ready { }, while busy { }. An arrow, as in 3 => ..., would be a second way to start a block. (Decision 1.9.)

12.6 An enum in a state machine

Firmware is full of state machines: a device is in one state, and each event moves it to another. An enum names the states and a match says what each event does in each:

door.zeno

enum Door {
    Closed
    Opening(percent: int)
    Open
}

function step(door: Door) -> Door {
    match door {
        case Closed { return Opening(0) }
        case Opening(p) {
            if p >= 75 {
                return Open
            }
            return Opening(p + 25)
        }
        case Open { return Open }
    }
}

var door = Closed
for tick in range(7) {
    print(tick, door)
    door = step(door)
}
0 Closed
1 Opening(0)
2 Opening(25)
3 Opening(50)
4 Opening(75)
5 Open
6 Open

The compiler checks that step knows what to do in every state. Add a case Jammed to Door and the program will not run until step has decided what a jammed door does.

12.7 Case names belong to the file

The cases of an enum are names in the file, like functions, which is why a case is written plain Red. Two enums in one file therefore cannot both have a case called Red:

enum Light {
    Red
    Green
}
enum Flag {
    Red
    White
}
error: `Red` is already a case of the enum `Light`. A case is written by its name alone, so two enums in one file cannot both have a `Red`. Give one of them another name
 --> main.zeno:5:1
  |
5 | enum Flag {
  | ^

1 error found. Nothing was run.

Give the cases names that say which enum they belong to, such as FlagRed, or put the enums in different files (Programs in Several Files).

An enum lists the cases a value can be, and a case can carry values of its own. match runs the block of the case that fits, takes out what a case carries, and must handle every case of an enum, either by name or with a final case _. A match on numbers or text always needs case _, and a plain name as the last case gives the value a name.

  1. Write an enum Coin with four coins and a function that gives the value of each in cents.

  2. Add Triangle(base: float, height: float) to Shape and run the program before changing area. Read the message.

  3. Write enum Reading with Value(volts: float) and Fault(code: int), and a function that prints a list of readings, with the fault codes in hexadecimal.

  4. Add Jammed to the door, and a Closing state, so that an open door closes again.