Search code examples
moduleocamlmutual-recursion

Why the requirement for signatures in mutually recursive modules in OCaml?


When using mutually recursive module definitions in OCaml, it's necessary to give signatures, even in the .ml file. This is an annoyance where I also want to expose a given interface from the .mli, as I end up repeating the signature twice. :(!

module rec Client : sig
  type ('serv,'cli) t

  (* functions ... *)
end = struct
  type ('serv,'cli) t =
    { server: ('serv,'cli) Server.t
    ; (* other members ... *)
    }
end
and Server : sig
  type ('serv,'cli) t

  (* functions ... *)
end = struct
  type ('serv,'cli) t =
    { mutable clients: ('serv,'cli) Client.t list
    ; mutable state: 'serv
    }

  (* functions again ... *)
end

This is a rough approximation of what I'm doing (Client type objects know the Server that instantiated them. Servers know their Clients).

Of course, the signatures are repeated in the .mli. Why is this necessary?

(Note: I'm not complaining, but actually want to know if there's a type-theory or "hard compiler problem"-related reason for this.)


Solution

  • My guess : in order to compile recursive modules compiler needs type annotations for implementation. In mli file (if you are using any) types of those modules can be further restricted or hidden altogether, so in general case it is not sensible for compiler to expect to find useful types in mli wrt resolving type-recursion.