Lesson 3 of 9 · 27m
Algebraic Data Types and Exhaustive Pattern Matching
Model domains with variants and records, then use exhaustive matching, guards, and compiler warnings to expose missing cases early.
A senior OCaml engineer reading a new codebase usually looks for the variants first. Not the entrypoint, not the framework wiring — the variants. They tell you what the system believes can happen. Once those shapes are right, pattern matching becomes an audit mechanism: every consumer must account for every constructor the domain can produce.
Variants encode alternatives without subclass theater
A payment state machine is a good example because bad states are expensive:
type payment =
| Draft of { amount_cents : int64 }
| Authorized of { amount_cents : int64; auth_id : string }
| Captured of { amount_cents : int64; auth_id : string; capture_id : string }
| Failed of { amount_cents : int64; reason : string }The constructor carries exactly the data meaningful in that state. You cannot accidentally read capture_id from a draft because the field does not exist there. This is better than a record full of nullable fields where every consumer must remember which combinations are legal.
Matching is control flow plus data decomposition
let describe payment =
match payment with
| Draft { amount_cents } -> Printf.sprintf "draft for %Ld cents" amount_cents
| Authorized { auth_id; _ } -> "authorized as " ^ auth_id
| Captured { capture_id; _ } -> "captured " ^ capture_id
| Failed { reason; _ } -> "failed: " ^ reasonThe { auth_id; _ } pattern is explicit field punning with a wildcard for fields you do not care about. Pattern matching is not just a prettier switch: it binds values while checking structure.
Exhaustiveness warnings are architectural alarms
If a new constructor is added, every non-exhaustive match becomes visible:
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Refunded _Do not silence this reflexively. In mature systems, warning 8 is often the feature that carries a schema change through the whole codebase. It tells you exactly where a human must decide what the new state means.
Use wildcards carefully
A match such as | Active -> "active" | _ -> "inactive" looks convenient. It is also how Suspended, PendingReview, and FraudHold all quietly become 'inactive' after the next business rule lands. A wildcard is correct when the remaining cases genuinely share behavior. It is dangerous when used to finish the match quickly.
Guards refine structure but weaken proof
match amount_cents with
| n when n < 0L -> Error Negative_amount
| n when n = 0L -> Error Zero_amount
| n -> Ok nThe compiler generally cannot prove that integer guards cover all possibilities, so a final case or explicit design review is still needed. Guards are appropriate for semantic conditions, not as a substitute for representing states in the type.
Field notes
- Compile with warnings enabled and treat partial matches as defects, not style suggestions.
- Use GADTs only when ordinary variants cannot express the invariant; they are powerful but make inference and error messages harder.
- Avoid exceptions for routine state outcomes when a variant result communicates the state machine more clearly.
- Pattern matches evaluate in order. Overlapping or redundant cases can hide logic mistakes even when the compiler accepts them.
Was this lesson helpful?