Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 40 ยท Modules and Functors

Modules and Signatures: Structuring OCaml Programs

Organize OCaml code with modules. Learn structures, signatures, abstract types, .ml and .mli files, open, include, nested modules and how to hide implementation details.

Every OCaml file is a module. A module is a named bundle of types, values and other modules. Together with signatures, which describe what a module offers, modules give OCaml its tool for abstraction and large-scale structure. Where other languages use classes, packages, namespaces and interfaces, OCaml uses this one system.

If you can write List.map, you already use modules. Now you will write your own.

OCaml is not available in the site's code runners, so the ocaml blocks are read-only. A Python stand-in illustrates the "hide the representation" idea.

Defining a module

OCAML
module Counter = struct
  type t = int

  let zero = 0
  let incr c = c + 1
  let to_string c = "count=" ^ string_of_int c
end

let () = print_endline (Counter.to_string (Counter.incr Counter.zero))
(* prints: count=1 *)

struct ... end is the module's body (a structure). Access members with a dot: Counter.zero. Module names start with a capital letter.

Files are modules

A file counter.ml automatically defines a module Counter, with the contents of the file as its body. Another file uses it as Counter.incr. The dependency order is worked out by the build tool, and circular dependencies between modules are not allowed.

Opening and including

OCAML
let n = Counter.(to_string (incr zero))   (* local open: names resolve inside Counter *)

let m =
  let open Counter in
  to_string (incr zero)

open Counter                              (* opens for the rest of the file; use sparingly *)

Counter.( ... ) is the lightest form: it opens a module only for one expression. A global open can make it unclear where a name comes from and can silently shadow other names.

include copies a module's contents into another module, as if you had written them there:

OCAML
module Extended_list = struct
  include List
  let sum = fold_left ( + ) 0
end
(* Extended_list.map, Extended_list.sum ... *)

Signatures: describing an interface

A signature lists the types of what a module provides:

OCAML
module type COUNTER = sig
  type t
  val zero : t
  val incr : t -> t
  val to_string : t -> string
end

Notice type t with no definition. This is an abstract type: users know that t exists but not what it is. Constrain a module with a signature using :

OCAML
module Counter : COUNTER = struct
  type t = int
  let zero = 0
  let incr c = c + 1
  let to_string c = "count=" ^ string_of_int c
end

(* Counter.incr 5      -> error: this expression has type int but t was expected *)
(* Counter.incr Counter.zero  -> fine *)

Outside the module, a Counter.t cannot be built or taken apart except through the functions in the signature. That protects invariants: if t were a Set-like structure that must stay sorted, no outside code can break the ordering.

flowchart LR
    U["Client code"] --> S["signature COUNTER<br/>type t (abstract)<br/>zero, incr, to_string"]
    S --> I["implementation<br/>type t = int"]

Figure: the signature is the only view clients get of the implementation.

.ml and .mli files

In a real project the signature lives in its own file. counter.ml holds the implementation and counter.mli the interface:

OCAML
(* counter.mli *)
type t
val zero : t
val incr : t -> t
val to_string : t -> string
(** [to_string c] formats [c] for display. *)

If an .mli exists, only what it lists is visible to other modules. If you omit it, everything in the .ml is public. Documentation comments with (** ... *) are picked up by odoc.

Writing .mli files is good practice for every module that other code uses. It is documentation the compiler checks, and it speeds up rebuilds, because dependants only recompile when the interface changes.

Exposing part of a type

An abstract type hides everything. A signature can also reveal the representation when you want it public, with type t = int, or reveal some of it while keeping it private:

OCAML
module type ID = sig
  type t = private int      (* readable as an int, but only constructible via make *)
  val make : int -> t
end

private lets clients match and read the value but not build it directly.

Nested modules and submodules

Modules can contain modules:

OCAML
module Geometry = struct
  module Point = struct
    type t = { x : float; y : float }
    let origin = { x = 0.; y = 0. }
    let dist a b = Float.hypot (a.x -. b.x) (a.y -. b.y)
  end

  module Circle = struct
    type t = { centre : Point.t; r : float }
    let area c = Float.pi *. c.r *. c.r
  end
end

let d = Geometry.Point.(dist origin { x = 3.; y = 4. })
(* d = 5. *)

Use the convention "a module M with a main type t", so types read as Point.t, Circle.t, String.t. Functions that operate on that type take it as the first (or last, for pipelines) argument.

Module aliases

OCAML
module P = Geometry.Point        (* a short name for a long path *)

Stand-in: hiding the representation

A signature hides the type behind functions. Python can only hide by convention, with a closure:

Python Stand-in: an abstract counter via closures

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.

Nothing stops a Python caller from reading c["n"]. In OCaml with an abstract t, the compiler rejects it.

Common mistakes

  • Forgetting that the signature must list every value you want to expose. Missing items cause "unbound value" errors in other files.
  • Opening many modules at the top of a file. Prefer qualified names or local opens.
  • Giving a module a type that is not called t, so Module.t does not read naturally.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What module does a file named queue.ml define?

    The module name is the file name with the first letter capitalized.
  2. 2. What does an abstract type type t in a signature mean?

    Hiding the representation lets the implementer change it and protect invariants.
  3. 3. If both counter.ml and counter.mli exist, what is visible to other modules?

    The interface file is the public view of the module.
  4. 4. What is the difference between open M and include M?

    include extends the module being defined, so its contents become part of that module's own interface.

Summary

  • A module (struct ... end) groups types and values. Every .ml file is a module.
  • A signature (sig ... end, or an .mli file) specifies the public interface, and abstract types hide representations.
  • open and include bring other modules' contents in. Prefer local opens such as M.( ... ).
  • Use the t convention for the main type of a module.

Next: Functors