有人可以解释一下:“g的描述”吗? f1如何取得单位并返回一个int &其余的我也很困惑!模式匹配SML?
(* 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
通配符匹配一切并产生绑定的空单。
变量s匹配任何值v并产生保存(s,v)的单元素列表。
单位P只匹配Unit并产生绑定的空列表。
ConstP 17只匹配Const 17并产生绑定的空列表(对于其他整数也是类似的)。
TupleP PS形式元组的值匹配VS如果PS VS和具有相同的长度和对于所有的i,PS的第i个元件的相对于绑定产生的列表中的第i个元素相匹配是来自嵌套模式匹配的所有列表附加在一起。
ConstructorP(S1,P)匹配构造(S2,v)如S1和S2相同的字符串(可以将它们与=比较)和p匹配诉产生绑定的列表是从所述列表中嵌套模式匹配。我们将字符串s1和s2称为构造函数名称。
没有其他匹配。
最佳答案!谢谢 :) –