我得到了关于 OCaml 中函子的以下代码:
type comparison = Less | Equal | Greater;;
module type ORDERED_TYPE =
sig
type t
val compare: t -> t -> comparison
end
;;
module Set =
functor (Elt: ORDERED_TYPE) ->
struct
type element = Elt.t
type set = element list
let empty = []
let rec add x s =
match s with
| [] -> [x]
| hd :: tl ->
match Elt.compare x hd with
| Equal -> s
| Less -> x :: s
| Greater -> hd :: add x tl
let rec member x s =
match s with
| [] -> false
| hd :: tl ->
match Elt.compare x hd with
| Equal -> true
| Less -> false
| Greater -> member x tl
end
;;
module OrderedString : ORDERED_TYPE =
struct
type t = string
let compare x y =
if x = y then Equal
else if x < y then Less
else Greater
end
;;
module StringSet = Set(OrderedString);;
let out = StringSet.member "foo" (StringSet.add "foo" StringSet.empty);; (*compile error, where "foo" is expected OrderedString.t but actually is string*)
Run Code Online (Sandbox Code Playgroud)
上述错误可以通过消除: ORDERED_TYPEin来避免module OrderedString : ORDERED_TYPE =
就是不明白为什么。
类似地,如果模块中有任何类型,例如
module A = struct type t = string end;;
Run Code Online (Sandbox Code Playgroud)
如何将字符串值指定为类型A.t而不是实际类型string
谢谢。
您可以在标准库中查看它是如何完成的:set.mli。函子的签名是
module Make (Ord : OrderedType) : S with type elt = Ord.t
Run Code Online (Sandbox Code Playgroud)
该with type elt = Ord.t部分表示该elt类型不是抽象的。