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
- Arms try in order;
whenguards refine a pattern. functionopens a match on the last argument directly.- Tuples destructure in the pattern:
("spring", n).
Keywords and builtins used here
funfunctionletmatchwhenwith
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.
Step 1 of 3 in Pattern matching, step 8 of 29 in Language basics.