This week I learned about pattern matching in OCaml.

OCaml is an expression-oriented programming language. This means, according to Wikipedia, that “every expression yields a value.”

Procedures that rely on side-effects often yield a unit (i.e. ()).

let mylist = [ (1, 'a'); (2, 'b'); (3, 'c'); (4, 'd'); (5, 'e') ]
let mytable = Hashtbl.create 42
let _ = List.iter (fun (k, v) -> Hashtbl.add tbl k v) mylist

The _ consumes the value produced by List.iter. A more accurate way to write this is to match the value produced by List.iter against a unit type ().

let () = List.iter (fun (k, v) -> Hashtbl.add tbl k v) mylist

This is safer because it will break if List.iter is ever swapped out for a function that produces a value that isn’t a unit…like List.map

# let () = List.map (fun (k, v) -> (v, k)) mylist
  ;;
  Line 1, characters 9-47:
  Error: This expression has type (char * int) list
         but an expression was expected of type unit