Reputation: 51
If I have two modules A and B, and define a type in module A,
type t1 = THIS of int | THAT of char
and then want to do some pattern matching or constructing objects of that type in module B, I have to use something like
A.THIS(3)
This is what it forces me to do, even after I have some statement like
type t2 = A.t1
in the signature and implementation of the module. What if I wanted to be less verbose and not use 'A.' in module B? I could make a whole new type and a function to convert one to the other, but this seems clunky. Is there anything I'm missing?
Upvotes: 3
Views: 575
Reputation: 3970
You can use the open
keyword, which is similar to Java's import
:
module A = struct
type t1 = THIS of int | THAT of char
end
module B = struct
open A
let b = THIS 3
end
If you want to avoid polluting the global namespace of module B
, it is possible to use the let open ... in ...
expression, which was introduced in OCaml 3.12:
module A = struct
type t1 = THIS of int | THAT of char
end
module B = struct
let b = let open A in THIS 3
end
In some special (and relatively rare) cases, you may want to or have to use the include
keyword instead of open
. You can find good explanation for their difference in the Opening a module path and Including the components of another structure sections of the OCaml manual.
Upvotes: 8
Reputation: 66823
I'm not a module expert, but you can do this (I just tested it):
(In b.ml):
type t1 = A.t1 = THIS of int | THAT of char
You can also open
the A module, of course. Often this is too drastic for my taste. To make it less drastic, you could define the type in a third module and open it in both A and B.
Upvotes: 5