小智 4
函子本质上是一种根据其他模块编写模块的方法。
一个非常经典的例子是Map.Make标准库中的函子。该函子允许您定义具有特定键类型的映射。
这是一个简单且相当愚蠢的例子:
module Color = struct
type t = Red | Yellow | Blue | Green | White | Black
let compare a b =
let int_of_color = function
| Red -> 0
| Yellow -> 1
| Blue -> 2
| Green -> 3
| White -> 4
| Black -> 5 in
compare (int_of_color a) (int_of_color b)
end
module ColorMap = Map.Make(Color)
Run Code Online (Sandbox Code Playgroud)
加载它ocaml会显示生成的模块的签名:
module Color :
sig
type t = Red | Yellow | Blue | Green | White | Black
val compare : t -> t -> int
end
module ColorMap :
sig
type key = Color.t
type 'a t = 'a Map.Make(Color).t
val empty : 'a t
val is_empty : 'a t -> bool
val mem : key -> 'a t -> bool
val add : key -> 'a -> 'a t -> 'a t
val singleton : key -> 'a -> 'a t
val remove : key -> 'a t -> 'a t
val merge :
(key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t
val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int
val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
val iter : (key -> 'a -> unit) -> 'a t -> unit
val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
val for_all : (key -> 'a -> bool) -> 'a t -> bool
val exists : (key -> 'a -> bool) -> 'a t -> bool
val filter : (key -> 'a -> bool) -> 'a t -> 'a t
val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t
val cardinal : 'a t -> int
val bindings : 'a t -> (key * 'a) list
val min_binding : 'a t -> key * 'a
val max_binding : 'a t -> key * 'a
val choose : 'a t -> key * 'a
val split : key -> 'a t -> 'a t * 'a option * 'a t
val find : key -> 'a t -> 'a
val map : ('a -> 'b) -> 'a t -> 'b t
val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t
end
Run Code Online (Sandbox Code Playgroud)
简单地module ColorMap = Map.Make(Color)创建了一个模块,该模块实现了一个地图,其中键是颜色。现在可以拨打电话ColorMap.singleton Color.Red 1并获取数字 1 的红色地图。
请注意,使用Map.Make有效,因为传递的 module ( Color) 满足函子的要求Map.Make。文档说函子的类型是module Make: functor (Ord : OrderedType) -> S with type key = Ord.t. 这: OrderedType意味着输入模块 ( Color) 必须与OrderedType模块签名一致(我确信有一个更正式的术语)。
为了与输入模块保持一致,必须具有带有签名的OrderedType类型t和函数。换句话说,必须有一种方法来比较 type 的值。如果您查看所报告的类型,这正是所提供的。comparet -> t -> inttocamlColor
何时使用函子是一个更加困难的问题,因为通常有几种可能的设计,每种设计都有自己的权衡。但大多数时候,当库提供函子作为执行某些操作的推荐方式时,您将使用函子。