如果我有以下仿函数,我如何用 ? 实例化它ListMapFn
?
functor G(M: ORD_MAP where type Key.ord_key = string) :
如果我有以下仿函数,我如何用 ? 实例化它ListMapFn
?
functor G(M: ORD_MAP where type Key.ord_key = string) :
只是为了详细说明仿函数的语法,这里有一些例子。
首先是一些初步声明,以便我们可以处理一些事情。
signature FOO =
sig
val foo : unit -> unit
end
structure FooUnit : FOO =
struct
fun foo () = ()
end
structure FooPrint : FOO =
struct
fun foo () = print "Foo\n"
end
现在。当我们创建只接受一个结构作为参数的函子时,如果我们不想写functor FooFn (f : FOO)
or是可选的functor FooFn (structure f : FOO)
。实际上,这仅适用于函子将一个结构作为参数的情况:
(* Optionally to write "structure f : FOO" as there is only one argument *)
functor FooFn (f : FOO) = struct
val foo = f.foo
end
但是,当函子接受两个或更多参数时,必须使用关键字结构。请注意,仿函数也可以采用其他参数,例如整数值。
(* Note there is no delimiter, just a space and the structure keyword *)
functor FooFooFn (structure f1 : FOO
structure f2 : FOO) =
struct
val foo1 = f1.foo
val foo2 = f2.foo
end
在应用函子并获取结果结构时,我们也有一些选择。第一个是直截了当的。
structure f1 = FooFn (FooUnit)
然而,这有点“特例”,因为我们将其定义为“内联”,省略了struct
andend
部分
structure f2 = FooFn (fun foo () = print "Inlined\n")
或者我们可以更详细一点,并包括struct
andend
部分。然而,这两个都只起作用,因为函子接受一个参数
structure f2_1 = FooFn (struct fun foo () = print "Inlined\n" end)
当函子采用多个参数时,语法有些相同
(* Again note there is no delimiter, so we can have it on the same line *)
structure f3 = FooFooFn (structure f1 = FooUnit structure f2 = FooPrint)
它有点像记录,因为顺序无关紧要
(* And we can even switch the order *)
structure f4 = FooFooFn (structure f2 = FooUnit
structure f1 = FooPrint)
就像是
structure S = G(ListMapFn(type ord_key = string; val compare = String.compare))
或者,如果您更喜欢命名ListMap
实例:
structure ListMap = ListMapFn(type ord_key = string; val compare = String.compare)
structure S = G(ListMap)