typestar

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

  1. Cases carry data: Rare of string, Damage of int.
  2. when guards split one case by severity.
  3. Add a case and every incomplete match stops compiling.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Pattern matching, step 10 of 29 in Language basics.

← Previous Next →