📦

Understanding Modules in OCaml

Apr 26, 2025

Modules in OCaml

Introduction

  • Modules are collections of definitions grouped together and are the basic means to organize OCaml software.
  • Separate concerns should be isolated into separate modules.

Basic Usage

File-Based Modules

  • In OCaml, every piece of code is wrapped into a module, which can be a submodule of another module.
  • Example: Two files, athens.ml and berlin.ml, define modules Athens and Berlin respectively.
  • Compilation with Dune requires a dune-project file for project-wide configuration and a dune file for build directives.
  • opam exec -- dune build and opam exec -- dune exec ./berlin.exe commands are used to compile and execute.
  • Modules can be accessed using ModuleName.definition and can be opened to bring definitions into scope.

Naming and Scoping

  • Use open to bring module definitions into scope, but be cautious of conflicts (e.g., don't open List).
  • Standard library Stdlib is opened by default.
  • Use let open ... in for local scope.

Interfaces and Implementations

  • By default, everything in a module is public.
  • Use .mli files to define module interfaces, restricting the default interface.
  • Example: cairo.ml and cairo.mli demonstrate private definitions.

Abstract and Read-Only Types

  • Types can be public, private, abstract, or read-only.
  • Example: exeter.mli and exeter.ml illustrate these concepts with types aleph, bet, gimel, and dalet.

Submodules

Submodule Implementation

  • Modules can contain submodules, accessed via chained names.
  • Example: florence.ml and glasgow.ml.

Submodule With Signatures

  • Define submodule interfaces using module signatures.
  • Example: florence.ml with HelloType module type.

Module Manipulation

Displaying a Module's Interface

  • Use OCaml toplevel or ocamlc to display a module's interface.
  • ocaml-print-intf tool can also be used.

Module Inclusion

  • include directive allows adding functions to existing modules.
  • Example: Add uncons function to List module in extlib.ml.

Stateful Modules

  • Modules can have internal states, like the Random module.
  • Random.get_state and Random.set_state provide access to the state.

Conclusion

  • Modules are key for organizing software, with interfaces defining exposed definitions.
  • Other means to handle OCaml software components include functors, libraries, and packages.

Help Improve Our Documentation

  • All OCaml docs are open source and contributions are encouraged.