Qualified imports in OCaml are possible but why aren't they used more?

module
#1

I’ve noticed that idiomatic OCaml does not seem to use qualified imports in code very much. Mostly there is the use of open keyword in code or you may have something verbose like Core_kernel.Map.empty (or shorter Map.empty if Core_kernel is open).

In Haskell there are a lot of qualified imports so instead of Core_kernel.Map.empty people might do a qualified import and subsequently refer to things with like M.empty – the M serving as a reminder where the empty function has come from.

You can emulate this in OCaml easily by doing:

module M = struct include Core_kernel.Map end
...
(* possible to use M.empty now *)
M.empty
...

Am I correct in my understanding?

Question
Why aren’t qualified imports used more often? I can see this being useful in tutorials. A lot of tutorial code has a bunch of opens and then its difficult to understand where things are coming from.

I am aware of the shortcut

Core_kernel.Map.( (* ocaml code here *) )

but it is not very satisfying to me.

#2

It’s a question of style, OCaml gives a lot of freedom there.
Personally I use very rarely open but a lot of qualified imports
(often as single-letter modules).

5 Likes
#3

To my knowledge, the following statement produce a new module space with a copy of the module Core_kernel.Map, which increases the executable size and makes it hard to make some optimizations on the dependency tree:

module M = struct include Core_kernel.Map end

Instead of creating a copy, you should prefer to use a module alias:

module M = Core_kernel.Map

This also works at expression level:

let module M = Core_kernel.Map in ...
7 Likes