- Courses
- 💻Programming Languages
- 🐫OCaml (WIP)
- Advanced Type System
- Functors
On this page
OCaml Functors — Parameterizing Modules Over Other Modules
Published on August 20, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
A functor is a function from modules to modules: it takes one or more modules as input and produces an entirely new module as output. This lets an entire implementation be written once, generically, and reused across as many different concrete types as needed — the same relationship an ordinary function has to the specific values it's called with, just one level up, operating on whole modules instead of individual values.
The Problem Functors Solve
Consider a set abstraction that needs to compare its elements somehow. A polymorphic 'a set type can hold elements of any type, but the operations that actually implement it — checking membership, inserting, removing — need some concrete way to decide whether two elements are equal. Hardcoding OCaml's built-in = works for simple cases, but immediately rules out anything that needs a different notion of equality: a set of strings compared case-insensitively, or a set of integers where two numbers with the same magnitude are treated as equal. Writing a separate, nearly identical set implementation for every such variation would duplicate the entire data structure's logic repeatedly, differing only in how two elements get compared — exactly the kind of repetition that becomes a maintenance liability the moment a bug fix or improvement needs to be applied to every copy separately.
Basic Functor Syntax
A functor is defined the same way an ordinary module is, except its definition takes a module as a parameter, written in parentheses with its own required signature:
module type Start = sig
val start : int
end
module Make_counter (Init : Start) = struct
let value = ref Init.start
let next () =
let v = !value in
incr value;
v
end
Make_counter is a function from modules to modules: given any module matching the Start signature, it produces a new module with its own value and next. Applying it works exactly like calling a function, just with a module in place of an ordinary value:
module Counter_from_zero = Make_counter (struct let start = 0 end)
module Counter_from_ten = Make_counter (struct let start = 10 end)
# Counter_from_zero.next ();;
- : int = 0
# Counter_from_ten.next ();;
- : int = 10
Each application of Make_counter produces a genuinely separate module, with its own independent value reference — applying the same functor twice doesn't share state between the two results, any more than calling the same function twice with different arguments would.
A Real Example: Building a Generic Set
This exact functor pattern is how OCaml's own standard library builds its Set module. Set.Make takes a module describing an element type and a comparison function, and returns a complete set implementation specialized to that type:
module type OrderedType = sig
type t
val compare : t -> t -> int
end
# module StringSet = Set.Make (String);;
module StringSet :
sig
type elt = string
type t = Set.Make(String).t
val empty : t
val add : elt -> t -> t
val mem : elt -> t -> bool
...
end
String already provides a t and a compare function matching what Set.Make requires, so applying the functor directly produces a complete, ready-to-use set implementation specialized for strings — full of operations like add, mem, union, and inter — without a single line of that logic having to be written by hand for this specific element type. A completely different element type and comparison strategy produces an equally complete, independent set module, built from the exact same underlying functor:
module Case_insensitive : OrderedType with type t = string = struct
type t = string
let compare a b = String.compare (String.lowercase_ascii a) (String.lowercase_ascii b)
end
module CI_Set = Set.Make (Case_insensitive)
CI_Set behaves like an ordinary set of strings, except membership and ordering are decided case-insensitively — accomplished entirely by supplying a different comparison function through the module argument, with none of Set.Make's own implementation needing to change or be duplicated.
Sharing Constraints: Connecting a Functor's Output to Its Input
A functor's result type is sometimes left abstract by default, which can disconnect it from the type it was actually built around unless that connection is stated explicitly. Writing a functor's own signature with a with type clause — a sharing constraint — is how that connection gets restored:
module type SET = sig
type elt
type t
val empty : t
val add : elt -> t -> t
val mem : elt -> t -> bool
end
module Make_set (Elt : OrderedType) : SET with type elt = Elt.t = struct
type elt = Elt.t
type t = elt list
let empty = []
let mem x s = List.exists (fun y -> Elt.compare x y = 0) s
let add x s = if mem x s then s else x :: s
end
Without with type elt = Elt.t in Make_set's own return signature, SET's elt would stay a fully abstract type as far as anything outside the functor could tell, with no visible connection back to whatever Elt.t the functor was actually applied to — making it impossible, for instance, to call Make_set(Int_ordered).add 5 Make_set(Int_ordered).empty, since the compiler would have no way to confirm 5 and the abstract elt type actually agree. The sharing constraint restores exactly that connection, letting the functor's output type be understood in terms of whatever input it was built from.
A Second Use Case: Eliminating Test Duplication
Functors aren't limited to building data structures — they're equally useful for factoring out logic that needs to run identically against several different implementations of the same signature. A test suite is a natural fit:
module type Stack = sig
type 'a t
val empty : 'a t
val push : 'a -> 'a t -> 'a t
val peek : 'a t -> 'a
end
module Stack_tests (S : Stack) = struct
let () = assert (S.(empty |> push 1 |> peek) = 1)
let () = assert (S.(empty |> push 1 |> push 2 |> peek) = 2)
end
Applying Stack_tests to any module matching the Stack signature runs the exact same battery of checks against it:
module List_stack_tests = Stack_tests (List_stack)
module Linked_stack_tests = Stack_tests (Linked_stack)
The tests themselves are written exactly once, entirely independent of which specific stack implementation they'll eventually be checked against — precisely the same code-reuse benefit the Set example offered, just applied to test logic rather than a data structure's core operations.
Applicative Functors: Repeated Applications Stay Compatible
By default, OCaml's functors are applicative, meaning applying the same functor to the exact same module argument twice produces types that are considered equal to each other, not merely similar. Set.Make(String).t computed in one part of a program and Set.Make(String).t computed separately elsewhere refer to the same type, as long as both applications used the literal same argument module — a property that matters when a single functor gets applied to the same argument in more than one place across a larger project, since it's what keeps those separately-computed results usable together rather than accidentally becoming two incompatible types that merely look alike.
Functors vs. First-Class Modules
Functors and first-class modules solve related but distinct problems. A functor is the right tool when the set of implementations needed is known and fixed at compile time — building a specialized Set or Map for a handful of known element types, or generating a test suite for several known stack implementations. When the actual choice of implementation instead needs to be made while a program is running — reading a name from configuration and picking a matching module at that point — packing modules as first-class values is the mechanism suited to that situation instead, since a functor application itself is always resolved statically, at compile time, not dynamically while the program executes.
Key Takeaways
- A functor is a function from modules to modules, letting an entire implementation be written once and applied to many different concrete module arguments.
module F (X : Sig) = struct ... enddefines a functor; applying it,F (SomeModule), produces a genuinely new, independent module each time.- OCaml's own
Set.MakeandMap.Makeare functors built exactly this way, parameterized over an element type and comparison function. - A sharing constraint (
with type t = ...) connects a functor's abstract result type back to the type it was actually built from, which is often necessary for the result to be usable the way callers expect. - Functors are equally useful for factoring out logic — such as a test suite — that needs to run identically against several different implementations of the same signature.
- OCaml's functors are applicative by default, meaning the same functor applied to the same argument module produces genuinely compatible types across separate applications; functors resolve implementation choice at compile time, while first-class modules are the tool for choices that need to be made at runtime.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
First-Class Modules
Next
Recursive Modules
- The Problem Functors Solve
- Basic Functor Syntax
- A Real Example: Building a Generic Set
- Sharing Constraints: Connecting a Functor's Output to Its Input
- A Second Use Case: Eliminating Test Duplication
- Applicative Functors: Repeated Applications Stay Compatible
- Functors vs. First-Class Modules
- Key Takeaways
