OCaml函数返回一个模块。

5

我有以下模块签名:

module type X_INT = sig val x: int end

如何编写一个函数,该函数以整数作为参数并生成类型为 X_INT 的模块?
let gen_module x = (* generates a module of type X_INT back *)???
1个回答

9

一步一步地,按照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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接