Basic problem with Dune and .mli files

Hi,

I’m new to Dune and OCaml, and I have the fundamental problem that the content of a .mli file is not visible from the corresponding .ml file. I must be missing something very basic.

Minimal example:

dune init proj myproj

(No changes to any dune files after this.)

Add files lib/foo.ml and lib/foo.mli

(* lib/foo.mli *)
module type Foo_sig = sig
	val content : string
end;;
(* lib/foo.ml *)
module Foo : Foo_sig = struct
	let content = "Success!";;
end;;

Replace the code in bin/main.ml

(* bin/main.ml *)
open Myproj.Foo

let () = print_endline Foo.content

This fails with “unbound module type Foo_sig”. If I copy the code of foo.mli into foo.ml, it works perfectly.

Hello,

Interfaces (.mli files) are not “included” in the corresponding implementations (.ml files), so the behaviour you observed is expected: what you write in the .mli is not “visible” from the corresponding .ml. In fact, in OCaml it works the other way around: .mli files are used to restrict the visibility of objects defined in .ml files, so that eg specific types or values, or details thereof, may be kept private to the implementation, hidden from the users of the module.

You may find working through Files, Modules, and Programs - Real World OCaml useful to learn more about how interfaces and implementations work. You can also find an explanation in the manual OCaml - The OCaml language, but it is rather concise, so it may not be very useful at this stage.

Cheers,
Nicolas

1 Like

Hi Nicolas,

thank you very much. So I could instead write:

(* lib/foo.mli *)
module Foo : sig
	val content : string
end;;
(* lib/foo.ml *)
module Foo = struct
	let content = "Success!";;
end;;

(or remove the explicit module declaration/definition entirely).

The pattern of putting a named module type in the .mli is from a project I’m currently looking at (HOLzero). There it works because everything (.mli and .ml) is just thrown into the toplevel by #use or something similar.

Yes, exactly.

Cheers,
Nicolas

Small note, in source code you don’t need ;;

@yawaramin Good point, thank you!

1 Like