









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










fun diff(nil,y) = y (1) | diff(x,nil) = x (2) | diff(hdx::tlx,hdy::tly) = diff(tlx,tly) (^) The set of patterns is exhaustive (^) Patterns (1) and (2) are non-disjoint or overlap because there is at least one value for which both patterns match (i.e., (nil,nil)) (^) Ordering of rules impose a priority ordering among patterns. (^) Patterns must be linear: no variable in a pattern can occur more than once: (^) fun equal(x,x) = true (* this is illegal *) (^) Patterns should not be redundant: they should match some value, not matched by earlier patterns.
Patterns match values which are also tree-shaped structures formed by the application of constructors and tupling:
Value term t = (true, Cons(1,Nil)) Following sequence of patterns of type (bool * intlist)): p1 = (true, _) p2 = (false, nil) p3 = (false, Cons(x,Nil)) p4 = (false, Cons(y,z)) p1 agrees with t on its first component. p2, p3, p4 do not. p1 also agrees on its second term. p3 and p4 have a pattern of the form Cons(p’) and agree with t on this component. p3 and p4 also agree with t on both arguments to Cons.
A pattern p matches a term t iff p agrees with t on all subterms of t. The matching problem: Given a finite sequence of patterns p1,…,pn and value term t, find the first pattern in the sequence which matches t, if one exists. (We elide issue of typing here.)
(^) Naïve approach:
(^) Better strategy: analyze pattern sequence at compile-time, and try to minimize number of case discrimination tests.
(^) Two choices: test either on first component or second component.
(^) Three additional tests required: (^) Test on first component of t. (leads to desired result) (^) Test on first component of Cons. (^) Test on second component of Cons.
1 {p1,p2,p3,p4} {p1} true false 2 {p2,p3,p4} {p2} Nil Cons 2,2 {p3,p4} {p3} {p4] Minimal decision tree for example
16 1 {p1,p2} {p1} nil cons 2 {p2} {p2} nil cons {} 2 {p1,p2} {p1,p2} nil cons 1 {p1} {p1} nil cons {}
{p1} {p2} nil (^) cons
(^) Favoring choice of tests with low branching factor first. (^) type color = red | blue | green (^) (p1) (true, green), (p2) (false, green) 17 2 {p1,p2} {} red,blue green 1 {p1,p2} {p1} true false {p2} 1 {p1,p2} {p1} true false 2 {p2} {} red,blue (^) green {p2}
{} {p1} red,blue (^) green