option in OCaml
Absence spelled Some or None — the type that killed null.
(* option makes absence explicit: Some value or None, no nulls. *)
let find_tag species =
match species with
| "sea star" -> Some 207
| "anemone" -> Some 88
| _ -> None
let report species =
match find_tag species with
| Some tag -> Printf.sprintf "%s wears tag %d" species tag
| None -> species ^ " is untagged"
let () =
print_endline (report "sea star");
print_endline (report "limpet");
(* The Option module maps and defaults without unwrapping. *)
let next = find_tag "anemone" |> Option.map succ in
Printf.printf "Next tag: %d\n" (Option.value next ~default:0)
How it works
Some 207andNoneare the only shapes.- Matching forces both cases to be handled.
Option.mapandOption.value ~defaultchain without unwrapping.
Keywords and builtins used here
NoneSomeinletmatchwith
The run, in numbers
- Lines
- 18
- Characters to type
- 566
- 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 9 of 29 in Language basics.