与OCaml中的多个实现接口

Mat*_*iak 6 ocaml module interface

在OCaml中创建接口的传统方法是什么?通过创建接口文件foo.mli和实现文件foo.ml,可以使用单个实现的接口,但是如何为同一个接口创建多个实现?

gas*_*che 9

您必须使用模块和签名.一个.ml文件隐含地定义模块,和.mli其签名.使用显式模块和签名,您可以将签名应用于多个不同的模块.

请参阅在线书"使用OCaml开发应用程序"的本章.


Gil*_*il' 5

如果您要为同一个签名设置多个实现,请在编译单元内定义签名,而不是作为编译单元,并且(如果需要)类似于模块.标准库中有一个示例:OrderedType签名,描述具有该类型的类型和比较函数的模块:

module type OrderedType = sig
  type t
  val compare : t -> t -> int
end
Run Code Online (Sandbox Code Playgroud)

这个签名是在这两个定义set.mlimap.mli(你可以称其为两种Set.OrderedTypeMap.OrderedType,甚至写出来自己:签名是结构性的).有标准库的若干编译单元有这样的签名(String,Nativeint,等).您还可以定义自己的模块,在定义模块时不需要做任何特殊操作:只要它具有被t调用compare的类型和名为type 的值t -> t -> int,模块就具有该签名.在标准库中有一个稍微详细的示例:Set.Makefunctor构建一个具有签名的模块OrderedType,因此您可以通过这种方式构建集合.

(* All four modules passed as arguments to Set.Make have the signature Set.OrderedType *)
module IntSet = Set.Make(module type t = int val compare = Pervasives.compare end)
module StringSet = Set.Make(String)
module StringSetSet = Set.Make(StringSet)
module IntSetSet = Set.Make(IntSet)
Run Code Online (Sandbox Code Playgroud)