A pattern is an arbitrarily nested list.

Added on - 25 Sep 2019

  • 2


  • 1228


  • 105


  • 0


Trusted by +2 million users,
1000+ happy students everyday
Showing pages 1 to 1 of 2 pages
Apatternis an arbitrarily nested list. It can bematchedagainst another arbitrarily nested list, calleditssubject.The functionmatchtakes a pattern and a subject as its arguments. Suppose that the patterncontains no keywords. If the pattern equals the subject, thenmatchreturns a true value: actually anempty 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 thatcorrespond to those keywords. If that happens, then we say that the patternmatchesthe subject. Thepattern 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), :athis}(match '(:a is :b) '((a rose) is (a rose))){:b (a rose), :a (arose)}(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. Theorder of the key-value pairs within the hash map does not matter. Also, if a keyword appears more thanonce in a pattern, then it must match equal elements of the subject each time it appears. For example, thekeyword: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 subjecteach time it appears. For example, the keyword:acannot match both(arose)and(notarose),so the pattern in the fourth example does not match.
You’re reading a preview
Preview Documents

To View Complete Document

Click the button to download
Subscribe to our plans

Download This Document