簡體   English   中英

返回模塊的OCaml函數

[英]OCaml function that returns a module

我有以下模塊簽名:

module type X_INT = sig val x: int end

如何編寫以整數作為參數並生成X_INT類型的模塊的函數?

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

逐步遵循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

最接近您想要的東西,但是需要明確的打包和拆包。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM