Reading — step 1 of 5
Learn
A module in OCaml groups types and functions. Defined with module:
module Counter = struct
type t = { mutable count : int }
let create () = { count = 0 }
let increment c = c.count <- c.count + 1
let get c = c.count
end
let () =
let c = Counter.create () in
Counter.increment c;
Counter.increment c;
Printf.printf "%d\n" (Counter.get c)
Access via Module.thing. By convention the main type is named t, so Counter.t reads naturally.
Module signatures declare what's exported (interface):
module type COUNTER = sig
type t
val create : unit -> t
val increment : t -> unit
val get : t -> int
end
module Counter : COUNTER = struct
...
end
The signature hides the internal representation — outside code can't see that t is a record with a mutable count field. This is OCaml's encapsulation.
Open brings a module's bindings into scope:
open List
(* Now `map` refers to `List.map` *)
Usually preferred at the top of a file. For local use, let open List in ... opens within an expression.
Functors are modules that take other modules as parameters — type-class-like polymorphism. Beyond this lesson, but worth knowing they exist.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…