TExcelTAD
Home › OCaml › OCaml Functors

OCaml Functors

A functor is a function from modules to modules. You give it a module that satisfies some signature, and it returns a new module built on top of it. Functors let you write generic code once, for any type that provides certain operations, such as "anything with a comparison function".

The most famous functors are in the standard library: Map.Make and Set.Make. First, let's write one ourselves.

Writing a functor

Suppose we want a "find the maximum" helper for any type that can be compared. We describe what we need in a signature, then write a functor that takes such a module as a parameter:

ocaml · try it yourself
module type ORDERED = sig
  type t
  val compare : t -> t -> int
  val to_string : t -> string
end

module Extremes (Elt : ORDERED) = struct
  let max_of = function
    | [] -> None
    | x :: rest -> Some (List.fold_left (fun m y -> if Elt.compare y m > 0 then y else m) x rest)

  let report label items =
    match max_of items with
    | Some m -> Printf.printf "%s: max is %s\n" label (Elt.to_string m)
    | None -> Printf.printf "%s: empty\n" label
end

module Int_elt = struct
  type t = int
  let compare = Int.compare
  let to_string = string_of_int
end

module By_length = struct
  type t = string
  let compare a b = Int.compare (String.length a) (String.length b)
  let to_string s = s
end

module Int_extremes = Extremes (Int_elt)
module Word_extremes = Extremes (By_length)

let () =
  Int_extremes.report "scores" [ 31; 77; 54 ];
  Word_extremes.report "words" [ "ox"; "camel"; "yak" ];
  Word_extremes.report "nothing" []
scores: max is 77
words: max is camel
nothing: empty

module Extremes (Elt : ORDERED) = struct ... end defines a functor. Extremes (Int_elt) applies it, producing an ordinary module. Note that Int_elt was never declared to be ORDERED: any module with the right contents fits (structural typing).

Map.Make and Set.Make

Map.Make and Set.Make take a module with a type t and a compare function (the signature OrderedType) and return an efficient, immutable map or set of that type. Many standard modules already have the required shape:

ocaml · try it yourself
module StringMap = Map.Make (String)
module IntSet = Set.Make (Int)

let () =
  let ages = StringMap.(empty |> add "Noor" 31 |> add "Ilya" 27 |> add "Bea" 45) in
  StringMap.iter (fun name age -> Printf.printf "%s is %d\n" name age) ages;
  let seen = IntSet.of_list [ 5; 3; 5; 9; 3; 1 ] in
  print_endline (String.concat " " (List.map string_of_int (IntSet.elements seen)))
Bea is 45
Ilya is 27
Noor is 31
1 3 5 9

Maps and sets are ordered by compare, so iteration is always in sorted key order. The next lesson explores them in depth.

Your own key type

To use your own type as a map key, write a module with t and compare:

ocaml · try it yourself
module Point = struct
  type t = int * int
  let compare (x1, y1) (x2, y2) = match Int.compare x1 x2 with 0 -> Int.compare y1 y2 | c -> c
end

module PointMap = Map.Make (Point)

let () =
  let board =
    PointMap.empty
    |> PointMap.add (0, 0) "rook"
    |> PointMap.add (4, 0) "king"
    |> PointMap.add (0, 7) "rook"
  in
  PointMap.iter (fun (x, y) piece -> Printf.printf "(%d,%d) %s\n" x y piece) board;
  match PointMap.find_opt (4, 0) board with
  | Some p -> Printf.printf "on (4,0): %s\n" p
  | None -> ()
(0,0) rook
(0,7) rook
(4,0) king
on (4,0): king

(For a pair of ints, the generic compare would also work: let compare = compare.)

Functor results and signatures

You can state the signature of a functor's result, and use with type to reveal which type it works on:

ocaml · try it yourself
module type STACK = sig
  type elt
  type t
  val empty : t
  val push : elt -> t -> t
  val to_string : t -> string
end

module Make_stack (E : sig type t val show : t -> string end) : STACK with type elt = E.t = struct
  type elt = E.t
  type t = elt list
  let empty = []
  let push x s = x :: s
  let to_string s = "[" ^ String.concat "; " (List.map E.show s) ^ "]"
end

module Float_stack = Make_stack (struct type t = float let show = Printf.sprintf "%.2f" end)

let () =
  Float_stack.(empty |> push 1.5 |> push 2.25 |> to_string) |> print_endline
[2.25; 1.50]

Without with type elt = E.t, the type elt would be abstract and you could not push a float.

When to use functors

Use a functor when Example
A data structure needs an operation on its elements Map.Make, Set.Make, Hashtbl.Make
You want to swap implementations a Storage parameter: in-memory for tests, file-based for production
You add the same features to many modules Comparable.Make (M) adding min, max, between

For plain code reuse, ordinary polymorphic functions are simpler. Reach for functors when you need a whole module to be generic.

Test yourself

What is a functor in OCaml?

  1. A function that maps over a list
  2. A function from modules to modules
  3. A class with one method
  4. A type of exception

What must a module provide to be used with Map.Make?

  1. A type t and a function compare : t -> t -> int
  2. A hash function
  3. A to_string function
  4. Nothing

In which order does StringMap.iter visit keys?

  1. Insertion order
  2. Random order
  3. Sorted order according to String.compare
  4. Reverse insertion order