liveBook · Manning

Pattern matching

As explained in F# in Action: A Revised Edition of Get Programming with F#

Pattern matching is a language feature that selects behavior by testing a value against structural or value patterns and binding matched components.

Pattern matching is F#’s everyday way to choose an outcome from a value. A `match … with` expression tests patterns in order; each `| pattern -> result` branch returns a value of the same type. Unlike a simple switch, a pattern can inspect a value’s structure and bind its contents to names. section 8.1 section 8.3.2

Distill a loan rule

Suppose `customerDetails` is a tuple of years of history and overdraft status. Two disqualifying conditions can share one result: let canTakeOutALoan = match customerDetails with | 0, _ | 1, true -> false | _ -> true Read this as: reject customers with no history, or one year of history and an overdraft; accept everyone else. The `_` ignores a value that does not affect that rule. section 8.1.3

Choose patterns that make the decision clear:

  • Match record fields by name when tuple positions obscure their meaning. A record pattern can mention only the fields relevant to that branch. section 8.1.4
  • Match lists by shape to distinguish an empty list, a particular length, or a head item and the remaining items without indexing first. section 8.2.4
  • Match a discriminated-union case to access only the data carried by that case. Match `Some number` and `None` separately when an optional value might be absent. section 8.3.2 section 9.1.2
Listing 8.9 Pattern matching over a discriminated union
let message = "Discriminated Unions FTW!"
 
match customer.ContactMethod with                           #1
| Email address -> $"Emailing '{message}' to {address}."    #2
| Telephone (country, number) ->                            #2
    $"Calling {country}-{number} with the
 message '{message}'!"
| Post postDetails ->                                       #2
    $"Printing a letter with contents '{message}'
 to {postDetails.Line1} {postDetails.City}..."
#1 Matches on the union value
#2 Safely unwraps each case and binds its contents to a symbol

The contact-method example shows each union case selecting a different action while binding only that case’s available data. section 8.3.2

Coverage matters. The compiler warns about missing cases and branches that earlier patterns make unreachable. A wildcard can complete a match, but it can also silently absorb a new union case later. Prefer explicit union cases when a future addition should prompt a fresh decision; bounded domain types can make a match complete without a wildcard. A .NET enum is different: it can hold values outside its named cases, so those names alone do not cover every possibility. section 8.1.1 section 8.3.4

Keep `if/then/else` for a direct Boolean choice, or a side effect that needs no `else` branch. Use pattern matching when the value has several meaningful shapes or cases. Compiler coverage checks help catch omissions, but they do not prove that each branch returns the *right* result; test those decisions where a mistake matters. section 8.2.5 section 14.1.1

How F# in Action: A Revised Edition of Get Programming with F# covers it

How deep it goes
Works through match syntax, ordered and exhaustive branches, and tuple, record, list, and union patterns; defers other pattern types to documentation.
Examples
Uses loan-eligibility rules, contact methods, loan-request lists, optional numbers, and instrument sounds to show different matches.
What it assumes
Builds on familiarity with if/then expressions while introducing match syntax before applying it to structured values.
What you can do after
Practice/perform F# matches that simplify conditional rules, safely extract case data, and use compiler warnings to find omissions.
How it connects
Connects pattern matching to tuples, records, lists, discriminated unions, options, compiler warnings, and if/then/else.

Also explained in

Compare how 14 books explain pattern matching →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of F# in Action: A Revised Edition of Get Programming with F#. The section links point to the parts of the book it draws on.