ZetCode

F# discriminated unions

last modified December 2, 2026

In this article we work with discriminated unions in F#.

A discriminated union is a type whose value is exactly one of several named cases. Each case may carry its own data. A record groups values that exist together, an and of fields; a union describes alternatives, an or of cases. Together with the match expression, unions are the main tool for modelling data in F#.

Defining a union

The simplest union lists cases without any data. Each case starts with a vertical bar and a capitalized name.

directions.fsx
type Direction =
    | North
    | East
    | South
    | West

let heading = East

printfn "%A" heading
printfn "%A" [North; South; West]

We define a Direction type with four cases. A case name is used as a value of the union type; heading has the type Direction. The %A format prints the name of the case.

λ dotnet fsi directions.fsx
East
[North; South; West]

Matching on a union

A match expression takes a union value apart. There is one rule for each case.

turn.fsx
type Direction =
    | North
    | East
    | South
    | West

let turnRight dir =
    match dir with
    | North -> East
    | East -> South
    | South -> West
    | West -> North

let describe dir =
    match dir with
    | North | South -> "vertical"
    | East | West -> "horizontal"

let start = North
let next = turnRight start

printfn "%A -> %A" start next
printfn "%A is %s" next (describe next)
printfn "%A" (turnRight (turnRight next))

The turnRight function returns the direction after a right turn, and describe groups the cases in pairs.

let turnRight dir =
    match dir with
    | North -> East
    | East -> South
    | South -> West
    | West -> North

The type of dir is inferred from the case names in the patterns. Each rule returns a Direction, so the function has the type Direction -> Direction.

| North | South -> "vertical"

Several cases can share a rule when their patterns are joined with a vertical bar.

λ dotnet fsi turn.fsx
North -> East
East is horizontal
West

Incomplete matches

The compiler knows all cases of a union, so it checks that a match covers every one of them.

incomplete.fsx
type Direction =
    | North
    | East
    | South
    | West

let arrow dir =
    match dir with
    | North -> "^"
    | East -> ">"
    | South -> "v"

printfn "%s" (arrow North)
printfn "%s" (arrow West)

The arrow function forgets the West case. The compiler warns about it with FS0025 and names a value that is not matched. The script still runs: the first call prints its arrow, and the call with West fails with a MatchFailureException. The output shows the warning, the first result and the first line of the error report.

λ dotnet fsi incomplete.fsx
incomplete.fsx(8,11): warning FS0025: Incomplete pattern matches on this expression. For example, the value 'West' may indicate a case not covered by the pattern(s).

^
Microsoft.FSharp.Core.MatchFailureException: The match cases were incomplete

Cases with data

A case can carry values. They are declared after the of keyword; several values are separated with *, like the types of a tuple.

shapes.fsx
type Shape =
    | Circle of float
    | Rectangle of float * float
    | Square of float

let area shape =
    match shape with
    | Circle r -> System.Math.PI * r * r
    | Rectangle (w, h) -> w * h
    | Square a -> a * a

let shapes = [Circle 1.5; Rectangle (3.0, 4.0); Square 2.5]

for shape in shapes do
    printfn "%A has area %.2f" shape (area shape)

A shape is a circle with a radius, a rectangle with a width and a height, or a square with a side.

let shapes = [Circle 1.5; Rectangle (3.0, 4.0); Square 2.5]

A case with data is used like a function: Circle 1.5 creates a Shape value. All three values have the same type, so they fit into one list.

| Rectangle (w, h) -> w * h

The pattern binds the data of the case to new names. The values are only reachable through a match, so we cannot read the radius of a rectangle by mistake.

λ dotnet fsi shapes.fsx
Circle 1.5 has area 7.07
Rectangle (3.0, 4.0) has area 12.00
Square 2.5 has area 6.25

Named fields

The values of a case can be given names. They document the meaning of each value and allow named arguments when a value is created.

named.fsx
type Shape =
    | Circle of radius: float
    | Rectangle of width: float * height: float

