Sum Types and Enums
Variants, payloads, generic sums, recursive types, enums, and matching.
Contents
A sum type is exactly one of a fixed set of variants. A variant may carry fields. An enum is a sum whose variants are bare names.
Declaring a Sum Type#
Variants follow a leading pipe. Each variant may have a parenthesized list of named fields.
type Shape =
| Circle(radius f64)
| Rect(width f64, height f64)
| Dot
A variant without fields is a bare name. Fields are written as name Type pairs separated by commas.
A sum type may be generic and recursive, provided recursion passes through a managed reference.
type Maybe[T] = | Nothing | Just(value T)
type Tree[T] =
| Leaf
| Node(left Tree[T], value T, right Tree[T])
Sum types are managed values. Enums are scalar values.
Constructing a Sum Value#
A variant with fields uses call syntax. A variant without fields is a bare expression. Type arguments are inferred from the fields when possible.
const circle = Circle(2.0)
const tree = Node(Leaf, 2, Node(Leaf, 3, Leaf))
const maybe = Just(7)
Annotate the binding when the type argument cannot be inferred.
const nothing Maybe[i32] = Nothing
const text Maybe[str] = Just("hello")
A sum type cannot declare invariants. Enforce constraints in constructor functions or wrap the sum in a record with an invariant.
Matching#
fn area(shape Shape) f64 => match shape {
Circle(radius) => 3.14159 * radius * radius
Rect(width, height) => width * height
Dot => 0.0
}
The number of bindings must match the number of fields. _ in a binding position ignores a field. A bare _ arm matches any remaining variant.
fn radius_or_zero(shape Shape) f64 => match shape {
Circle(radius) => radius
_ => 0.0
}
A match without a wildcard must list every variant.
Testing a Sum Value#
if shape is Circle(radius) {
print(radius)
}
if value is Just(v) {
print(v)
}
Use is for a single case and match for two or more.
Recursive Sums#
type Expr =
| Number(value i32)
| Add(left Expr, right Expr)
| Multiply(left Expr, right Expr)
fn evaluate(expr Expr) i32 => match expr {
Number(value) => value
Add(left, right) => evaluate(left) + evaluate(right)
Multiply(left, right) => evaluate(left) * evaluate(right)
}
A recursive value must eventually reach a variant that does not recurse.
Enums#
The keyword enum appears after the type name.
type Color enum {
Red
Green
Blue
}
type Direction enum {
North
East
South
West
}
Variants are accessed through the type name with ..
const colour = Color.Green
const direction = Direction.North
An enum is an unmanaged scalar with no payload. Values of the same enum type can be compared with ==.
Matching an Enum#
An enum pattern is qualified by the enum type.
fn code(colour Color) i32 => match colour {
Color.Red => 1
Color.Green => 2
Color.Blue => 3
}
if colour is Color.Green {
print("go")
}
An enum match that omits a variant and has no wildcard is rejected.
Printing and Equality#
Sum types, Option, and Result can be interpolated but not printed directly. Enums can be interpolated. print accepts integers, floats, booleans, runes, and strings.
print($"colour = {colour}")
print($"result = {Some(5)}")
Sum values do not support ==. Write a function or trait implementation that matches both values.
trait Eq {
fn eq(x, y Self) bool
}
impl Expr of Eq {
fn eq(a, b Self) bool => match a {
Number(x) => match b {
Number(y) => x == y
_ => false
}
_ => false
}
}
A real implementation must recurse through every variant.
Choosing a Type#
| Type | Payload | Managed | Equality | Typical use |
|---|---|---|---|---|
| Enum | None | No | == |
Mode, direction, colour, status label |
| Sum | Per variant | Yes | User-defined | Syntax tree, domain event, protocol message |
Option[T] |
One value | Yes | No | A value that may be absent |
Result[T, E] |
Success or error value | Yes | No | An operation that may fail |
Collector#
A sum value is allocated at construction; its tag and fields are initialized before publication. The collector traces the value while reachable. Cycles are collected because the collector traces rather than counts references. The tag is not accessible; use match or is.