Functors, in fact, are a way of writing modules in terms of other modules.
A pretty classic example is the Map.Makefunctor from the standard library. This functor allows you to define a card with a specific type of key.
Here is a trivial and rather dumb example:
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)
Loading this in ocamlshows the signature of the generated modules:
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
module ColorMap = Map.Make(Color) , , . ColorMap.singleton Color.Red 1 1.
, Map.Make , (Color) Map.Make. , module Make: functor (Ord : OrderedType) -> S with type key = Ord.t. : OrderedType , (Color) ( , ) OrderedType.
OrderedType, t compare t -> t -> int. , t. , ocaml, , Color.
- , , . , -.