Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml function that returns a module

Tags:

module

ocaml

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 *)???
like image 774
objmagic Avatar asked Feb 13 '23 00:02

objmagic


1 Answers

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.

like image 131
camlspotter Avatar answered Feb 19 '23 11:02

camlspotter