typestar

match in OCaml

An expression the compiler audits for coverage.

(* match is an expression; the compiler audits the coverage. *)
let describe count =
  match count with
  | 0 -> "empty quadrat"
  | 1 -> "a single animal"
  | n when n < 10 -> Printf.sprintf "%d animals, quiet" n
  | _ -> "teeming"

(* Tuples destructure right in the pattern. *)
let advice = function
  | ("spring", n) when n > 20 -> "return at the next low tide"
  | (season, _) -> "log and move on, " ^ season

let () =
  [0; 1; 6; 40] |> List.iter (fun n -> print_endline (describe n));
  print_endline (advice ("spring", 31));
  print_endline (advice ("autumn", 4))

How it works

  1. Arms try in order; when guards refine a pattern.
  2. function opens a match on the last argument directly.
  3. Tuples destructure in the pattern: ("spring", n).

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
551
Tokens
128
Three-star pace
65 tpm

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

Type this snippet

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

← Previous Next →

match in other languages