使用第一类模块时,类型构造函数"..."将逃避其范围

mbe*_*gal 5 ocaml types module typeerror first-class-modules

鉴于一个简单的工厂:

module type Factory  = sig type t val create : unit -> t end
module FactoryImpl : Factory = struct 
   type t = string
   let create: unit -> t = fun ()  -> "aaa" 
end 
let factory: (module Factory) = (module FactoryImpl)
let f = let module F = (val factory) in F.create ()
Run Code Online (Sandbox Code Playgroud)

编译抱怨:

This has type:
F.t
But somewhere wanted:
F.t
The type constructor F.t would escape its scope
Run Code Online (Sandbox Code Playgroud)

我是OCaml模块的新手,不知道如何告诉编译器f类型Factory.t

gsg*_*gsg 7

这里的问题是F.create ()产生一个类型的值F.t,所以f应该有类型F.t,但这是不可能的,因为F没有绑定在let module那个绑定之外F.

如果将范围扩展F为全局,程序将键入check:

module type Factory = sig
  type t
  val create : unit -> t
end

module FactoryImpl : Factory = struct
  type t = string
  let create: unit -> t = fun () -> "aaa"
end

let factory: (module Factory) = (module FactoryImpl)

module F = (val factory)

let f = F.create ()
Run Code Online (Sandbox Code Playgroud)

请注意,这Factory.t不是有效类型,因为没有绑定到名称的模块Factory.模块和模块类型位于不同的命名空间中.