OCaml Medium · Lesson 1 · On the house

Signatures and abstract types

module type, sig ... end, hiding representations, and .mli files. Lesson 1 is free — on the house.

Lessons · OCaml Medium · Lesson 1 of 10 · On the house

Signatures and abstract types

module type, sig ... end, hiding representations, and .mli files.

Illustration for OCaml
Lesson 1 is on the house.

A signature describes a module's interface: module type STACK = sig type 'a t val empty : 'a t val push : 'a -> 'a t -> 'a t end.

Constrain a module with it: module Stack : STACK = struct type 'a t = 'a list ... end. Outside, 'a Stack.t is abstract: nobody can see or depend on it being a list.

Abstraction enforces invariants. A Sorted_list module can guarantee sorting because only its own functions can build values of its type.

An .mli file is the signature of the matching .ml file. Write it first for library code; it doubles as documentation.

include copies a module's contents into another, which is useful for extending a module with a few functions.

abstract type

module type COUNTER = sig
  type t
  val zero : t
  val incr : t -> t
  val to_int : t -> int
end

module Counter : COUNTER = struct
  type t = int
  let zero = 0
  let incr n = n + 1
  let to_int n = n
end

let () =
  let c = Counter.(zero |> incr |> incr) in
  print_endline (string_of_int (Counter.to_int c))
Match this when you type.

Quiz

What does constraining Counter with COUNTER hide?

Quiz

Could outside code write Counter.incr 5?

Quiz

What file holds a module's signature?

Quiz

What does the still print?

Check

Match the still for: Signatures and abstract types.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.