I would like to give two .ml sources files the same name in different directories in my source tree, but the OCaml documentation states that the a file A.ml is exported as a toplevel module A = struct ... end. If I have two files X/A.ml and Y/A.ml, how can I refer to them both from B.ml?
Modules can contain modules, i.e. you can have a hierarchy of modules.
From the B.ml point of view, you can see two modules named X.A
and Y.A
.
They can even both have a function named foo
, those functions would be seen as X.A.foo
and Y.A.foo
.
Beware that if you open
both modules X
and Y
, the module A
from Y
will hide the module A
from X
.
That was from the namespace point of view. Now, about the source tree. One way would be to have those files:
The file x.ml is automatically generated and contains just this:
module A = struct
(*The contents of x/a.ml is included here*)
end
Likewise for y.ml There are several preprocessors able to include a file: cpp, camlp4, camlp5, camlmix...
This set of automatically generated files (and regenerated each time the source changes) is not very satisfiying, I will look at other answers.
You can also have a look at ocamlc -pack
, but when I tried it a long time ago there was a problem with ocamldoc
unable to have x/a.ml and y/a.ml . So check this before you settle on a tool.
You cannot link modules with the same name into the same program. For example, extensions to the standard library, such as Batteries and Core, are forced to give standard modules a different name. In Batteries, the List module is called BatList. Then, they provide a wrapper module Batteries, within which the module is renamed with by doing module List = BatList
. The overall path to this module is Batteries.List
, so there is no clash with the Standard Library's top level List
. Finally, the recommended way of using Batteries and Core is to do open Batteries
and open Core
, thereby giving you access to their additional list functions under the module name List
.
Thus the only option is to rename your modules, but you can do this in two ways:
Change the base names of the modules, e.g. call them A and B.
Put the modules under another module, e.g. name them X.A and Y.A. If you want to keep your current directory structure, you can use OCaml's -pack option. Personally, I find this option too restrictive and always end up doing manual packing, i.e. the technique described above used by Batteries and Core.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With