Skip to content
LumenaryAcademy
Foundations 60 min

Records, unions and pattern matching

Modelling a problem with types that say exactly what can exist, and taking values apart safely.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

Types that tell the truth

Suppose a customer can be reached by email, by phone, by post, or not at all. In many languages you would write a class with four nullable fields, Email, PhoneNumber, Street, City, and hope that exactly the right ones are filled in. Nothing stops a record having an email and half a postal address, or nothing at all when it should have something. Every piece of code that reads it has to guess.

F# lets you say what is actually true: a contact is one of four things, and each thing carries exactly the data it needs. Code that handles a contact must handle all four cases, and the compiler checks that it does. This combination of records ("this and that"), discriminated unions ("this or that") and pattern matching is the heart of F#, and the reason its users say that a good type definition reads like a description of the problem.

DefinitionsH

Records: this and that

Definition— Record

A type made of named fields, all present at once: type Book = { Title: string; Author: string; Year: int; Language: string }. Records are immutable, compare by value (two records with equal fields are equal), can be sorted, and print readably with %A.

fsharp
// A record: named fields, immutable, with equality and printing built in.
type Book =
    { Title: string
      Author: string
      Year: int
      Language: string }

let typo = { Title = "Things Fall Apart"; Author = "Chinua Acheb"; Year = 1958; Language = "English" }
let quixote = { Title = "Don Quixote"; Author = "Miguel de Cervantes"; Year = 1605; Language = "Spanish" }

// Copy-and-update: a new record with some fields changed; the original is untouched.
let things = { typo with Author = "Chinua Achebe" }
printfn "before: %s, after: %s" typo.Author things.Author

// Structural equality: same field values means equal.
let copy = { Title = "Don Quixote"; Author = "Miguel de Cervantes"; Year = 1605; Language = "Spanish" }
printfn "equal? %b" (quixote = copy)

// Records sort and print without extra code.
let shelf = [ things; quixote; { quixote with Title = "Exemplary Novels"; Year = 1613 } ]
for b in shelf |> List.sortBy (fun b -> b.Year) do
    printfn "%d  %-18s %s" b.Year b.Title b.Author

printfn "%A" things

// Anonymous records, for one-off shapes.
let summary = {| Count = shelf.Length; Oldest = (shelf |> List.minBy (fun b -> b.Year)).Title |}
printfn "%d books, oldest: %s" summary.Count summary.Oldest

It prints:

text
before: Chinua Acheb, after: Chinua Achebe
equal? true
1605  Don Quixote        Miguel de Cervantes
1613  Exemplary Novels   Miguel de Cervantes
1958  Things Fall Apart  Chinua Achebe
{ Title = "Things Fall Apart"
  Author = "Chinua Achebe"
  Year = 1958
  Language = "English" }
3 books, oldest: Don Quixote
  • Creating a record needs no constructor call: write the fields in braces, and F# infers the type from the field names.
  • Copy-and-update, { typo with Author = "Chinua Achebe" }, creates a new record that differs only in the named fields. The original is unchanged, as the "before" line shows. This is how you "change" immutable data: by making a corrected copy. Behind the scenes, the unchanged fields are shared, not deep-copied, so it is cheap.
  • Structural equality: quixote = copy is true because all fields are equal. You did not write an Equals method; F# generated one, and also generated comparison, which is why List.sortBy and List.minBy work on records, and hashing, so records can be keys in a map or a set.
  • Anonymous records, written with {| ... |}, have no declared type. They are handy for a one-off result inside a function, much like C#'s anonymous types.

One gotcha: F# infers a record's type from its field names, and when two record types share a field name, the most recently declared one wins. If type Film = { Title: string; Year: int } were declared after Book, then { Title = ...; Year = ... } would be taken as a Film. Annotate the binding (let b: Book = ...) or qualify a field (Book.Title = ...) to say which you mean.

Field layout follows the official style guide: one field per line, aligned, when a record does not fit comfortably on one line.

DefinitionsH

Discriminated unions: this or that

Definition— Discriminated union

A type whose values are exactly one of several named cases, each of which may carry its own data: type Contact = Email of address: string | Phone of countryCode: int * number: string | .... Also called a sum type or tagged union. Pattern matching is how you find out which case you have and take out its data.

fsharp
// A discriminated union: a value is exactly one of these cases, each with its own data.
type Contact =
    | Email of address: string
    | Phone of countryCode: int * number: string
    | Post of street: string * city: string
    | NoContact

let describe contact =
    match contact with
    | Email address -> $"email {address}"
    | Phone (code, number) -> $"call +{code} {number}"
    | Post (street, city) -> $"write to {street}, {city}"
    | NoContact -> "no way to reach them"

