鉴于一个简单的工厂:
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
我经常阅读一些编程语言对模块的支持(“一流”)(OCaml,Scala,TypeScript [?]),最近偶然发现了这样的答案,因此将模块引用为 Scala的显着特征之一就是一流的公民。
我以为我很清楚模块化编程的含义,但是在发生这些事件之后,我开始怀疑我的理解...
我认为模块没有什么特别的,但是某些类的实例充当微型库。小型库代码进入一个类,该类的对象是模块。您可以将它们作为依赖项传递给需要该模块提供的服务的任何其他类,因此,任何体面的OOPL都具有一流的模块,但显然没有!
我只想有一个在 Hashtbls 上通用的简单函数,所以我写了这个:
let iter_htbl (type a) (module H : Hashtbl.S with type key = a) htbl =
H.iter (fun _key _v -> ()) htbl
Run Code Online (Sandbox Code Playgroud)
这给了我以下错误:
53 | H.iter (fun _key _v -> ()) htbl
^^^^
Error: This expression has type 'a but an expression was expected of type
'b H.t
The type constructor H.t would escape its scope
Run Code Online (Sandbox Code Playgroud)
如果我写:
53 | H.iter (fun _key _v -> ()) htbl
^^^^
Error: This expression has type 'a but an expression was …Run Code Online (Sandbox Code Playgroud)