let perimeter shape =
    match shape with
    | Circle r -> 2.0 * System.Math.PI * r
    | Rectangle (width = w; height = h) -> 2.0 * (w + h)

let c = Circle (radius = 2.0)
let r = Rectangle (height = 3.0, width = 5.0)
let s = Rectangle (4.0, 1.0)

for shape in [c; r; s] do
    printfn "%A: %.2f" shape (perimeter shape)

The fields of Rectangle are named width and height.

let r = Rectangle (height = 3.0, width = 5.0)
let s = Rectangle (4.0, 1.0)

Named arguments can be given in any order. Positional arguments still work.

| Rectangle (width = w; height = h) -> 2.0 * (w + h)

In a pattern, named fields are separated with semicolons. Fields that are not needed can be left out of a named pattern.

λ dotnet fsi named.fsx
Circle 2.0: 12.57
Rectangle (5.0, 3.0): 16.00
Rectangle (4.0, 1.0): 10.00

Unions in records and lists

Unions combine with the other types. Here a record has a field whose type is a union, so every order states how it was paid for.

payments.fsx
type Payment =
    | Cash
    | Card of number: string
    | Voucher of code: string * value: decimal

type Order = { Id: int; Total: decimal; PaidWith: Payment }

let describe payment =
    match payment with
    | Cash -> "cash"
    | Card number -> $"card ending {number[number.Length - 4 ..]}"
    | Voucher (code, value) -> $"voucher {code} ({value} EUR)"

let orders =
    [ { Id = 1; Total = 24.50m; PaidWith = Cash }
      { Id = 2; Total = 99.90m; PaidWith = Card "4111222233334444" }
      { Id = 3; Total = 15.00m; PaidWith = Voucher ("SPRING", 20m) } ]

for o in orders do
    printfn "order %d: %.2f EUR, %s" o.Id o.Total (describe o.PaidWith)

let byCard =
    orders
    |> List.filter (fun o ->
        match o.PaidWith with
        | Card _ -> true
        | _ -> false)
    |> List.length

printfn "paid by card: %d" byCard

The Payment union has a case without data and two cases with data.

| Card number -> $"card ending {number[number.Length - 4 ..]}"

Only the last four digits of the card number are shown; the slice takes the string from the fourth character from the end.

match o.PaidWith with
| Card _ -> true
| _ -> false

The wildcard _ ignores the card number in the first rule and matches all remaining cases in the second.

λ dotnet fsi payments.fsx
order 1: 24.50 EUR, cash
order 2: 99.90 EUR, card ending 4444
order 3: 15.00 EUR, voucher SPRING (20 EUR)
paid by card: 1

Recursive unions

A union case may contain values of the union itself. Such a recursive union describes tree-shaped data, for example an arithmetic expression.

expressions.fsx
type Expr =
    | Num of int
    | Add of Expr * Expr
    | Mul of Expr * Expr
    | Neg of Expr

let rec eval expr =
    match expr with
    | Num n -> n
    | Add (a, b) -> eval a + eval b
    | Mul (a, b) -> eval a * eval b
    | Neg e -> -(eval e)

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

// (2 + 3) * 4 + -5
let e = Add (Mul (Add (Num 2, Num 3), Num 4), Neg (Num 5))

printfn "%s = %d" (show e) (eval e)

An expression is a number, a sum or a product of two expressions, or a negated expression.

let rec eval expr =
    match expr with
    | Num n -> n
    | Add (a, b) -> eval a + eval b

A recursive type calls for a recursive function; see F# recursion. The Num case is the base case, and the other cases evaluate their parts first.

λ dotnet fsi expressions.fsx
((2 + 3) * 4 + -5) = 15

Single-case unions

A union with one case wraps a single value. It gives a plain type such as string or decimal its own name, so that values of different meaning cannot be mixed up.

single_case.fsx
type Email = Email of string
type CustomerId = CustomerId of int

let send (Email address) text =
    printfn "to %s: %s" address text

let lookup (CustomerId id) =
    if id = 7 then Email "paul@example.com" else Email "office@example.com"

