|
2.3.3 Naming Pieces of Patterns
Particularly when you use transformation rules, you often need to name pieces of patterns. An object like x_ stands for any expression, but gives the expression the name x. You can then, for example, use this name on the right-hand side of a transformation rule.
An important point is that when you use x_, Mathematica requires that all occurrences of blanks with the same name x in a particular expression must stand for the same expression.
Thus f[x_, x_] can only stand for expressions in which the two arguments of f are exactly the same. f[_, _], on the other hand, can stand for any expression of the form f[x, y], where x and y need not be the same.
The transformation rule applies only to cases where the two arguments of f are identical.
In[1]:= {f[a, a], f[a, b]} /. f[x_, x_] -> p[x]
Out[1]= 
Mathematica allows you to give names not just to single blanks, but to any piece of a pattern. The object x:pattern 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 right-hand side of the rule.

Patterns with names.
This gives a name to the complete form _^_ so you can refer to it as a whole on the right-hand side of the transformation rule.
In[2]:= f[a^b] /. f[x:_^_] -> p[x]
Out[2]= 
Here the exponent is named n, while the whole object is x.
In[3]:= f[a^b] /. f[x:_^n_] -> p[x, n]
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]:= {f[h[4], h[4]], f[h[4], h[5]]} /. f[h[_], h[_]] -> q
Out[4]= 
Now both arguments of f are constrained to be the same, and only the first case matches.
In[5]:= {f[h[4], h[4]], f[h[4], h[5]]} /. f[x:h[_], x_] -> r[x]
Out[5]= 
|