TExcelTAD
Home › OCaml › OCaml Modules

OCaml Modules

A module groups related types, values and functions under one name. You have used modules from the start: List, String, Printf. Every .ml file is automatically a module too: the file inventory.ml becomes the module Inventory.

Inside one file, you can define modules with module Name = struct ... end:

ocaml · try it yourself
module Temperature = struct
  type t = float  (* degrees Celsius *)

  let freezing = 0.0
  let of_fahrenheit f = (f -. 32.0) *. 5.0 /. 9.0
  let to_fahrenheit c = (c *. 9.0 /. 5.0) +. 32.0
  let describe c = if c <= freezing then "freezing" else if c < 20.0 then "cool" else "warm"
end

let () =
  let today = Temperature.of_fahrenheit 68.0 in
  Printf.printf "%.1f C is %s\n" today (Temperature.describe today);
  Printf.printf "%.1f F\n" (Temperature.to_fahrenheit 100.0)
20.0 C is warm
212.0 F

Names inside a module are accessed with dot notation: Temperature.describe. By convention, the main type of a module is called t, so you refer to it as Temperature.t.

Opening modules

Writing Module.name everywhere gets long. There are several ways to bring names into scope:

ocaml · try it yourself
module Geometry = struct
  let pi = 3.14159
  let circle_area r = pi *. r *. r
  let square_area s = s *. s
end

let () =
  (* 1. local open with Module.( ... ) *)
  Printf.printf "%.2f\n" Geometry.(circle_area 2.0 +. square_area 3.0);
  (* 2. let open ... in *)
  let open Geometry in
  Printf.printf "%.2f\n" (circle_area 1.0)
21.57
3.14

A top-level open Geometry makes the names available for the rest of the file. Use it sparingly: opening many modules makes it hard to tell where a name comes from, and a later open can shadow earlier names.

Tip: Module.(expr) is great for short arithmetic-heavy expressions, such as Int64.(add x (mul y 2L)).

Nested modules and aliases

Modules can contain other modules, and you can give a module a shorter alias:

ocaml · try it yourself
module Shop = struct
  module Price = struct
    let with_tax p = p *. 1.25
    let format p = Printf.sprintf "%.2f kr" p
  end

  module Cart = struct
    let total items = List.fold_left (fun acc (_, p) -> acc +. p) 0.0 items
  end
end

module P = Shop.Price

let () =
  let items = [ ("coffee", 45.0); ("bun", 32.0) ] in
  let net = Shop.Cart.total items in
  print_endline (P.format (P.with_tax net))
96.25 kr

Including a module

include M copies all of M's contents into the current module. It is a simple way to extend a module:

ocaml · try it yourself
module MyList = struct
  include List

  let sum = fold_left ( + ) 0
  let average l = float (sum l) /. float (length l)
end

let () =
  let l = [ 4; 8; 15; 16; 23; 42 ] in
  Printf.printf "length %d, sum %d, average %.2f\n" (MyList.length l) (MyList.sum l) (MyList.average l)
length 6, sum 108, average 18.00

MyList.length comes from List; sum and average are new.

Modules and files

In a real project, each file is a module and you rarely write struct ... end at the top level:

text
src/
├── temperature.ml    → module Temperature
├── temperature.mli   → its interface (signature), optional
└── main.ml           → uses Temperature.describe

Dune finds the files and compiles them in the right order. Module names must be unique within a library, and dependency cycles between modules are not allowed: if A uses B, then B cannot use A.

A module as a small library

Modules are a natural way to put a type together with its operations:

ocaml · try it yourself
module Money = struct
  type t = { cents : int; currency : string }

  let make currency amount = { cents = int_of_float (Float.round (amount *. 100.)); currency }
  let add a b =
    if a.currency <> b.currency then invalid_arg "Money.add: currency mismatch";
    { a with cents = a.cents + b.cents }
  let to_string m = Printf.sprintf "%d.%02d %s" (m.cents / 100) (m.cents mod 100) m.currency
end

let () =
  let a = Money.make "EUR" 19.99 and b = Money.make "EUR" 0.01 in
  print_endline (Money.to_string (Money.add a b));
  print_endline (Money.to_string (Money.make "USD" 7.5))
20.00 EUR
7.50 USD

Right now anyone can build a Money.t directly with a bad value, such as negative cents with the wrong currency. The next lesson shows how signatures hide the representation so that only Money.make can create values.

Test yourself

Which module does the file user_db.ml define?

  1. user_db
  2. UserDb
  3. User_db
  4. USER_DB

What does List.(length [1; 2] + 1) do?

  1. A syntax error
  2. Evaluates the expression with List's names in scope, giving 3
  3. Creates a new module
  4. Adds 1 to every element

What does include List do inside a module?

  1. Imports List lazily
  2. Copies all of List's definitions into the current module
  3. Makes the module a subtype of List
  4. Nothing, it is a comment