OCaml Signatures and Abstraction
A signature (module type) describes the interface of a module: which types and values it offers, and with which types. A module can be restricted to a signature, hiding everything else. This is how OCaml achieves encapsulation.
module type COUNTER = sig
type t
val zero : t
val increment : t -> t
val value : t -> int
end
module Counter : COUNTER = struct
type t = int
let zero = 0
let increment n = n + 1
let value n = n
let secret_helper n = n * 100 (* not in the signature: hidden *)
end
let () =
let c = Counter.(zero |> increment |> increment |> increment) in
Printf.printf "count = %d\n" (Counter.value c)count = 3
module Counter : COUNTER = ... checks that the structure provides everything in COUNTER and then hides the rest. Counter.secret_helper no longer exists from the outside.
Abstract types
In the signature, type t is written without a definition. That makes t abstract: outside the module, nobody knows that a Counter.t is really an int. You cannot add 10 to it or build one directly:
module type COUNTER = sig
type t
val zero : t
val increment : t -> t
val value : t -> int
end
module Counter : COUNTER = struct
type t = int
let zero = 0
let increment n = n + 1
let value n = n
end
let () = Printf.printf "%d\n" (Counter.value (Counter.zero + 10))File "<source>", line 15, characters 46-58:
15 | let () = Printf.printf "%d\n" (Counter.value (Counter.zero + 10))
^^^^^^^^^^^^
Error: The value Counter.zero has type Counter.t
but an expression was expected of type int
The only way to change a counter is increment, so a counter can never go down. Abstraction lets a module guarantee invariants and change its internal representation later without breaking users.
Smart constructors
A common pattern: hide the type and expose a function that validates input before creating a value.
module Email : sig
type t
val of_string : string -> (t, string) result
val to_string : t -> string
val domain : t -> string
end = struct
type t = { user : string; domain : string }
let of_string s =
match String.split_on_char '@' (String.lowercase_ascii (String.trim s)) with
| [ user; domain ] when user <> "" && String.contains domain '.' -> Ok { user; domain }
| _ -> Error ("invalid email: " ^ s)
let to_string e = e.user ^ "@" ^ e.domain
let domain e = e.domain
end
let () =
List.iter
(fun s ->
match Email.of_string s with
| Ok e -> Printf.printf "ok: %s (domain %s)\n" (Email.to_string e) (Email.domain e)
| Error msg -> print_endline msg)
[ " Ada@Example.ORG "; "no-at-sign"; "bob@localhost" ]ok: ada@example.org (domain example.org)
invalid email: no-at-sign
invalid email: bob@localhost
Every Email.t in the whole program has passed validation, because there is no other way to make one. The signature here is written inline: module Email : sig ... end = struct ... end.
.mli files
In a project, the signature of email.ml usually lives in a separate file email.mli:
(* email.mli *)
type t
(** A validated, lower-case email address. *)
val of_string : string -> (t, string) result
(** [of_string s] trims and validates [s]. *)
val to_string : t -> string
val domain : t -> stringThe compiler checks email.ml against email.mli. Comments in (** ... *) are documentation comments, rendered by odoc.
Exposing a type's definition
Sometimes you want users to see a type, for example a variant they need to match on. Then write the full definition in the signature:
module Traffic : sig
type light = Red | Yellow | Green (* concrete: users can match on it *)
val next : light -> light
val to_string : light -> string
end = struct
type light = Red | Yellow | Green
let next = function Red -> Green | Green -> Yellow | Yellow -> Red
let to_string = function Red -> "red" | Yellow -> "yellow" | Green -> "green"
end
let () =
let rec cycle light n =
if n > 0 then begin
print_string (Traffic.to_string light ^ " ");
cycle (Traffic.next light) (n - 1)
end
in
cycle Traffic.Red 5;
print_newline ();
match Traffic.next Traffic.Green with Traffic.Yellow -> print_endline "slow down" | _ -> ()red green yellow red green
slow down
A third option, type t = private int, lets users read the representation (and use it as an int with a coercion (x :> int)) but not create values directly.
Signatures reference
| In a signature | Meaning |
|---|---|
type t |
abstract type |
type t = int / type t = A | B |
concrete (manifest) type |
type t = private ... |
readable but not constructible from outside |
val f : int -> t |
a value and its type |
exception Bad_input of string |
an exception |
module M : SIG |
a submodule |
include SIG |
all items of another signature |
Test yourself
What does type t (without = ...) in a signature mean?
tis an inttis abstract: its representation is hiddentis a syntax errortis a variant
Where does the signature for stack.ml usually go in a project?
stack.sigstack.mlistack.hdune
Why use a smart constructor like Email.of_string?
- It is faster
- So every value of the type has been validated
- Records cannot be built otherwise
- To avoid pattern matching