有人可以解釋一下:「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稱爲構造函數名稱。
沒有其他匹配。
最佳答案!謝謝 :) –