typestar

Discriminated unions in F#

A closed set of shapes; match must cover them all.

// A discriminated union is a closed set of shapes; match must
// cover them all -- the compiler audits.
type Inspection =
    | Routine
    | SwarmCells of count: int
    | Queenless of daysSince: int

let respond inspection =
    match inspection with
    | Routine -> "log and close up"
    | SwarmCells n when n > 2 -> sprintf "split now: %d cells" n
    | SwarmCells n -> sprintf "watch closely: %d cells" n
    | Queenless days -> sprintf "order a queen, %d days gone" days

[Routine; SwarmCells 4; Queenless 6]
|> List.iter (respond >> printfn "%s")

How it works

  1. Cases carry data: SwarmCells of count: int.
  2. when guards split one case into severities.
  3. Add a case and every match that misses it stops compiling.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
524
Tokens
86
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 79 seconds.

Type this snippet

Step 2 of 3 in Types, step 14 of 27 in Language basics.

← Previous Next →

Discriminated unions in other languages