Nos*_*tap 3 functional-programming ml sml
如果我有以下仿函数,我怎样才能用ListMapFn?实例化它?
functor G(M: ORD_MAP where type Key.ord_key = string) :
Run Code Online (Sandbox Code Playgroud)
只是详细说明仿函数的语法,这里有一些例子.
首先是一些初步声明,所以我们有一些工作要做.
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
Run Code Online (Sandbox Code Playgroud)
现在.当我们创建只使用一个结构作为参数的仿函数时,可选地,如果我们不想写functor FooFn (f : FOO)或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
Run Code Online (Sandbox Code Playgroud)
但是,当函子接受两个或多个参数时,必须使用关键字结构.请注意,仿函数也可以采用其他参数,例如整数值.
(* 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
Run Code Online (Sandbox Code Playgroud)
在应用仿函数时,我们还有一些选项,并返回结果.第一个是直截了当的.
structure f1 = FooFn (FooUnit)
Run Code Online (Sandbox Code Playgroud)
然而,这个是一个"特殊情况",因为我们定义它"内联",省略struct和end部分
structure f2 = FooFn (fun foo () = print "Inlined\n")
Run Code Online (Sandbox Code Playgroud)
或者我们可以多一点冗长,包括struct与end部分.然而,这两者都有效,因为仿函数需要一个参数
structure f2_1 = FooFn (struct fun foo () = print "Inlined\n" end)
Run Code Online (Sandbox Code Playgroud)
当函子接受多个参数时,语法有些相同
(* Again note there is no delimiter, so we can have it on the same line *)
structure f3 = FooFooFn (structure f1 = FooUnit structure f2 = FooPrint)
Run Code Online (Sandbox Code Playgroud)
它有点像记录,因为顺序无关紧要
(* And we can even switch the order *)
structure f4 = FooFooFn (structure f2 = FooUnit
structure f1 = FooPrint)
Run Code Online (Sandbox Code Playgroud)