no way to compare when less than two revisions

Differences

This shows you the differences between two versions of the page.


doc:patmatch [2014/01/09 16:54] (current) – created gkazhoya
Line 1: Line 1:
 +====== Pattern Matching ======
  
 +It's used for finding patterns in lists, i.e. matching the given pattern to the given list.
 +It's located in the ''cram_core'' stack, in package ''cram_utilities'', more specifically, the whole implementation is in ''patmatch.lisp''.
 +
 +The main function is 
 +<code lisp>(defun pat-match (pat seq &optional (bdgs nil) &rest rest) ... )</code>
 +where ''pat'' is the pattern which is a list that can contain pattern variables, and ''seq'' is the sequence to match to which is a list which may not contain pattern variables. Pattern variable is a Lisp symbol that starts with ''?'' (more about the naming comes later). The function goes through the pattern and creates an association list with the pattern variables on the left side and their corresponding values from ''seq'' on the right side. For example:
 +<code lisp>CUT> (pat-match '(a b ?x ?y) '(a b c d))</code>
 +which results in
 +<code lisp>
 +((?Y . D) (?X . C))
 +T
 +</code>
 +The first result is the association list, which we call the //bindings//, and the second result says if the pattern matched the sequence or not. Note, that if the bindings list is empty it doesn't mean that the pattern didn't match: e.g.
 +<code lisp>CUT> (pat-match '(a b c d) '(a b c d))</code>
 +returns
 +<code lisp>
 +NIL
 +T
 +</code>
 +
 +Valid pattern variable names include, e.g. '''?var'', '''?'', '':?var'' and ''(gensym "?")''. For more examples check the unit tests of ''cram_utilites''.
 +
 +If you don't want to add a certain variable to the list of bindings, name it "'?_", e.g.:
 +<code lisp>CUT> (pat-match `(a b ?_ ?foo) '(a b c d))</code>
 +results in
 +<code lisp>
 +((?FOO . D))
 +T
 +</code>