有人可以解释一下:“g 的描述”吗? f1 如何获取单位并返回一个 int 以及其余的我也很困惑!!
(* Description of g:
* g takes f1: unit -> int, f2: string -> int and p: pattern, and returns
* an int. f1 and f2 are used to specify what number to be returned for
* each Wildcard and Variable in p respectively. The return value is the
* sum of all those numbers for all the patterns wrapped in p.
*)
datatype pattern = Wildcard
| Variable of string
| UnitP
| ConstP of int
| TupleP of pattern list
| ConstructorP of string * pattern
datatype valu = Const of int
| Unit
| Tuple of valu list
| Constructor of string * valu
fun g f1 f2 p =
let
val r = g f1 f2
in
case p of
Wildcard => f1 ()
| Variable x => f2 x
| TupleP ps => List.foldl (fn (p,i) => (r p) + i) 0 ps
| ConstructorP (_,p) => r p
| _ => 0
end
通配符匹配所有内容并生成空的绑定(bind)列表。
变量 s 匹配任何值 v 并生成包含 (s,v) 的单元素列表。
UnitP 仅匹配 Unit 并生成空绑定(bind)列表。
ConstP 17 仅匹配 Const 17 并生成空绑定(bind)列表(对于其他整数也类似)。
TupleP ps 匹配 Tuple vs 形式的值,如果 ps 和 vs 具有相同的长度,并且对于所有 i,ps 的第 i 个元素与 vs 的第 i 个元素匹配。生成的绑定(bind)列表是附加在一起的嵌套模式匹配的所有列表。
ConstructorP(s1,p) 如果 s1 和 s2 是相同的字符串(可以使用 = 进行比较)并且 p 与 v 匹配,则与 Constructor(s2,v) 匹配。生成的绑定(bind)列表为嵌套模式匹配的列表。我们将字符串 s1 和 s2 称为构造函数名称。
没有其他匹配。
最佳答案
Can someone please explain the: "description of g"? How can f1 takes unit and returns an int & the rest i'm confused about too!!
函数
g
的类型为 (unit → int) → (string → int) → pattern → int,因此它需要三个(柯里化(Currying))参数其中两个是函数,一个是模式。参数
f1
和f2
必须是始终返回相同常量的确定性函数,或者是具有副作用、可以返回任意整数的函数/字符串,分别由外部源确定。由于评论谈到“为每个通配符和变量返回什么数字”,因此听起来更有可能
f1
应在不同时间返回不同的数字(我不确定 number 在f2
的情况下指的是什么!)。一个定义可能是这样的:local val counter = ref 0 in fun uniqueInt () = !counter before counter := !counter + 1 fun uniqueString () = "s" ^ Int.toString (uniqueInt ()) end
虽然这只是一个猜测。此定义仅适用于
Int.maxInt
。注释将
g
的返回值描述为[...] the sum of all those numbers for all the patterns wrapped in p.
由于这些数字没有赋予任何含义,因此似乎
g
没有任何实际用途,而是比较任意给定的f1
集的输出和f2
针对未给出的任意测试。包罗万象的模式通常是不好的:
... | _ => 0
Nothing else matches.
原因是,如果您使用其他类型的模式扩展pattern,编译器将不会通知您函数
g
中缺少模式;对于可能尚未定义的情况,包罗万象的内容会错误地暗示其含义。
关于functional-programming - 模式匹配 SML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41844358/