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
Some 2024andNoneare the only two shapes.- Matching forces both cases to be handled.
Option.mapanddefaultValuechain without unwrapping.
Keywords and builtins used here
funletmatchwith
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.
Step 2 of 3 in Pattern matching, step 8 of 27 in Language basics.