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













