给出一个简单的工厂:
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
答案 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
。模块和模块类型位于单独的命名空间中。