Skip to content

Making OCaml recursive modules convenient

Joel Reymont
Joel Reymont
1 min read

Jane St posted about recursive OCaml modules from recursive signatures a while ago.

module rec Even : sig
  type t = Zero | Succ of Odd.t
end = Even
and Odd : sig
  type t = Succ of Even.t
end = Odd

You cannot have functions inside recursive modules defined this way which is really inconvenient. You can bring the convenience back with just a couple of wrappers, though!

module rec Even' : sig
  type t = Zero | Succ of Odd.t
end = Even'
and Odd' : sig
  type t = Succ of Even.t
end = Odd'

module Even = struct
  include Even'
  (* put your functions here *)
end

module Odd = struct
  include Odd'
  (* put your functions here *)
end

Then just use the Even and Odd modules going forward.

Why bother with rec.modules in the first place? Compiler abstract syntax trees (ASTs) are recursive, e.g. expressions depend on themselves. Recursive modules are great to wrap an AST!

OCaml