typestar

Option in F#

Absence spelled Some or None — there is no null to forget.

// Option makes absence explicit: Some value or None, no nulls.
let findQueen hive =
    match hive with
    | "Willow" -> Some 2024
    | "Bramble" -> Some 2023
    | _ -> None

let report hive =
    match findQueen hive with
    | Some year -> sprintf "%s: queen from %d" hive year
    | None -> sprintf "%s: queenless!" hive

["Willow"; "Thistle"] |> List.iter (report >> printfn "%s")

// The Option module maps and defaults without unwrapping by hand.
let age = findQueen "Bramble" |> Option.map (fun y -> 2026 - y)
printfn "Queen age: %d" (age |> Option.defaultValue 0)

How it works

  1. Some 2024 and None are the only two shapes.
  2. Matching forces both cases to be handled.
  3. Option.map and defaultValue chain without unwrapping.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
547
Tokens
109
Three-star pace
65 tpm

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

Type this snippet

Step 2 of 3 in Pattern matching, step 8 of 27 in Language basics.

← Previous Next →

Option in other languages