On this page
Pattern Matching
Pattern matching is one of Halyard's most powerful features. It lets you destructure data and branch based on its shape.
Basic Patterns
Literal Patterns
Match exact values:
let x = 1
case x of
0 -> "zero"
1 -> "one"
_ -> "many"
Compiled
Variable Patterns
Bind values to names:
let point = (3, 4)
case point of
(x, y) -> x + y
Compiled
Wildcard Pattern
Match anything without binding:
let tuple = (42, "ignored")
case tuple of
(x, _) -> x -- Ignore second element
Compiled
Constructor Patterns
Match custom type variants:
let maybeValue = Just 42
case maybeValue of
Just x -> "Got value"
Nothing -> "Nothing"
Compiled
Qualified Enum Patterns
Enum patterns support qualified syntax with ::, consistent with how variants are constructed:
enum Color = Red | Green | Blue
let color = Color::Green
case color of
Color::Red -> "fire"
Color::Green -> "nature"
Color::Blue -> "sky"
Compiled
Nested Patterns
Patterns can be nested:
import String
let result = Ok Just 5
case result of
Ok (Just x) -> "Success with value: " ++ String.fromInt x
Ok Nothing -> "Success but empty"
Err msg -> "Error: " ++ msg
Compiled
List Patterns
Destructure lists using exact matches:
let list = [1, 2]
case list of
[] -> "empty"
[x] -> "single"
[x, y] -> "pair"
[x, y, z] -> "triple"
_ -> "more"
Compiled
Cons Patterns
Use the :: operator to destructure a list into head and tail:
let list = [1, 2, 3]
case list of
x :: xs -> x -- x is the head, xs is the tail
[] -> 0 -- empty list case
Compiled
Nested cons patterns for multiple elements:
let list = [1, 2, 3, 4]
case list of
a :: b :: rest -> a + b
x :: xs -> x
[] -> 0
Head and Tail (Recursive)
fn sum : [Int] -> Int
fn sum numbers =
case numbers of
[] -> 0
x :: xs -> x + sum xs
sum [1, 2, 3, 4, 5] -- 15
Compiled
Record Patterns
Match record fields:
let person = { name = "Alice", age = 30 }
case person of
{ name, age } -> name
Compiled
The scrutinee type may be a type alias — since aliases are transparent, a value of type PersonAlias where type alias PersonAlias = { name: String, age: Int } is declared can be matched with the same record pattern as a plain { name: String, age: Int } value.
Rest Pattern (..)
When matching only some fields, use .. to explicitly ignore the rest. Partial record patterns without .. are an error:
let user =
{ name = "Bob"
, age = 25
, email = "bob@example.com"
}
case user of
{ name, .. } -> "Hello, " ++ name
Compiled
-- Error: Record pattern is missing fields: age, email
case user of
{ name } -> name -- must use { name, .. } or match all fields
Tuple Patterns
Destructure tuples:
let pair = (3, 0)
case pair of
(0, 0) -> "origin"
(x, 0) -> "on x-axis"
(0, y) -> "on y-axis"
(x, y) -> "somewhere else"
Compiled
Guards
Add conditions to patterns using if:
let number = 42
case number of
n if n < 0 -> "negative"
n if n == 0 -> "zero"
n if n < 10 -> "small positive"
n if n < 100 -> "medium"
_ -> "large"
Compiled
As-Patterns
Bind the whole value while also destructuring:
let maybe = Just 42
case maybe of
Just x -> (x, Just x)
Nothing -> (0, Nothing)
Compiled
Useful for accessing both parts and the whole:
let list = [1, 2, 3]
case list of
x :: xs as all -> "Head"
[] -> "empty"
Compiled
Or-Patterns
Match multiple alternatives:
enum Direction
= North
| South
| East
| West
let direction = Direction::North
case direction of
Direction::North | Direction::South -> "vertical"
Direction::East | Direction::West -> "horizontal"
Compiled
Or-patterns with common variable bindings:
let point = (5, 2)
case point of
(x, 1) | (x, 2) | (x, 3) -> x -- x is bound in all alternatives
_ -> 0
Compiled
Pattern Matching in Let
Destructure in let bindings:
let point = (10, 20)
let (x, y) = point
x + y
Compiled
let user = { name = "Alice", age = 30 }
let { name, age } = user
name
Compiled
Pattern Matching in Function Arguments
fn fst : (a, b) -> a
fn fst pair =
case pair of
(x, _) -> x
fst
(1, "hello") -- 1
Compiled
fn addPairs : (Int, Int) -> (Int, Int) -> (Int, Int)
fn addPairs p1 p2 =
case (p1, p2) of
((x1, y1), (x2, y2)) -> (x1 + x2, y1 + y2)
addPairs (1, 2) (3, 4) -- (4, 6)
Compiled
Pattern Matching in Lambdas
Lambdas support irrefutable patterns (patterns that always match):
-- Tuple destructuring
let addPair = |(x : Int, y : Int)| x + y
addPair (3, 4) -- 7
Compiled
Typed Record Fields in Lambdas
Record fields in lambda patterns can have type annotations. This works standalone — no pipe context needed:
-- Record destructuring
let describe = |{ name: String, age: Int }| name
describe { name = "Bob", age = 25 }
Compiled
The parser disambiguates between types (uppercase) and nested patterns (lowercase):
{ name: String }—Stringis a type annotation{ name: n }—nis a pattern (variable binding)
Note: Lambdas only support irrefutable patterns. Refutable patterns like |Just x| or |[a, b]| are not allowed.
Pattern Completeness Validation
Halyard validates pattern matching at compile time to help catch common errors.
Exhaustiveness Checking
The compiler checks that patterns are exhaustive — for every column type: enums
(list their variants), lists ([] / _ :: _), tuples, records (with and without
..), record-variant payloads, and literal domains (Int, Float, Decimal,
String, Char, …):
enum TrafficLight = Red | Yellow | Green
let light = TrafficLight::Yellow
case light of
TrafficLight::Red -> "stop"
TrafficLight::Yellow -> "caution"
TrafficLight::Green -> "go"
Compiled
let p = (1, "x")
-- Tuple columns are checked too: only (0, _) is covered.
case p of
(0, _) -> 1
Compiled
Guard Exhaustiveness
For Int and Char scrutinees, the compiler analyses guard intervals and
verifies coverage at compile time. A complete partition requires no catch-all:
let x = -3
-- A complete partition of Int — no catch-all needed.
-- The compiler verifies the guards cover every Int value.
case x of
n if n > 0 -> "positive"
n if n == 0 -> "zero"
n if n < 0 -> "negative"
Compiled
When guards do not form a complete partition, the compiler reports the uncovered
sub-domain as a NonExhaustiveMatch error. For every other type, a guarded arm
contributes no coverage and the coverage matrix reports what is missing — the
error names the missing shapes (e.g. _ for an infinite domain, True, False
for an all-guarded Boolean case):
let s = "hello"
-- All arms guarded, no catch-all: a guarded arm never counts as coverage,
-- so the matrix reports the gap even though no interval analysis applies to String.
case s of
c if c == "hello" -> 1
c if c == "world" -> 2
Compiled
Unreachable Pattern Detection
The compiler warns about unreachable patterns (dead code):
let x = False
case x of
_ -> "anything" -- This matches everything
True -> "true" -- Warning: Unreachable pattern
Compiled
Pattern Type Validation
Patterns must match the type being matched:
case 42 of
"hello" -> 1 -- Error: Pattern type mismatch: expected Int, but pattern is String
_ -> 0
Compiled
Branch Return Type Validation
All branches must return compatible types:
case 1 of
1 -> 42 -- Int
2 -> "hello" -- Error: Case branches have incompatible types
_ -> 0
Compiled
Int and Float branches are the one exception: they join at Float, and each Int branch is converted (see Numeric Type Promotion):
let x = 2
case x of
1 -> 42 -- Int
2 -> 3.14 -- Float: the branches join at Float
_ -> 0
Compiled
Enum Variant Pattern Validation
The compiler validates that enum variant patterns match the variant's actual shape. Using record syntax for a tuple variant (or vice versa), supplying wrong fields, or using wildcards incorrectly all produce compile-time errors:
enum Shape = Circle Float | Rect { width : Float, height : Float }
-- Error: Circle takes a positional argument, not a record pattern
case s of
Circle { radius } -> radius -- wrong syntax for a tuple variant
-- Error: Rect requires record pattern with named fields
case s of
Rect w h -> w * h -- wrong syntax for a record variant
-- Error: unknown field 'depth' in Rect pattern
case s of
Rect { width, depth } -> width -- 'depth' is not a field of Rect
Correct patterns:
enum Shape = Circle Float | Rect { width : Float, height : Float }
let s = Shape::Rect { width = 2.0, height = 2.5 }
case s of
Circle r -> r
Rect { width, height } -> width * height
Compiled
Best Practices
- Order patterns specific to general — put catch-all
_last - Handle all cases explicitly when possible
- Use guards for complex conditions — but never rely on a guarded arm for coverage; without an unguarded catch-all the case is non-exhaustive
- Avoid deep nesting — refactor into helper functions
- Use as-patterns to avoid reconstructing values
Next Steps
Learn about modules to organize your code into reusable units.