WOLFRAM LANGUAGE TUTORIAL

Naming Pieces of Patterns

Particularly when you use transformation rules, you often need to name pieces of patterns. An object like stands for any expression, but gives the expression the name x. You can then, for example, use this name on the righthand side of a transformation rule.

An important point is that when you use , the Wolfram Language requires that all occurrences of blanks with the same name x in a particular expression must stand for the same expression.

Thus can only stand for expressions in which the two arguments of are exactly the same. , on the other hand, can stand for any expression of the form , where x and y need not be the same.

The transformation rule applies only to cases where the two arguments of are identical.
In[1]:=
Click for copyable input
Out[1]=

The Wolfram Language allows you to give names not just to single blanks, but to any piece of a pattern. The object in general represents a pattern which is assigned the name x. In transformation rules, you can use this mechanism to name exactly those pieces of a pattern that you need to refer to on the righthand side of the rule.

_any expression
x_any expression, to be named x
x:patternan expression to be named x, matching pattern

Patterns with names.

This gives a name to the complete form so you can refer to it as a whole on the righthand side of the transformation rule.
In[2]:=
Click for copyable input
Out[2]=
Here the exponent is named , while the whole object is .
In[3]:=
Click for copyable input
Out[3]=

When you give the same name to two pieces of a pattern, you constrain the pattern to match only those expressions in which the corresponding pieces are identical.

Here the pattern matches both cases.
In[4]:=
Click for copyable input
Out[4]=
Now both arguments of are constrained to be the same, and only the first case matches.
In[5]:=
Click for copyable input
Out[5]=