使用一流的模块时,类型构造函数“ ...”将逃避其范围

时间:2018-07-09 22:35:13

标签: types module ocaml 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 ()

编译器抱怨:

This has type:
F.t
But somewhere wanted:
F.t
The type constructor F.t would escape its scope

我对OCaml模块还很陌生,不知道如何告诉编译器f的类型为Factory.t

1 个答案:

答案 0 :(得分:7)

这里的问题是F.create ()产生类型为F.t的值,因此f应该具有类型F.t,但这是不可能的,因为F是没有绑定到绑定let module的{​​{1}}之外。

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

F

请注意,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 () 不是有效的类型,因为没有模块绑定到名称Factory.t。模块和模块类型位于单独的命名空间中。