8

给定一个简单的工厂:

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

4

1 回答 1

11

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

如果将范围扩展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不是有效类型,因为没有模块绑定到 name Factory。模块和模块类型位于不同的命名空间中。

于 2018-07-10T05:21:10.003 回答