On this page

OCaml First-Class Modules: Pack & Unpack

Published on August 20, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A module in OCaml is ordinarily a static component, resolved entirely at compile time — it can't be passed as an argument to a function, stored inside a list, or chosen dynamically based on something a program only learns while running. First-class modules lift this restriction: a module can be packed into an ordinary value, carried around exactly like any other piece of data, and unpacked back into a genuine module wherever it's actually needed.

Why This Matters: Modules Aren't Normally Values​

Functions are values in OCaml — they can be bound to a name, stored in a list, passed as an argument, and returned as a result. Modules, by default, can't do any of this. Given several modules that all implement the same signature, there's ordinarily no way to put them in a list together and pick one out at runtime, the way a list of ordinary functions could be built and indexed into. First-class modules exist specifically to close this gap.

Packing a Module Into a Value​

The (module ... : ...) syntax converts an ordinary module into a value of type (module SignatureName):


module type Formatter = sig

  val format : int -> string

end



module Decimal : Formatter = struct

  let format n = string_of_int n

end



module Hex : Formatter = struct

  let format n = Printf.sprintf "0x%x" n

end

# let decimal_packed = (module Decimal : Formatter);;

val decimal_packed : (module Formatter) = <module>

decimal_packed is now an ordinary value — it can be bound to a name, and its type, (module Formatter), is a genuine core-language type like int or string list. Both implementations can now be collected into a single list, something plain modules could never do directly:


let formatters : (module Formatter) list =

  [ (module Decimal : Formatter); (module Hex : Formatter) ]

Unpacking a Value Back Into a Module​

(val ... : ...) performs the reverse conversion, extracting a real module back out of a packed value, in a context where a module expression is expected:


let use_formatter (packed : (module Formatter)) (n : int) : string =

  let module F = (val packed : Formatter) in

  F.format n

# use_formatter decimal_packed 255;;

- : string = "255"

# use_formatter (module Hex : Formatter) 255;;

- : string = "0xff"

Pattern matching offers a more direct, equivalent way to unpack, since OCaml performs the unpacking automatically when a function parameter is written using the (module Name : Signature) pattern:


let use_formatter (module F : Formatter) (n : int) : string = F.format n

This version behaves identically to the one above, just without needing a separate let module step inside the function body.

Choosing an Implementation at Runtime​

This is where first-class modules earn their keep: selecting which module to use based on something only known while the program is running, such as a configuration value or user input.


let formatter_by_name = function

  | "decimal" -> (module Decimal : Formatter)

  | "hex" -> (module Hex : Formatter)

  | name -> failwith (Printf.sprintf "unknown formatter: %s" name)

# use_formatter (formatter_by_name "hex") 42;;

- : string = "0x2a"

Nothing about which formatter gets used here is fixed until formatter_by_name actually runs — the decision genuinely happens at runtime, exactly the kind of dynamic dispatch ordinary, static modules can't provide on their own. This same pattern is the basis for plugin-style systems: a registry mapping names to packed modules, with the specific implementation picked dynamically based on configuration or user input, rather than being wired in at compile time.

Connecting a Packed Module to a Value's Type​

A packed module's own internal type is hidden by default — packing a module that exposes an abstract t produces a value whose connection to any other type is lost, unless that connection is preserved explicitly. Locally abstract types, written (type a), are the tool for keeping that link alive across a function boundary:


module type Combinable = sig

  type t

  val combine : t -> t -> t

end



let combine_all (type a) (module C : Combinable with type t = a) (items : a list) : a =

  match items with

  | [] -> failwith "empty list"

  | h :: t -> List.fold_left C.combine h t

module Ints : Combinable with type t = int = struct

  type t = int

  let combine = ( + )

end

# combine_all (module Ints : Combinable with type t = int) [1; 2; 3; 4];;

- : int = 10

The (type a) parameter introduces a fresh, locally abstract type inside combine_all's definition, and the with type t = a constraint on the module parameter ties that type directly to C.t. This is what lets the function's second parameter, items : a list, be checked against exactly the same type the packed module itself operates on, rather than the two being unrelated as far as the type checker could otherwise tell.

Restrictions Worth Knowing​

A package type used in packing or unpacking can't contain unresolved type variables — every type involved has to be fully determined at the point of packing or unpacking, which is precisely why locally abstract types are needed to connect a packed module's internal type to anything outside it, rather than leaving that type as an ordinary polymorphic variable. There's also a narrower restriction around functors specifically: unpacking a first-class module directly inside the body of a functor is generally disallowed, since OCaml's functors are applicative by default, and permitting an unpack there could otherwise allow constructing programs that break the type system's soundness guarantees around that applicativity.

When to Reach for First-Class Modules​

First-class modules are the right tool specifically when which implementation to use is a decision the program needs to make while it's running — reading a name from a configuration file and selecting a matching implementation, building a registry of pluggable components, or storing a heterogeneous collection of modules that all share one signature. When the choice between implementations is always known at compile time instead, an ordinary module reference or a functor application accomplishes the same goal with considerably less ceremony, and remains the simpler default outside of these genuinely dynamic situations.

Key Takeaways​

Found this helpful? Share the knowledge...

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

Buy Me a Coffee

Previous

GADTs

Next

Functors