Skip to content

Variants, result, and let*

27 March 2025 ยท OCaml 5.2

Algebraic data types are where day-to-day OCaml lives. A variant lists every shape a value can take, and match unpacks it with exhaustiveness checked by the compiler: leave a constructor out, or add a new one later, and every incomplete match warns by line number.

type expr =
  | Lit of int
  | Add of expr * expr
  | Neg of expr

let rec eval = function
  | Lit n -> n
  | Add (a, b) -> eval a + eval b
  | Neg e -> -eval e

function is shorthand for fun x -> match x with. Errors follow the same pattern through the standard library's ('a, 'e) result, which is just Ok of 'a | Error of 'e, and binding operators (let*) chain fallible steps without nested matches:

let parse_digit = function
  | '0' .. '9' as c -> Ok (Char.code c - Char.code '0')
  | c -> Error (Printf.sprintf "not a digit: %c" c)

let sum_digits s =
  let ( let* ) = Result.bind in
  let rec loop acc i =
    if i = String.length s then Ok acc
    else
      let* d = parse_digit s.[i] in
      loop (acc + d) (i + 1)
  in
  if s = "" then Error "empty" else loop 0 0

let () =
  assert (eval (Add (Lit 10, Neg (Lit 3))) = 7);
  assert (sum_digits "123" = Ok 6);
  assert (sum_digits "12a" = Error "not a digit: a");
  assert (sum_digits "" = Error "empty")

let* isn't special syntax wired to Result: defining ( let* ) binds any function of shape 'a t -> ('a -> 'b t) -> 'b t, so Option.bind or an async promise uses the exact same notation.