Making OCaml recursive modules convenient
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!