F# · Lesson 5

Unions & Pattern Matching

Discriminated unions, match with guards and nested/list patterns, single-case domain types, and making illegal states unrepresentable.

7 min read

In short

  • A union lists cases, and each case can carry its own data
  • match checks the case and extracts its data in one step
  • Missing cases are flagged (FS0025): avoid _ on your own unions
  • Single-case unions give ids and values their own types
  • Model states as cases, not as flags

Discriminated unions (DUs) plus match are the heart of F# domain modelling. If you've written TypeScript tagged unions ({ kind: "circle", ... } | { kind: "square", ... }) with a switch, you already know the idea. F# just makes it shorter, safer and the default way to model data.

Unions without data (enum-like)

▶ Try
type OrderStatus =
    | Pending
    | Shipped
    | Delivered
    | Cancelled

let status = Shipped          // no prefix needed (OrderStatus.Shipped also works)
▶ Try
type OrderStatus = "pending" | "shipped" | "delivered" | "cancelled";

Each | Name is a case. Case names start with an uppercase letter (lowercase is only allowed on a union marked [<RequireQualifiedAccess>]).

Unions with data

Each case can carry its own data, of different types:

▶ Try
type Shape =
    | Circle of radius: float
    | Rectangle of width: float * height: float
    | Square of side: float

let shapes = [ Circle 1.0; Rectangle(2.0, 3.0); Square 4.0 ]
▶ Try
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rectangle"; width: number; height: number }
  | { kind: "square"; side: number };
  • of radius: float says the case carries a float. The field name (radius:) is optional documentation.
  • Multiple fields are separated by *, and you construct with a tuple: Rectangle(2.0, 3.0).
  • No kind tag field to write: the case name is the tag.
  • Cases are functions: [ 1.0; 2.0 ] |> List.map Circle gives a Shape list.

match

▶ Try
let area (shape: Shape) : float =
    match shape with
    | Circle radius -> System.Math.PI * radius * radius
    | Rectangle(width, height) -> width * height
    | Square side -> side * side
▶ Try
function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle": return Math.PI * shape.radius ** 2;
    case "rectangle": return shape.width * shape.height;
    case "square": return shape.side ** 2;
  }
}

Line by line: match shape with starts the expression. Each arm is | pattern -> result. The pattern Circle radius both checks the case and extracts its data into a new name. Arms are tried top to bottom; the first that matches wins. Like if, match is an expression, so every arm returns the same type.

Exhaustiveness

Delete the Square arm and the compiler warns:

warning FS0025: Incomplete pattern matches on this expression. For example, the value 'Square (_)' may indicate a case not covered by the pattern(s).

This is TypeScript's const _exhaustive: never = shape trick, built in and always on. Add a new case to a union and the compiler lists every match you need to update. That's why you should avoid a catch-all _ on your own unions: it silences exactly this warning. Many teams turn FS0025 into an error.

Pattern toolbox

▶ Try
match value with
| 0 -> "zero"                                   // constant
| n when n < 0 -> "negative"                    // guard: extra condition
| 1 | 2 | 3 -> "small"                          // or-pattern: any of these
| _ -> "big"                                    // wildcard: anything

Tuple patterns match several values at once, ideal for "state × event" logic:

▶ Try
let canShip (status: OrderStatus) (isPaid: bool) : bool =
    match status, isPaid with
    | Pending, true -> true
    | Pending, false -> false
    | (Shipped | Delivered | Cancelled), _ -> false

Nested patterns look inside data inside data:

▶ Try
type CardBrand = Visa | Amex
type Payment =
    | Cash
    | Card of CardBrand * last4: string

let fee (payment: Payment) : decimal =
    match payment with
    | Cash -> 0m
    | Card(Amex, _) -> 0.035m
    | Card(Visa, _) -> 0.029m

List patterns take lists apart:

▶ Try
let describe (items: string list) : string =
    match items with
    | [] -> "empty"
    | [ only ] -> $"just {only}"
    | [ first; second ] -> $"{first} and {second}"
    | first :: rest -> $"{first} and {List.length rest} more"

