Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 40 ยท Modules and Functors

First-Class Modules, Recursive Modules and Module Types

Use OCaml modules as values. Learn first-class modules with pack and unpack, module type of, include with constraints, recursive modules and when each technique is appropriate.

Modules and ordinary values live in separate worlds in OCaml: you cannot put a module in a list or pass it to a normal function. That separation keeps the module system simple and fast, but sometimes you need to choose an implementation at run time, for example "the storage backend named in the config file". First-class modules let you wrap a module into a value, move it around like any other value, and open it again later.

This lesson also covers the remaining module tools: module type of, include with constraints, destructive substitution and recursive modules.

OCaml is not available in the site's code runners, so ocaml blocks are read-only. The Python stand-in selects an implementation by name, which is the same pattern with weaker guarantees.

Packing a module as a value

Start with a signature and two implementations:

OCAML
module type GREETER = sig
  val greet : string -> string
end

module English : GREETER = struct
  let greet name = "Hello, " ^ name
end

module Spanish : GREETER = struct
  let greet name = "Hola, " ^ name
end

Wrap a module in a value with (module M : SIG):

OCAML
let greeters : (string * (module GREETER)) list =
  [ ("en", (module English)); ("es", (module Spanish)) ]

The type (module GREETER) is the type of a packed module. Now greeters is an ordinary list. To use one, unpack it with let module or a pattern:

OCAML
let greet_in lang name =
  match List.assoc_opt lang greeters with
  | Some (module G : GREETER) -> G.greet name
  | None -> "?"

let () = print_endline (greet_in "es" "Ada")
(* prints: Hola, Ada *)

In the arm Some (module G : GREETER), the name G is a module you can use like any other for that arm.

You can also take a packed module as a parameter:

OCAML
let shout (module G : GREETER) name = String.uppercase_ascii (G.greet name)

let () = print_endline (shout (module English) "ada")
(* prints: HELLO, ADA *)

Use cases

  • Plug-in registries, where a table maps names to implementations.
  • Choosing a storage backend, clock or logger based on configuration.
  • Dependency injection for tests: pass a fake implementation of an interface.
  • Hiding a type together with its operations in a single value (an "existential").

If the choice is known at compile time, a functor is simpler. If it is made at run time, use first-class modules.

Existential packing: a type with its operations

A signature can include a type, and the packed module keeps it hidden:

OCAML
module type SHAPE = sig
  type t
  val make : float -> t
  val area : t -> float
  val name : string
end

module Sq : SHAPE = struct
  type t = float
  let make s = s
  let area s = s *. s
  let name = "square"
end

module Ci : SHAPE = struct
  type t = float
  let make r = r
  let area r = Float.pi *. r *. r
  let name = "circle"
end

let area_of (module S : SHAPE) size = S.area (S.make size)

let () =
  List.iter
    (fun (m : (module SHAPE)) ->
      let (module S) = m in
      Printf.printf "%s %.2f\n" S.name (area_of m 2.0))
    [ (module Sq); (module Ci) ]
(* prints: square 4.00 then circle 12.57 *)

Each shape has its own private t, yet the list is homogeneous, because every element has the type (module SHAPE). Object-oriented programmers will recognise this as interface dispatch.

module type of

module type of M gives the signature that M has. It saves you from copying a signature by hand:

OCAML
module type STRING_LIKE = module type of String

A common use is to extend a module while keeping all of its interface:

OCAML
module My_list : sig
  include module type of List
  val sum : int list -> int
end = struct
  include List
  let sum = fold_left ( + ) 0
end

include with constraints

include can bring in a signature or a module and then adjust the types:

OCAML
module type CONTAINER = sig
  type 'a t
  val empty : 'a t
  val add : 'a -> 'a t -> 'a t
end

module type INT_CONTAINER = CONTAINER with type 'a t := 'a list

The := is destructive substitution. It replaces 'a t with 'a list and removes t from the signature, rather than adding an equation as with type t = ... does. It is useful to avoid duplicated type names after include.

Recursive modules

Two modules that need each other can be declared together with module rec:

OCAML
module rec Even : sig
  val is_even : int -> bool
end = struct
  let is_even n = n = 0 || Odd.is_odd (n - 1)
end
and Odd : sig
  val is_odd : int -> bool
end = struct
  let is_odd n = n <> 0 && Even.is_even (n - 1)
end

Recursive modules require a full signature on each module and are rarely needed. Mutually recursive types and functions (type ... and ..., let rec ... and ...) cover most real cases, and splitting a shared type into its own module avoids the problem.

Local modules

You can define a module inside an expression, which is handy for a one-off functor application:

OCAML
let top_words words =
  let module M = Map.Make (String) in
  let counts =
    List.fold_left
      (fun m w -> M.update w (function None -> Some 1 | Some n -> Some (n + 1)) m)
      M.empty words
  in
  M.bindings counts

Stand-in: choose an implementation by name

Python Stand-in: a registry of greeters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In Python any object with a greet attribute fits. In OCaml the packed module must have the signature GREETER, checked when you write (module English).

Common mistakes

  • Reaching for first-class modules when a record of functions would do. A record { greet : string -> string } is lighter if there are no types involved.
  • Forgetting the annotation on (module M). Packing needs an expected signature, either from context or (module M : SIG).
  • Trying to use a type from an unpacked module outside its scope: the type is existential and cannot escape.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (module English : GREETER) create?

    It packs the module into an ordinary value that can be stored and passed around.
  2. 2. How do you use a packed module m of type (module GREETER)?

    Unpacking binds a module name for the scope where you use it.
  3. 3. When is a functor preferable to a first-class module?

    Functors resolve statically and produce fully typed modules; first-class modules suit run-time choice.
  4. 4. What does := do in with type 'a t := 'a list?

    Destructive substitution replaces the type everywhere and deletes its declaration.

Summary

  • (module M : SIG) packs a module into a value and (module X : SIG) in a pattern or parameter unpacks it.
  • Packed modules suit run-time selection, plug-in tables and dependency injection.
  • module type of, include and destructive substitution let you reuse and adapt signatures.
  • module rec exists for truly mutually dependent modules but is rarely needed.

Next: Standard Library Containers: List, Map, Set and Hashtbl