Skip to content

Modules, signatures, and functors

11 September 2025 ยท OCaml 5.2

Every .ml file in OCaml is already a module, and an optional .mli beside it is its signature: what callers are allowed to see. Leaving a type's definition out of the signature makes it abstract, so invariants hold at module boundaries because nothing outside can construct a value behind your back.

A functor is a function from modules to modules. That's how Map.Make and Set.Make work in the standard library: hand them a module with a type t and a compare function, and you get back a balanced tree specialized to that key.

module type ORDERED = sig
  type t
  val compare : t -> t -> int
end

module Counter (Key : ORDERED) : sig
  type t
  val empty : t
  val bump : Key.t -> t -> t
  val count : Key.t -> t -> int
  val to_list : t -> (Key.t * int) list
end = struct
  module M = Map.Make (Key)
  type t = int M.t

  let empty = M.empty

  let bump k t =
    M.update k (function None -> Some 1 | Some n -> Some (n + 1)) t

  let count k t = Option.value (M.find_opt k t) ~default:0
  let to_list = M.bindings
end

module Words = Counter (String)

let () =
  let counts =
    [ "let"; "in"; "let"; "rec"; "let" ]
    |> List.fold_left (fun acc w -> Words.bump w acc) Words.empty
  in
  assert (Words.count "let" counts = 3);
  assert (Words.count "fun" counts = 0);
  assert (Words.to_list counts = [ ("in", 1); ("let", 3); ("rec", 1) ])

String already has type t = string and val compare : t -> t -> int, so Counter (String) needs no wrapper or boilerplate trait implementation, and two different orderings over strings can coexist as two functor applications without colliding on a global type.