moduleinterfaceocamlocamlbuildutop

How to load .ml file with its corresponding .mli file in utop?


Simply put, let us say I have an implementation file called moduleExample.ml and an interface file in the same directory called moduleExample.mli.

How could I load them together in such a way that the functions not listed in the interface moduleExample.mli are hidden from moduleExample.ml's signature in utop? Additionally, how about type abstraction through the moduleExample.mli file?


Solution

  • I think the proper method to do that, or more generally load within a toplevel a whole project of several modules and interfaces, is to use a build system to compile all modules and link them within a toplevel.

    Using dune, you can do that by doing dune utop directory as described here. For exhaustiveness here's an architecture example:

    dune.ml

    (library
      (name dummy)
      (wrapped false)
    )
    

    ex.ml

    type t = int
    let of_int x = x
    let to_string = string_of_int
    let add = (+)
    let print x = print_string (to_string x)
    

    ex.mli

    type t
    val of_int : int -> t
    val print : t -> unit
    

    Loading all that into utop by doing dune utop . and then using the #show directive on the module Ex, gives:

    utop # #show Ex;;
    module Ex : sig type t val of_int : int -> t val print : t -> unit end