【发布时间】:2017-06-10 04:57:14
【问题描述】:
有人可以解释一下:“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
通配符匹配所有内容并生成空的绑定列表。
变量 s 匹配任何值 v 并生成包含 (s,v) 的单元素列表。
UnitP 仅匹配 Unit 并生成空的绑定列表。
ConstP 17 仅匹配 Const 17 并生成空的绑定列表(其他整数也类似)。
TupleP ps 匹配 Tuple vs 形式的值,如果 ps 和 vs 具有相同的长度并且对于所有 i,ps 的第 i 个元素匹配 vs 的第 i 个元素。生成的绑定列表是嵌套模式匹配中的所有列表附加在一起。
ConstructorP(s1,p) 匹配 Constructor(s2,v) 如果 s1 和 s2 是相同的字符串(你可以用 = 比较它们)并且 p 匹配 v。产生的绑定列表是嵌套模式匹配的列表。我们将字符串 s1 和 s2 称为构造函数名称。
没有其他匹配项。
【问题讨论】:
标签: functional-programming sml ml