Sum Types and Enums
Variants, payloads, generic sums, recursive types, enums, matching, and the absence of structural equality.
Contents
A sum type is a value that is exactly one of a fixed set of variants. Some variants carry fields; some carry none. An enum is a simpler sum whose variants are bare names. Sum types are the main tool for modelling alternatives, and they replace sentinel values, nullable pointers, and error codes in idiomatic Haze.
Declaring a Sum Type#
A sum declaration lists its variants after a leading pipe. Each variant may have a parenthesized list of named fields.
type Shape =
| Circle(radius f64)
| Rect(width f64, height f64)
| Dot
The leading pipe is required in the = form. A variant with no fields is written as a bare name. A variant with fields uses name Type pairs, separated by commas. The declaration may span several lines; the formatter aligns the variant bodies.
A sum type may be generic. Type parameters appear after the type name and may be used in variant fields. A sum may also be recursive, as long as the 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. They are allocated when constructed and traced by the collector. Enums, by contrast, are scalar values.
Constructing a Sum Value#
A variant with fields is constructed with call syntax. A variant without fields is a bare expression. The compiler infers the type arguments from the fields when possible.
const circle = Circle(2.0)
const tree = Node(Leaf, 2, Node(Leaf, 3, Leaf))
const maybe = Just(7)
When a generic sum has a variant with no fields, or the field types do not determine the type argument, annotate the binding.
const nothing Maybe[i32] = Nothing
const text Maybe[str] = Just("hello")
A sum type cannot declare invariants. If a constraint applies to all variants, enforce it in the constructor functions or wrap the sum in a record with an invariant.
Matching a Sum Value#
A match inspects the variant and binds its fields. The arm body may be an expression or a block. The match is an expression when every arm produces a value.
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. An underscore in a binding position ignores a field. A bare _ arm is a wildcard and matches any remaining variant.
fn radius_or_zero(shape Shape) f64 => match shape {
Circle(radius) => radius
_ => 0.0
}
A match with no wildcard must list every variant; the compiler rejects one that leaves a variant unhandled. A sum that may grow should include a deliberate wildcard arm so that adding a variant does not break existing matches.
Testing a Sum Value#
The is operator tests one variant without selecting a branch. Bindings from the pattern are visible in the then branch when is is used as an if condition.
if shape is Circle(radius) {
print(radius)
}
if value is Just(v) {
print(v)
}
is is best for a single case. Use match when two or more variants need handling or when the result must be a value.
Recursive Sums#
Recursive sums are the natural representation of trees, lists, and syntax. The recursive field has the sum type itself, which is a managed reference.
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)
}
The base case must eventually reach a variant that does not recurse. A recursive value with no base case cannot be constructed.
Enums#
An enum declares a fixed set of bare variants. The keyword enum appears after the type name.
type Color enum {
Red
Green
Blue
}
type Direction enum {
North
East
South
West
}
A variant is accessed through the type name with ..
const colour = Color.Green
const direction = Direction.North
An enum is a scalar value with no payload. It is unmanaged and can be compared with == when both operands have the same enum type. Enum variants may not carry fields; use a sum type when payloads are needed.
Matching an Enum#
An enum pattern must be qualified by the enum type. An unqualified variant name is not an enum pattern.
fn code(colour Color) i32 => match colour {
Color.Red => 1
Color.Green => 2
Color.Blue => 3
}
is tests an enum variant directly.
if colour is Color.Green {
print("go")
}
An enum match that omits a variant and has no wildcard is rejected by the compiler. List every variant when the enum is closed and stable; add a wildcard with a deliberate default when the enum is expected to grow.
Printing and Equality#
Sum types, Option, and Result can be interpolated into a string, but they cannot be printed with print directly. Enums can be interpolated because they are scalar values with a known variant name; print itself accepts only integers, floats, booleans, runes, and strings, so an enum is normally shown through interpolation. Records and lists cannot be interpolated directly.
print($"colour = {colour}")
print($"result = {Some(5)}")
Sum values do not support ==. Two values that look structurally equal are not comparable with the built-in operator. Write a function or a trait implementation that matches both values and compares their contents when structural equality is needed.
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
}
}
The implementation above is intentionally incomplete for Add and Multiply; a real implementation must recurse through every variant. The example shows the shape of the solution, not a finished equality function.
Choosing Between a Sum and an Enum#
Use an enum when the value is a label with no data and the set of labels is closed. Use a sum when a variant carries information, when the alternatives need different payloads, or when a function must return one of several outcomes. Use Option for presence and Result for success or failure; they are built-in sums with standard constructors and matching rules.
| 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 |
Sum Types and the Collector#
A sum value is allocated when it is constructed, and its tag and fields are initialized before it is published. The collector traces the value while it is reachable. A recursive structure is collected when no root refers to it, including cycles, because the collector is a tracing collector rather than a reference counter. The language does not expose a way to inspect the tag directly; use match or is so that the compiler can generate the correct dispatch.