Pattern Matching
Match expressions, constructors, bindings, wildcards, refinement tests, and exhaustiveness.
Contents
Pattern matching is how Haze inspects a value that may take one of several forms. It is available for sum types, enums, Option, and Result. Records and lists are destructured with field access and indexing rather than patterns.
Match Expressions#
A match names a subject and a sequence of arms. Each arm contains a pattern, =>, and a body. The body may be an expression or a block. Arms are tested in order.
type Shape =
| Circle(radius f64)
| Rect(width f64, height f64)
fn area(shape Shape) f64 => match shape {
Circle(radius) => 3.14159 * radius * radius
Rect(width, height) => width * height
}
A match used as a statement may have arms that produce no value. A match used as an expression must have every arm produce a value of a compatible type, or all arms produce no value.
fn describe(value Option[i32]) {
match value {
Some(v) => print(v)
None => print("missing")
}
}
Constructors and Bindings#
A sum pattern names a variant and binds each of its fields to a name. The number of bindings must match the number of fields. A binding introduced by an arm is immutable and is scoped to that arm.
type Tree =
| Leaf
| Node(left Tree, value i32, right Tree)
fn sum(tree Tree) i32 => match tree {
Leaf => 0
Node(left, value, right) => sum(left) + value + sum(right)
}
An underscore in a binding position discards that field. A bare underscore as the entire pattern is the wildcard arm, which matches any remaining value.
fn first_or(tree Tree, fallback i32) i32 => match tree {
Node(_, value, _) => value
_ => fallback
}
The wildcard arm is also the way to make a match total when the variant set might grow. Without a wildcard, every variant must be covered; the compiler rejects a match that leaves a variant unhandled. A runtime fallback remains in the generated code, but it is unreachable for a checked match.
Enum Patterns#
Enum variants are qualified by the enum type. An unqualified variant name in a pattern is not an enum pattern and produces an error.
type Color enum {
Red
Green
Blue
}
fn code(colour Color) i32 => match colour {
Color.Red => 1
Color.Green => 2
Color.Blue => 3
}
Enum variants do not carry fields. A value is the variant itself, so there are no bindings. A match over an enum is the idiomatic replacement for a chain of equality tests.
Option and Result Patterns#
Option[T] has Some(value) and None. Result[T, E] has Success(value) and Error(reason). Both are ordinary sum-like types and are matched with bindings.
fn report(result Result[i32, str]) {
match result {
Success(value) => print($"ok: {value}")
Error(reason) => print($"error: {reason}")
}
}
fn report_optional(value Option[i32]) {
match value {
Some(v) => print(v)
None => print("none")
}
}
The ? operator is the concise way to propagate an Error; match is the way to handle one locally or to transform it. Use ? when the caller should decide what a failure means, and match when the current function can recover.
The is Operator#
is tests a value against a pattern and produces a boolean. Its pattern syntax is the same as a match arm, but it does not select a branch; it is an expression.
const value Option[i32] = Some(3)
if value is Some(v) {
print(v)
}
if value is None {
print("empty")
}
When is appears as the condition of an if, the bindings are visible in the then branch. The else branch does not receive them. This is the idiomatic form for handling exactly one case.
if value is Success(v) {
print(v)
} else {
print("failed")
}
A refinement type may also be used as a pattern. The pattern checks the invariant and binds the value when it holds. The bound value has the refinement type, so it can be passed to functions that require it without another check.
type Positive = i32 : invariant self > 0
fn main() {
const raw = 42
if raw is Positive(p) {
print(p)
} else {
print("not positive")
}
}
Refinement patterns are only available through is; match requires a sum type, enum, Option, or Result. A refinement of one of those types behaves as the underlying type for matching, and the invariant is checked by is.
Bindings and Narrowing#
An is test narrows the value in the then branch through its bindings. The original variable is not changed; the binding is a new immutable name of the refined type.
fn take_positive(n i32) i32 {
if n is Positive(p) {
return p * 2
}
return 0
}
A binding from a pattern is not visible outside its branch. If the value is needed after the branch, return it or assign it to a variable declared before the branch.
fn positive_or_zero(n i32) i32 {
var result = 0
if n is Positive(p) {
result = p
}
return result
}
Nested Decisions#
Patterns in Haze bind names; they do not nest arbitrary patterns. To inspect a nested value, bind the outer field and match it in a second step. This keeps the control flow explicit and avoids a pattern language that is difficult to read.
fn depth(value Option[Tree]) i32 => match value {
Some(tree) => match tree {
Leaf => 0
Node(left, _, right) => 1 + depth(Some(left)) + depth(Some(right))
}
None => 0
}
The same rule applies to guards and literal patterns: Haze does not have them. Express a guard with an if inside the arm, and express a literal comparison with an if or a match on the value's variant plus a condition.
Match as an Expression#
A match produces a value when every arm produces one. This makes it a compact replacement for a switch statement that assigns to a temporary.
const label = match value {
Some(v) => $"value {v}"
None => "missing"
}
The arm bodies must have compatible types. A void arm may not be mixed with a value-producing arm; the compiler rejects a match where some arms produce a value and others do not.
Practical Guidance#
The best match is a total match. List every variant when the type is closed and stable, and use a wildcard arm with a deliberate default when the type is likely to grow. Prefer is for a single case and match for two or more. Keep arm bodies short; move a long computation into a named helper so the shape of the decision remains visible.