logo

Pattern Matching Function

   

Added on  2019-09-25

2 Pages1228 Words149 Views
 | 
 | 
 | 
Apatternis an arbitrarily nested list. It can bematchedagainst another arbitrarily nested list, called itssubject.The functionmatchtakes a pattern and a subject as its arguments. Suppose that the pattern contains no keywords. If the pattern equals the subject, thenmatchreturns a true value: actually an empty hash map, which Clojure writes as{}. If the pattern does not equal the subject, thenmatchreturns a false value: actuallynil. In the following examples, the symbol ‘meansreturns.(match '() '()){}(match '() '(a b c))nil(match '(a b c) '(a b c)){}(match '(a (b c)) '(a (b c))){}(match '(a b) '(a (b)))nilThings become more interesting if the pattern contains keywords. Thenmatchmay return a hash map, whose keys are all the keywords from the pattern, and whose values are elements of the subject that correspond to those keywords. If that happens, then we say that the patternmatchesthe subject. The pattern matches the subject in all these examples.(match '(:a) '(test)){:a test}(match '(:a is a :b) '(this is a test)){:b test, :a this}(match '(:a is a :b) '(this is a (hard test))){:b (hard test), :a this}(match '(:a is :b) '((a rose) is (a rose))){:b (a rose), :a (a rose)}(match '(:a is :a) '((a rose) is (a rose))){:a (a rose)}(match '(cons (first :a) (rest :b)) '(cons(first x) (rest x))){:b x, :a x}Clojure writes a hash map as a series of key-value pairs between{and}, separated by commas. The order of the key-value pairs within the hash map does not matter. Also, if a keyword appears more than once in a pattern, then it must match equal elements of the subject each time it appears. For example, the keyword:amatches the nested list(a rose)twice. Sometimes the keywords in the pattern do not correspond to elements of the subject, or the pattern haselements that do not appear in the subject, etc. Thenmatchreturnsnil, and we say that the pattern doesnot match the subject. The pattern does not match the subject in all these examples.(match '(:a) '())nil(match '(:a is a :b) '(this is not a test))nil(match '(:a is a :b) '(x is y))nil(match '(:a is :a) '((a rose) is (not a rose)))nil(match '(cons (first :a) (rest :a)) '(cons (first x) (rest y)))nilAgain, if a keyword appears more than once in a pattern, then it must match equal elements of the subject each time it appears. For example, the keyword:acannot match both(arose)and(notarose),so the pattern in the fourth example does not match.
Pattern Matching Function_1

End of preview

Want to access all the pages? Upload your documents or become a member.