Skip to content
Discriminated Unions
step 1/4

Reading — step 1 of 4

Learn

~1 min readPattern Matching and Types

Discriminated unions (DUs) define a type that's one of several variants. F#'s killer type-modeling feature.

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

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

let shapes = [Circle 5.0; Square 4.0; Rectangle (3.0, 6.0)]
shapes |> List.iter (fun s -> printfn "%f" (area s))

DUs are how you eliminate null checks:

type Maybe<'T> =
    | Some of 'T
    | None

F#'s built-in option type works exactly this way. Pattern match on Some x to extract the value safely; None is the explicit absent case. The compiler forces you to handle both — no NullReferenceException possible.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…