objmagic
objmagic

Reputation: 1028

OCaml function that returns a module

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 *)???

Upvotes: 5

Views: 1462

Answers (1)

camlspotter
camlspotter

Reputation: 9040

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.

Upvotes: 9

Related Questions