返回模块的OCaml函数

时间:2014-09-17 17:54:45

标签: module ocaml

我有以下模块签名:

module type X_INT = sig val x: int end

如何编写一个以整数作为参数并生成X_INT类型的模块的函数?

let gen_module x = (* generates a module of type X_INT back *)???

1 个答案:

答案 0 :(得分:6)

按照OCaml模块系统的演变历史逐步进行:

作为ML仿函数:

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

但它不是函数,而是函子。

通过本地let模块:

let gen_module x = 
  let module M = struct
    let x = x
  in
  print_int M.x

但您只能在本地使用M.

通过第一类模块:

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

最接近您想要的东西,但需要明确的打包和拆包。

相关问题