On this page

OCaml Nested Modules Explained

Published on August 3, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A module isn't limited to living in its own file — one module can be defined directly inside another, producing a submodule reachable through an extra layer of qualification. This makes it possible to group a cluster of closely related definitions under their own clearly labeled namespace, without going to the trouble of splitting them into an entirely separate file.

Defining a Module Directly in Code​

Outside of the one-module-per-file mapping familiar from ordinary project files, a module can also be written directly as an expression, using module Name = struct ... end:


module String_set = struct

  type t = string list



  let empty = []

  let add x s = x :: s

  let mem x s = List.mem x s

end

The part between struct and end is called a structure — an anonymous sequence of definitions that only becomes a named module once it's bound with module Name = .... This is exactly the same shape every .ml file already has; writing it explicitly like this just makes that structure visible directly inside another piece of code, rather than existing implicitly at the level of a whole file.

Nesting a Module Inside Another​

Because a module definition is just another kind of definition, it can appear inside any other module, including inside an ordinary .ml file, producing a genuine submodule:


(* validation.ml *)

module Errors = struct

  type t = Empty | Too_long of int



  let to_string = function

    | Empty -> "value cannot be empty"

    | Too_long n -> Printf.sprintf "value exceeds %d characters" n

end



let check s =

  if String.length s = 0 then Error Errors.Empty

  else if String.length s > 100 then Error (Errors.Too_long 100)

  else Ok s

From outside validation.ml, the nested module is reached with an extra layer of qualification, exactly mirroring the file's own module name: Validation.Errors.to_string. Inside the same file, the shorter Errors.to_string is enough, since the surrounding file's own module qualifier is already implicit at that point.

Nesting is most useful when a cluster of related definitions — an error type and the functions that operate on it, in this example — deserves to be grouped together and clearly labeled as belonging together, without going to the trouble of splitting it into an entirely separate file. It's a natural fit for small, self-contained pieces of a larger module: a dedicated error type, a handful of configuration values, or a small helper namespace that would feel out of place cluttering the top level of the file.

Nesting More Than One Level Deep​

Submodules can themselves contain further submodules, with qualification simply growing by one more level at each layer:


module Shapes = struct

  module Circle = struct

    type t = { radius : float }

    let area c = Float.pi *. c.radius *. c.radius

  end



  module Square = struct

    type t = { side : float }

    let area s = s.side *. s.side

  end

end

# Shapes.Circle.area { radius = 2.0 };;

- : float = 12.566...

Each level of nesting adds one more segment to the qualified path needed to reach a definition from outside: Shapes.Circle.area, Shapes.Square.area. There's no fixed limit to how deep this can go, though in practice, nesting much beyond two or three levels tends to make code harder to read rather than better organized, and is usually a sign that splitting some of the nested modules out into their own files would serve the project better.

Giving a Submodule Its Own Signature​

A nested module can be restricted with its own signature, exactly the same way a whole file can be restricted with a .mli, by writing the signature directly between the module name and its structure:


module Errors : sig

  type t

  val to_string : t -> string

end = struct

  type t = Empty | Too_long of int



  let to_string = function

    | Empty -> "value cannot be empty"

    | Too_long n -> Printf.sprintf "value exceeds %d characters" n

end

With this signature in place, Errors.t becomes abstract from the perspective of anything outside the Errors submodule — even other code inside the same file can no longer pattern-match directly on Empty or Too_long — while Errors.to_string remains available exactly as before. This is the same abstraction principle already familiar from whole-file .mli signatures, just applied at a smaller scale to a module nested inside a single file, and it's especially useful when only part of a file's contents need that level of protection, rather than the file's entire public interface.

Referencing an Outer Module's Definitions from Within a Submodule​

A submodule has access to everything defined earlier in its enclosing module, exactly as if that surrounding code were an ordinary part of its environment:


let default_radius = 1.0



module Circle = struct

  let default_area = Float.pi *. default_radius *. default_radius

end

Circle can refer to default_radius directly, without any qualification, since it's simply nested inside the same scope that binding already belongs to. The relationship only requires qualification in the other direction — reaching into a submodule from outside it, or from code that comes before the submodule is defined, always needs the full qualified path.

When Nesting Is the Right Tool​

Nesting earns its place when a small, cohesive piece of a module's functionality benefits from its own clearly labeled namespace, but isn't substantial enough to justify becoming an entirely separate file with its own build entry. A dedicated error type paired with the functions that operate on it, a small set of related constants, or a compact helper namespace used only within one file are all typical candidates. Once a nested module grows large enough to represent its own significant piece of functionality — accumulating many definitions of its own, or becoming something other parts of the project might reasonably want to depend on directly — that's usually the point where promoting it to its own file, and its own top-level module, serves the project better than continuing to nest it.

Key Takeaways​

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Module Signatures

Next

Module Aliasing