I have the following module signature:
module type X_INT = sig val x: int end
How can i write a function which takes an integer as an argument and generates a module of type X_INT?
let gen_module x = (* generates a module of type X_INT back *)???
Step by step, following the evolution history of OCaml module system:
As an ML functor:
module Gen_module( A : sig val x : int end ) = struct
let x = A.x
end
module M = Gen_module(struct let x = 42 end)
let () = print_int M.x
but it is not a function but a functor.
By local let module:
let gen_module x =
let module M = struct
let x = x
in
print_int M.x
but you can use M only locally.
By the first class module:
let gen_module x = (module struct let x = x end: X_INT)
let m = gen_module 42
let () =
let module M = (val m) in
print_int M.x
the nearest thing to what you want, but needs explicit packing and unpacking.
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