gpt4 book ai didi

functional-programming - 如何在 SML 中实例化仿函数?

转载 作者:行者123 更新时间:2023-12-04 08:41:19 24 4
gpt4 key购买 nike

如果我有以下仿函数,如何使用 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)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)

然而,这有点“特例”,因为我们将其定义为“内联”,省略了 structend 部分

structure f2 = FooFn (fun foo () = print "Inlined\n")

或者我们可以更详细一些,包括 structend 部分。然而,这两个都只起作用,因为仿函数接受一个参数

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)

关于functional-programming - 如何在 SML 中实例化仿函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14513002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com