182k views
2 votes
Write a function match that takes a valu * pattern and returns a (string * valu) list option, namely NONE if the pattern does not match and SOME lst where lst is the list of bindings if it does. Note that if the value matches but the pattern has no patterns of the form VariableP s, then the result is SOME []. Hints: Sample solution has one case expression with 7 branches. The branch for tuples uses all_answers and ListPair.zip. Sample solution is 13 lines. Remember to look above for the rules for what patterns match what values, and what bindings they produce. These are hints: We are not requiring all_answers and ListPair.zip here, but they make it easier.

User Xielingyun
by
4.9k points

1 Answer

3 votes

Answer:

Check the explanation

Step-by-step explanation:

fun match (v,p) =

case (v,p) of

(_,Wildcard) => SOME []

|(Const v1,ConstP p1) =>if v1 = p1 then SOME [] else NONE

|(Unit,UnitP) =>SOME []

|(Constructor (s ,v1),ConstructorP (s1, p1) ) => if s = s1 then match(v1,p1) else NONE

|(Tuple vs,TupleP ps) => if List.length vs = List.length ps

then case all_answers match (ListPair.zip(vs,ps)) of

SOME v2=>SOME v2

|_ => NONE

else NONE

|(_, Variable s ) => SOME [(s,v)]

|(_,_) => NONE

User Hodaya Shalom
by
6.0k points