Variants in OCaml
A closed set of shapes; match must cover them all.
(* A variant type is a closed set of shapes; match covers them all. *)
type observation =
| Routine
| Rare of string
| Damage of int (* percent of the pool disturbed *)
let respond = function
| Routine -> "log and move on"
| Rare species -> "photograph the " ^ species
| Damage pct when pct > 50 -> Printf.sprintf "report: %d%% lost" pct
| Damage pct -> Printf.sprintf "note %d%% disturbance" pct
let () =
[Routine; Rare "octopus"; Damage 70; Damage 15]
|> List.iter (fun o -> print_endline (respond o))
How it works
- Cases carry data:
Rare of string,Damage of int. whenguards split one case by severity.- Add a case and every incomplete match stops compiling.
Keywords and builtins used here
DamageRareRoutinefunfunctionintletofstringtypewhen
The run, in numbers
- Lines
- 15
- Characters to type
- 506
- Tokens
- 96
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 89 seconds.
Step 3 of 3 in Pattern matching, step 10 of 29 in Language basics.