let contacts =
    [ Email "ines@example.org"
      Phone (351, "912 345 678")
      Post ("12 Jalan Bunga", "Kuala Lumpur")
      NoContact ]

contacts |> List.iter (describe >> printfn "%s")

// Unions can be recursive: a tiny arithmetic language and its evaluator.
type Expr =
    | Num of float
    | Var of string
    | Add of Expr * Expr
    | Mul of Expr * Expr

let rec eval (env: Map<string, float>) expr =
    match expr with
    | Num n -> n
    | Var name -> env[name]
    | Add (a, b) -> eval env a + eval env b
    | Mul (a, b) -> eval env a * eval env b

let rec show expr =
    match expr with
    | Num n -> string n
    | Var name -> name
    | Add (a, b) -> $"({show a} + {show b})"
    | Mul (a, b) -> $"{show a} * {show b}"

// Simplify using nested patterns: x * 1 = x, x + 0 = x, 0 * x = 0.
// Children are simplified first, then the rules are tried on the rebuilt node.
let rec simplify expr =
    let rule e =
        match e with
        | Mul (x, Num 1.0) | Mul (Num 1.0, x) -> x
        | Add (x, Num 0.0) | Add (Num 0.0, x) -> x
        | Mul (Num 0.0, _) | Mul (_, Num 0.0) -> Num 0.0
        | x -> x
    match expr with
    | Add (a, b) -> rule (Add (simplify a, simplify b))
    | Mul (a, b) -> rule (Mul (simplify a, simplify b))
    | leaf -> leaf

let area = Add (Mul (Var "w", Var "h"), Mul (Num 0.0, Var "border"))
let env = Map [ "w", 4.0; "h", 2.5; "border", 1.0 ]
printfn "%s = %g" (show area) (eval env area)
printfn "%s = %g" (show (simplify area)) (eval env (simplify area))

It prints:

text
email ines@example.org
call +351 912 345 678
write to 12 Jalan Bunga, Kuala Lumpur
no way to reach them
(w * h + 0 * border) = 10
w * h = 10

A shorthand. A function whose body is just a match on its last argument can be written with function, which takes the argument implicitly: let describe = function | Email a -> ... | Phone (c, n) -> .... You will see it often in F# code; it means exactly the same thing.

Cases are constructors. Email "ines@example.org" creates a Contact. Field names such as address and countryCode are optional, but they document the meaning and show up in editors.

match takes values apart. Each line of a match expression is a rule: a pattern, an arrow, and the result. Phone (code, number) matches the phone case and binds its two fields to new names in one step. The whole match is an expression, so describe simply returns its value. describe >> printfn "%s" composes the description with printing.

Unions can be recursive. Expr is a tiny language of arithmetic: a number, a variable, or the sum or product of two smaller expressions. Recursive unions are how compilers, interpreters, query builders and document formats represent trees, and F# is a favourite language for writing such tools precisely because functions over them are so short. eval gives each case its meaning; show prints it; simplify rewrites it.

Nested and or-patterns. In simplify, Mul (x, Num 1.0) matches a multiplication whose right side is the number 1, binding the left side to x, and | between two patterns makes an or-pattern: either shape matches, as long as both bind the same names. The simplifier works bottom-up: it simplifies the children first, then tries its rules on the rebuilt node, which is why 0 * border disappeared and then w * h + 0 became w * h.

Map [ "w", 4.0; ... ] builds an immutable dictionary from key-value pairs; the next lesson covers it. %g prints a float in its shortest natural form.

Exhaustiveness

The compiler knows every case of a union, so it can tell when a match forgets one. Delete the NoContact rule from describe and F# reports:

text
main.fsx(7,11): warning FS0025: Incomplete pattern matches on this expression. For example, the value 'NoContact' may indicate a case not covered by the pattern(s).

This is the single most valuable warning in F#. When you add a new case to a union, say WhatsApp of string, the compiler lists every match in the program that must now handle it. Many teams treat it as an error by adding FS0025 to the WarningsAsErrors property in the project file. Avoid ending matches with a catch-all | _ -> when you can list the cases instead: the wildcard silences exactly the warning that would have helped you later.

Single-case unions for domain types

A union with one case is a cheap way to make distinct types for values that would otherwise all be strings or numbers:

fsharp
type EmailAddress = EmailAddress of string
type CustomerId = CustomerId of int

let sendWelcome (EmailAddress address) = printfn "Sending to %s" address

