The Match Object

The Match object is one of the most commonly used match objects. It matches an expression to a pattern and generates one or more lists of variable bindings. The MatchCommutative object is very similar, but allows a broader range of matches to be generated in cases where the pattern contains objects that have the Commutative property in their object definition.

Pattern matching is processed from the top down. Consider the pattern match:

the pattern matching process may be easier to follow if we write both the expression and the pattern without any rendering:

Add[x, Div[y, Sub[z, 2]]]

Add[a, Div[b, c]]

If the object at the top of the pattern is not a variable, then matching process just compares the expression to the pattern and succeeds if the names (name and namespace) are the same. If the match succeeds, then we move to the parameters and match each parameter of the expression to the corresponding parameter in the pattern. So the next step is to match "x" to "a". Since "a" is a variable, the matching process just binds "a" with the value "x" and reports this step in the match to be a success. The second parameter follows the same process. The Div matches, the variable "b" is bound to the value "y" and the variable "c" is bound to Sub[z, 2]. The matching process is now complete and returns a binding list containing three variables.

Note that it's allowed to create patterns where the same variable appears more than once. For example, consider the match:

When this pattern match is processed, the Div will match, the first parameter of the Div will bind "a" to "x + 1" and when the second parameter is process, since "a" is alreay bound, the pattern matcher will just verify that the expression that was previously bound to the variable matches the current expression.

It's also possible to create patterns that generate more than one list of bindings. The section on Pattern Matching to Monoids describes these patterns in detail.

It's also possible for the expression on the left-hand side of the pattern match to contain terms in the variables namespace. These terms are never treated as variables during the pattern matching. They are just treated like any other term in this case.