Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Pattern Matching and Options

Pattern Matching in Depth

Master F# pattern matching: constant, tuple, list, record and union patterns, guards, as, or-patterns, nested patterns, wildcards and completeness checking, with a runnable C# comparison.

Pattern matching is where F# feels most different from languages built around if and switch. A pattern does two jobs at once: it tests the shape of a value and it binds names to the parts you care about. Instead of checking a condition and then reaching into the value, you describe what the value looks like and receive its pieces.

This lesson tours every kind of pattern you will use, then shows how the compiler checks that you have covered all cases.

match basics

FSHARP
let describeNumber n =
    match n with
    | 0 -> "zero"
    | 1 | 2 | 3 -> "small"
    | _ -> "other"

Cases are tried from top to bottom and the first one that fits wins. _ is the wildcard that matches anything. 1 | 2 | 3 is an or-pattern. match is an expression, so every branch must return the same type, and the result of the whole match is the value of the branch taken.

Patterns for tuples, lists and arrays

FSHARP
let fizzbuzz n =
    match n % 3, n % 5 with
    | 0, 0 -> "FizzBuzz"
    | 0, _ -> "Fizz"
    | _, 0 -> "Buzz"
    | _ -> string n

let rec sum list =
    match list with
    | [] -> 0
    | head :: tail -> head + sum tail

let firstTwo = function
    | [ a; b ] -> Some (a, b)
    | a :: b :: _ -> Some (a, b)
    | _ -> None

Matching a tuple lets you test two values at once without nesting ifs. List patterns take lists apart: [] is empty, head :: tail splits off the first element, and [ a; b ] matches exactly two elements. Arrays use [| a; b |]. function is shorthand for a lambda that immediately matches its argument.

C# C# stand-in: tuple and list patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# list patterns (C# 11) resemble F# ones closely, but F# has had them from the start and the compiler checks them thoroughly.

Record and union patterns

FSHARP
type Shape =
    | Circle of radius: float
    | Rectangle of width: float * height: float

type Order = { Id: int; Total: decimal; Shape: Shape option }

let label order =
    match order with
    | { Total = t } when t > 1000m -> "large"
    | { Shape = Some (Circle _) } -> "round item"
    | { Shape = Some (Rectangle (w, h)) } when w = h -> "square item"
    | { Id = id } -> $"order {id}"

A record pattern names only the fields it needs. Union patterns carry the case name and bind its data. Patterns nest as deeply as the data does: the third case above reaches through Order, Option and Shape in one line.

Guards, as and variables

A guard is an extra when condition. If it is false, matching continues with the next case:

FSHARP
let classify x =
    match x with
    | n when n < 0 -> "negative"
    | 0 -> "zero"
    | n when n % 2 = 0 -> "even"
    | _ -> "odd"

The as keyword names the whole value while you also take it apart:

FSHARP
let describe list =
    match list with
    | (first :: _) as all -> $"starts with {first}, {List.length all} items"
    | [] -> "empty"

Use guards sparingly. The compiler cannot see through a when clause, so it assumes the guard may fail and may ask you for a fallback case even when your logic covers everything.

Type tests and null

You can test a runtime type with :? when you must work with obj:

FSHARP
let show (o: obj) =
    match o with
    | :? int as i -> $"int {i}"
    | :? string as s -> $"string {s}"
    | null -> "null"
    | _ -> "something else"

This is the main place where an incomplete match is expected, and it appears mostly in interop code (Interop with C#). In normal F# code, prefer unions to type tests.

Completeness and redundancy

flowchart TD
    V["value"] --> C1{"case 1?"}
    C1 -->|yes| B1["branch 1"]
    C1 -->|no| C2{"case 2?"}
    C2 -->|yes| B2["branch 2"]
    C2 -->|no| C3{"_ ?"}
    C3 -->|"always"| B3["branch 3"]

Cases are tried in order; the compiler warns if no case can match some value (incomplete) or a case can never be reached (redundant).

An incomplete match raises warning FS0025 and, if an unhandled value arrives at runtime, a MatchFailureException. A redundant case (for example a | _ -> placed before more specific ones) raises warning FS0026. Treat both warnings as errors in real projects. A wildcard at the end of a union match is convenient but gives up the safety net: when you add a case later, nothing warns you. For important unions, list every case.

let patterns and parameters

Patterns are not limited to match. They work in let, function parameters and lambdas:

FSHARP
let (x, y) = (3, 4)
let { Name = name } = { Name = "Ada"; Age = 36 }
let distance (x1, y1) (x2, y2) = sqrt ((x2 - x1) ** 2.0 + (y2 - y1) ** 2.0)
let swap = fun (a, b) -> (b, a)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the two jobs of a pattern?

    A pattern checks what the value looks like and gives names to the pieces you want.
  2. 2. What does head :: tail match?

    The cons pattern needs at least one element; the empty list has its own pattern [].
  3. 3. What happens when a guard (when) is false?

    A guard refines a case; if it fails, the next case is tried.
  4. 4. Why can a final wildcard case be risky for a match over your own union?

    With a wildcard the match is always complete, so the compiler cannot tell you about the new case.

Summary

  • Patterns test shape and bind names; match returns a value and tries cases top to bottom.
  • Tuples, lists, arrays, records and unions all have patterns, and patterns nest.
  • Use | for alternatives, when for guards, as to name a whole value, :? for runtime types.
  • The compiler warns about incomplete and redundant matches; treat the warnings seriously.
  • Patterns also work in let, parameters and lambdas.

Next: Option and ValueOption