typestar

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

  1. Some 207 and None are the only shapes.
  2. Matching forces both cases to be handled.
  3. Option.map and Option.value ~default chain without unwrapping.

Keywords and builtins used here

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.

Type this snippet

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

← Previous Next →