[] is the empty list, [ a; b ] is exactly two items, and head :: tail is "first item, then the rest". Together with rec, list patterns give you recursion over lists:

▶ Try
let rec total (prices: decimal list) : decimal =
    match prices with
    | [] -> 0m
    | price :: rest -> price + total rest

(In practice you'd write List.sum, but this shape shows up when you process tokens, commands or any input one item at a time.)

Arrays match too: | [| user; domain |] -> .... function is shorthand for a one-argument lambda that immediately matches: let isFinal = function Delivered | Cancelled -> true | _ -> false.

Option is just a union

▶ Try
type Option<'T> =
    | None
    | Some of 'T

(None is declared first, which is why None sorts before any Some.)

So you handle it with the same tool: match tryFindUser id with Some user -> ... | None -> .... (The next topic covers option and Result in depth.)

Single-case unions for domain types

In TypeScript, a customerId: number and an orderId: number are interchangeable, and that's a classic bug. F# fixes it with one-case unions:

▶ Try
type CustomerId = CustomerId of int
type OrderId = OrderId of int

let loadOrder (OrderId id) = $"loading order {id}"    // unwrap in the parameter
loadOrder (OrderId 42)                                 // ok
// loadOrder (CustomerId 42)                           // compile error!
▶ Try
type CustomerId = number & { readonly __brand: "CustomerId" };   // TS "branded type" workaround

Pair them with a smart constructor that validates once:

▶ Try
type Quantity = Quantity of int

let createQuantity (n: int) : Quantity option =
    if n >= 1 && n <= 99 then Some(Quantity n) else None

Anything holding a Quantity can trust it's in range. Validation happens at the edge, and the type carries the proof everywhere else.

Make illegal states unrepresentable

A typical "bag of flags" model:

▶ Try
type CartBad =
    { Items: string list
      IsPaid: bool
      PaymentId: string option }   // IsPaid = true but PaymentId = None? Items empty but paid?

Nothing stops impossible combinations, so every function must defend against them. Model the states instead:

▶ Try
type Cart =
    | Empty
    | Active of items: string list
    | Paid of items: string list * paymentId: string

Now a paid cart always has a payment id, and an empty cart has no items field to get wrong. State transitions become a match on (state, event) where every combination is visible, and the compiler checks you handled them.

Common beginner mistakes

  • A nested match can swallow the following arms. If the inner match starts at the same column as the outer arms, it continues until the end of the outer one, and its arms "steal" the outer arms below (you'll usually see a confusing type error, or an FS0026 "rule never matched" warning). Indent the inner match further than the outer |, wrap it in parentheses, or move it into a helper function. The helper is often the clearest.
  • Matching against a variable. | expected -> ... does not compare with an existing expected. It binds a new name and matches everything. Use a guard: | x when x = expected -> ....
  • Ignoring FS0025 (incomplete matches) and FS0026 (rule never matched). Both mean a bug. Usually a missing case, or a broad pattern placed above a specific one.
  • Catch-all _ on your own unions hides future missing cases. List the cases explicitly.
  • Wrong case construction. Rectangle 2.0 3.0 fails. Multi-field cases take a tuple: Rectangle(2.0, 3.0).
  • Forgetting parentheses when constructing nested values: Some Quantity 3 is wrong; write Some(Quantity 3).
  • Forgetting rec on a function that recurses over a list.
  • Inconsistent arm types. Every arm must return the same type, just like if/else.

Cheat sheet

▶ Try
type Status = Active | Suspended of reason: string        // union
type Email = Email of string                               // single-case union
let s = Suspended "late payment"
match s with
| Active -> "ok"
| Suspended reason when reason.Contains("payment") -> "billing"
| Suspended reason -> reason
match a, b with                                            // tuple pattern
| 0, _ | _, 0 -> "has zero"
| _ -> "no zeros"
match xs with
| [] -> 0 | [ x ] -> x | x :: rest -> x + List.length rest // list patterns
let (Email raw) = Email "a@b.com"                          // unwrap single-case union
let isActive = function Active -> true | Suspended _ -> false

Practise this lesson

In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.

Open in the app