Skip to content
Halyard
Project
Source code on Codeberg (opens in new tab)

Search

Menu

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:

halyard
let x = 1

case x of
    0 -> "zero"
    1 -> "one"
    _ -> "many"

Variable Patterns

Bind values to names:

halyard
let point = (3, 4)

case point of
    (x, y) -> x + y

Wildcard Pattern

Match anything without binding:

halyard
let tuple = (42, "ignored")

case tuple of
    (x, _) -> x  -- Ignore second element

Constructor Patterns

Match custom type variants:

halyard
let maybeValue = Just 42

case maybeValue of
    Just x -> "Got value"
    Nothing -> "Nothing"

Qualified Enum Patterns

Enum patterns support qualified syntax with ::, consistent with how variants are constructed:

halyard
enum Color = Red | Green | Blue

let color = Color::Green

case color of
    Color::Red -> "fire"
    Color::Green -> "nature"
    Color::Blue -> "sky"

Nested Patterns

Patterns can be nested:

halyard
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

List Patterns

Destructure lists using exact matches:

halyard
let list = [1, 2]

case list of
    [] -> "empty"
    [x] -> "single"
    [x, y] -> "pair"
    [x, y, z] -> "triple"
    _ -> "more"

Cons Patterns

Use the :: operator to destructure a list into head and tail:

halyard
let list = [1, 2, 3]

case list of
    x :: xs -> x  -- x is the head, xs is the tail
    [] -> 0  -- empty list case

Nested cons patterns for multiple elements:

halyard
let list = [1, 2, 3, 4]

case list of
    a :: b :: rest -> a + b
    x :: xs -> x
    [] -> 0

Head and Tail (Recursive)

halyard
fn sum : [Int] -> Int
fn sum numbers =
    case numbers of
        [] -> 0
        x :: xs -> x + sum xs

sum [1, 2, 3, 4, 5]  -- 15

Record Patterns

Match record fields:

halyard
let person = { name = "Alice", age = 30 }

case person of
    { name, age } -> name

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:

halyard
let user =
    { name = "Bob"
    , age = 25
    , email = "bob@example.com"
    }

case user of
    { name, .. } -> "Hello, " ++ name
halyard
-- Error: Record pattern is missing fields: age, email
case user of
    { name } -> name     -- must use { name, .. } or match all fields

Tuple Patterns

Destructure tuples:

halyard
let pair = (3, 0)

case pair of
    (0, 0) -> "origin"
    (x, 0) -> "on x-axis"
    (0, y) -> "on y-axis"
    (x, y) -> "somewhere else"

Guards

Add conditions to patterns using if:

halyard
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"

As-Patterns

Bind the whole value while also destructuring:

halyard
let maybe = Just 42

case maybe of
    Just x -> (x, Just x)
    Nothing -> (0, Nothing)

Useful for accessing both parts and the whole:

halyard
let list = [1, 2, 3]

case list of
    x :: xs as all -> "Head"
    [] -> "empty"

Or-Patterns

Match multiple alternatives:

halyard
enum Direction
    = North
    | South
    | East
    | West

let direction = Direction::North

case direction of
    Direction::North | Direction::South -> "vertical"
    Direction::East | Direction::West -> "horizontal"

Or-patterns with common variable bindings:

halyard
let point = (5, 2)

case point of
    (x, 1) | (x, 2) | (x, 3) -> x  -- x is bound in all alternatives
    _ -> 0

Pattern Matching in Let

Destructure in let bindings:

halyard
let point = (10, 20)

let (x, y) = point

x + y
halyard
let user = { name = "Alice", age = 30 }

let { name, age } = user

name

Pattern Matching in Function Arguments

halyard
fn fst : (a, b) -> a
fn fst pair =
    case pair of
        (x, _) -> x

fst

(1, "hello")  -- 1
halyard
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)

Pattern Matching in Lambdas

Lambdas support irrefutable patterns (patterns that always match):

halyard
-- Tuple destructuring
let addPair = |(x : Int, y : Int)| x + y

addPair (3, 4)  -- 7

Typed Record Fields in Lambdas

Record fields in lambda patterns can have type annotations. This works standalone — no pipe context needed:

halyard
-- Record destructuring
let describe = |{ name: String, age: Int }| name

describe { name = "Bob", age = 25 }

The parser disambiguates between types (uppercase) and nested patterns (lowercase):

  • { name: String } — String is a type annotation
  • { name: n } — n is 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, …):

halyard
enum TrafficLight = Red | Yellow | Green

let light = TrafficLight::Yellow

case light of
    TrafficLight::Red -> "stop"
    TrafficLight::Yellow -> "caution"
    TrafficLight::Green -> "go"
halyard
let p = (1, "x")

-- Tuple columns are checked too: only (0, _) is covered.
case p of
    (0, _) -> 1

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:

halyard
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"

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):

halyard
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

Unreachable Pattern Detection

The compiler warns about unreachable patterns (dead code):

halyard
let x = False

case x of
    _ -> "anything"  -- This matches everything
    True -> "true"  -- Warning: Unreachable pattern

Pattern Type Validation

Patterns must match the type being matched:

halyard
case 42 of
    "hello" -> 1  -- Error: Pattern type mismatch: expected Int, but pattern is String
    _ -> 0

Branch Return Type Validation

All branches must return compatible types:

halyard
case 1 of
    1 -> 42  -- Int
    2 -> "hello"  -- Error: Case branches have incompatible types
    _ -> 0

Int and Float branches are the one exception: they join at Float, and each Int branch is converted (see Numeric Type Promotion):

halyard
let x = 2

case x of
    1 -> 42  -- Int
    2 -> 3.14  -- Float: the branches join at Float
    _ -> 0

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:

halyard
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:

halyard
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

Best Practices

  1. Order patterns specific to general — put catch-all _ last
  2. Handle all cases explicitly when possible
  3. Use guards for complex conditions — but never rely on a guarded arm for coverage; without an unguarded catch-all the case is non-exhaustive
  4. Avoid deep nesting — refactor into helper functions
  5. Use as-patterns to avoid reconstructing values

Next Steps

Learn about modules to organize your code into reusable units.