let customer = CustomerId 7
let address = lookup customer

send address "Your order has been shipped."

let (Email raw) = address
printfn "raw value: %s" raw

Email and CustomerId are distinct types, although they wrap a string and an integer.

let send (Email address) text =

A single-case union is unwrapped directly in the parameter: the pattern (Email address) always matches. Calling send with a plain string or a CustomerId is a compile-time error.

let (Email raw) = address

The same pattern works in a let binding.

λ dotnet fsi single_case.fsx
to paul@example.com: Your order has been shipped.
raw value: paul@example.com

Generic unions

A union can have type parameters. The option type of the standard library is such a union, with the cases None and Some of 'T; see F# option type. Here we define a binary search tree that holds values of any comparable type.

tree.fsx
type Tree<'T> =
    | Leaf
    | Node of Tree<'T> * 'T * Tree<'T>

let rec insert value tree =
    match tree with
    | Leaf -> Node (Leaf, value, Leaf)
    | Node (left, v, right) ->
        if value < v then Node (insert value left, v, right)
        elif value > v then Node (left, v, insert value right)
        else tree

let rec toList tree =
    match tree with
    | Leaf -> []
    | Node (left, v, right) -> toList left @ [v] @ toList right

let rec depth tree =
    match tree with
    | Leaf -> 0
    | Node (left, _, right) -> 1 + max (depth left) (depth right)

let numbers = List.fold (fun t x -> insert x t) Leaf [5; 3; 8; 1; 4; 9; 3]
let words = List.fold (fun t x -> insert x t) Leaf ["pear"; "apple"; "fig"]

printfn "%A, depth %d" (toList numbers) (depth numbers)
printfn "%A, depth %d" (toList words) (depth words)

A tree is empty, a Leaf, or a Node with a left subtree, a value and a right subtree.

type Tree<'T> =
    | Leaf
    | Node of Tree<'T> * 'T * Tree<'T>

'T stands for the type of the values. A Tree<int> holds integers and a Tree<string> strings; the compiler infers which one from the inserted values.

let numbers = List.fold (fun t x -> insert x t) Leaf [5; 3; 8; 1; 4; 9; 3]

List.fold starts with an empty tree and inserts the elements one by one. Smaller values go to the left, larger to the right, and the duplicate 3 is ignored. Reading the tree from left to right gives the values in sorted order.

λ dotnet fsi tree.fsx
[1; 3; 4; 5; 8; 9], depth 3
["apple"; "fig"; "pear"], depth 3

Equality and comparison

Union values have structural equality: two values are equal when they are the same case with equal data. They can also be compared and sorted; cases declared earlier are smaller.

cards.fsx
type Suit =
    | Clubs
    | Diamonds
    | Hearts
    | Spades

type Card =
    | Number of int * Suit
    | Jack of Suit
    | Queen of Suit
    | King of Suit
    | Ace of Suit

printfn "%b" (Jack Hearts = Jack Hearts)
printfn "%b" (Number (7, Clubs) = Number (7, Spades))
printfn "%b" (Queen Clubs < King Clubs)
printfn "%b" (Number (10, Spades) < Jack Clubs)

let hand = [King Spades; Number (7, Hearts); Ace Clubs; Number (7, Clubs); Jack Diamonds]

printfn "%A" (List.sort hand)
printfn "%A" (List.max hand)

A card is a numbered card or a face card, each with a suit.

printfn "%b" (Number (10, Spades) < Jack Clubs)

The case is compared first. Every Number card is smaller than a Jack, because Number is declared first. Values of the same case are compared by their data, from left to right.

λ dotnet fsi cards.fsx
true
false
true
true
[Number (7, Clubs); Number (7, Hearts); Jack Diamonds; King Spades; Ace Clubs]
Ace Clubs

Source

F# language reference: Discriminated Unions

In this article we have defined discriminated unions, matched on their cases, given cases data and named fields, and written recursive, single-case and generic unions. The match expression is covered in F# match expression, records in F# records, and a union for results and errors in F# Result type.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all F# tutorials.