Now passing a CustomerId where an EmailAddress is expected is a compile error, not a bug found in production. The pattern in the parameter, (EmailAddress address), unwraps the value directly.

Worked examplesH

Patterns everywhere

Patterns work on tuples, lists, constants, records and more, and can be combined. Active patterns let you add your own.

fsharp
// Tuple patterns make decision tables readable.
type Move = Rock | Paper | Scissors

let winner a b =
    match a, b with
    | x, y when x = y -> "draw"
    | Rock, Scissors | Paper, Rock | Scissors, Paper -> "first player"
    | _ -> "second player"

for a, b in [ Rock, Scissors; Paper, Paper; Rock, Paper ] do
    printfn "%A vs %A: %s" a b (winner a b)

// List patterns and guards. Cases are tried from top to bottom.
let describeList list =
    match list with
    | [] -> "empty"
    | [ x ] -> $"just {x}"
    | [ x; y ] when x = y -> $"a pair of {x}s"
    | [ x; y ] -> $"{x} and {y}"
    | first :: rest -> $"starts with {first}, then {rest.Length} more"

for l in [ []; [ 7 ]; [ 4; 4 ]; [ 1; 2 ]; [ 9; 8; 7; 6 ] ] do
    printfn "%A -> %s" l (describeList l)

// Active patterns: name your own ways of looking at a value.
let (|Even|Odd|) n = if n % 2 = 0 then Even else Odd

let (|Int|_|) (text: string) =
    match System.Int32.TryParse text with
    | true, value -> Some value
    | false, _ -> None

let classify input =
    match input with
    | Int (Even as n) -> $"the even number {n}"
    | Int n -> $"the odd number {n}"
    | "" -> "nothing typed"
    | text -> $"'{text}' is not a number"

for s in [ "42"; "17"; ""; "forty" ] do
    printfn "%s" (classify s)

It prints:

text
Rock vs Scissors: first player
Paper vs Paper: draw
Rock vs Paper: second player
[] -> empty
[7] -> just 7
[4; 4] -> a pair of 4s
[1; 2] -> 1 and 2
[9; 8; 7; 6] -> starts with 9, then 3 more
the even number 42
the odd number 17
nothing typed
'forty' is not a number

Tuple patterns turn decision tables into code. match a, b with matches a pair; the rule Rock, Scissors | Paper, Rock | Scissors, Paper lists the three winning combinations as one or-pattern. A guard, when x = y, adds a condition the pattern cannot express. Rules are tried from top to bottom, so the draw rule must come first.

Move is a union whose cases carry no data, which is how F# writes an enumeration. %A prints a case by its name.

List patterns match [], fixed-length lists such as [ x; y ], and head-and-tail shapes first :: rest. Order matters: if the general first :: rest rule came before [ x; y ], the two-element rule could never be reached, and the compiler would warn FS0026: This rule will never be matched.

Active patterns are functions that the pattern matcher can call. The complete active pattern (|Even|Odd|) classifies any integer into one of two named cases. The partial active pattern (|Int|_|) succeeds (returning Some value) only when a string parses as an integer, and fails (None) otherwise, so match moves on to the next rule. Patterns nest: Int (Even as n) means "parses as an integer, which is even, and call it n". Active patterns let parsing and classification logic read like ordinary matching, and they are much used in F# code that interprets text, commands or messages.

The match System.Int32.TryParse text with | true, value -> ... inside (|Int|_|) shows one more convenience: F# turns a .NET method's out parameter into an extra element of a returned tuple.

ExplanationH

Making illegal states unrepresentable

A phrase popularised by Yaron Minsky, of the trading firm Jane Street, sums up how F# and OCaml developers design: make illegal states unrepresentable. Instead of checking at run time that a combination of fields makes sense, choose types under which a nonsensical combination cannot be written at all.

Compare two models of an online order's delivery:

fsharp
// Every field might or might not be filled in; many combinations are nonsense.
type DeliveryLoose =
    { IsShipped: bool
      TrackingNumber: string      // empty unless shipped?
      DeliveredOn: System.DateOnly option
      CancelReason: string }      // only if cancelled?

// Each state carries exactly the data that exists in that state.
type Delivery =
    | Pending
    | Shipped of trackingNumber: string
    | Delivered of trackingNumber: string * deliveredOn: System.DateOnly
    | Cancelled of reason: string

