Pattern matching is a particular convenient way to specify
a case analysis on compound data and at the same time to
deconstruct the data.
The essence of pattern matching is to compare the input data with
set of patterns and when the first matching pattern is found,
to perform an associated action. A typical match expression
has the following form:
The result of is compared to the patterns ...
in turn, until the first matching pattern is found, then the
associated is evaluated. If the pattern
contains pattern variables used to match arbitrary input, then
these variables in are bound to the pieces of
matched. Example: If the datum (1 2) is matched by the pattern (a b),
then an associated expression (+ a b) will evaluate to 3.
There are several pattern matching libraries for Scheme. PLT Scheme
comes with two, namely (lib "match.ss" "mzlib") and (lib "plt-match.ss" "mzlib").
The most important difference between them is pattern syntax, where plt-match
is open to future enchancements.
You can view pattern matching as being similar to regular expressions,
but acting on S-expressions instead of text strings. As in Regular Expressions,
patterns allow you to bind parts of the data to variables that can be used in
the expression part. Unlike regular expression systems, patterns can
be used to do things like
Match against the fields of a struct.
Match based on the result of evaluating an expression.
Use quasiquoting to make pattern templates.
Pattern matching is useful in handling markup (HTML or XML translated to S-Expressions),
dispatching functions, and analyzing Scheme code, among other tasks.