With the second model, a delivered order without a tracking number, or a cancelled order that was also delivered, simply cannot be constructed, and every function that handles a Delivery is reminded by the compiler to consider all four states. (option, in the first model, is F#'s standard type for "maybe a value", a union with two cases, Some and None; a later lesson is devoted to it.)

Records, tuples, unions or classes?

A rough guide that most F# code follows:

  • A tuple for two or three values used together briefly, such as a function returning a quotient and a remainder.
  • A record when the parts have meanings worth naming, or the value travels between functions and modules.
  • A union when a value can be in one of several states or kinds, especially when each carries different data.
  • A class when you need to interoperate with .NET code that expects one, or to encapsulate mutable state behind methods; the lesson on types shows F#'s object-oriented side.

The practical workflow is to start a feature by writing its types, in a file of their own, and to discuss them with colleagues, or even with non-programmers who know the business: a well-written union is short enough to read aloud. Scott Wlaschin's book Domain Modeling Made Functional (Pragmatic Bookshelf, 2018) develops this approach at length.

History & global context

An idea that spread

Algebraic data types and pattern matching are older than most programming languages in use today. They appeared in the research languages of the 1970s, notably Hope, developed at the University of Edinburgh, and ML, F#'s ancestor, and they became central to Haskell, OCaml and their relatives. For decades they were seen as a feature of "academic" languages.

That has changed completely. Rust's enum, Swift's enums with associated values, Kotlin's sealed classes, Scala's case classes, TypeScript's discriminated unions and, in November 2026, C# 15's union types and closed hierarchies all bring the same idea to mainstream programming: a value that is exactly one of several shapes, and a match that the compiler checks for completeness. If you learn to design with unions in F#, you will recognise the technique in all of them.

Common misconceptionsH

Common misconceptions

Misconception

"A union is like a C# enum." An enum is a set of named numbers; any integer can be cast to an enum, and cases carry no data. A union's cases can each carry different data, and no value outside the declared cases can exist. A union with data-less cases (like Move) is the closest thing to an enum, and is safer.

Misconception

"Copy-and-update copies the whole object graph." It creates one new record and reuses references to the unchanged field values. Because those values are immutable, sharing them is safe.

Misconception

"A final | _ -> case is good defensive programming." It hides the exhaustiveness check. Use a wildcard when the remaining cases really should be treated alike, such as all other strings or numbers, but list union cases explicitly so the compiler can tell you when a new one appears.

Exercises

Exercises

1. Records, unions and pattern matching

Warm-upComputational

What does this script print?

type Point = { X: int; Y: int }
let p = { X = 1; Y = 2 }
let q = { p with Y = 5 }
let r = { X = 1; Y = 5 }
printfn "%b %b %d" (p = q) (q = r) (q.X + q.Y)

2. Records, unions and pattern matching

Warm-upComputational

What does this script print?

type Shape =
    | Circle of radius: float
    | Rect of width: float * height: float
    | Triangle of a: float * b: float * c: float

let sides shape =
    match shape with
    | Circle _ -> 0
    | Rect _ -> 4
    | Triangle _ -> 3

[ Circle 1.0; Rect (2.0, 3.0); Triangle (3.0, 4.0, 5.0); Rect (1.0, 1.0) ]
|> List.sumBy sides
|> printfn "%d"

3. Records, unions and pattern matching

CoreComputational

What does this script print?

let f pair =
    match pair with
    | 0, _ -> "A"
    | _, 0 -> "B"
    | x, y when x > y -> "C"
    | _ -> "D"

printfn "%s%s%s%s" (f (0, 0)) (f (3, 0)) (f (5, 2)) (f (2, 5))

4. Records, unions and pattern matching

CoreComputational

What does this script print?

let (|Small|Medium|Large|) n =
    if n < 10 then Small elif n < 100 then Medium else Large

let size n =
    match n with
    | Small -> "S"
    | Medium -> "M"
    | Large -> "L"

[ 5; 50; 500; 99; 10 ] |> List.map size |> String.concat "" |> printfn "%s"

5. Records, unions and pattern matching

CoreHuman

You add a new case | WhatsApp of number: string to the lesson's Contact union, and describe has no rule for it. What happens?

Choose one

6. Records, unions and pattern matching

StretchHuman

A course registration is either waitlisted (with a position in the queue), enrolled (with a seat number), or withdrawn (with a date). Which type makes illegal states unrepresentable?

Choose one

Further reading and resources

  • Records · MicrosoftThe reference for records, copy-and-update and equality.
  • Discriminated unions · MicrosoftCases, fields, recursive unions and single-case unions.
  • Pattern matching · MicrosoftEvery kind of pattern F# supports.
  • F# for Fun and Profit · Scott WlaschinA large, free collection of articles on designing with F# types, by the author of Domain Modeling Made Functional.
  • Active patterns · MicrosoftComplete, partial and parameterised active patterns.