Patterns and ``Placeholder Variables''
Patterns (_)
Patterns and Pattern Replacement are probably one of the most powerful features of Mathematica. The underscore _ stands for a pattern, a symbol x with an underscore (x_) is recognized as anypattern that matches x. Here are some examples.
Here's a way to put the last input command into words: Search list AList for any pattern that matches "2 × anything" and replace "2 × anything" with a, then output the new AList. Study the following examples carefully:
A qualifier on a pattern can be used to restrict which expressions will match the pattern:
The third member of this result may be a bit surprising; it has to do with the way Mathematica internalizes expressions. In this case it represents the fraction as and it performs the replacement on the exponent (note that it must treat the "-" sign independently of the "1", as it returns "-One" rather than "One"…).
_ all by itself stands for anything. x_ also stands for anything, but gives anything a name for later use.
This is not very useful and it really is doing what you asked for—the first thing it found was AList itself and replaced AList with AppleDumplings.
x^n_ stands for x to any power, and the power can be refered to as n; x_^n_ stands for any expression raised to a power. We can use these ideas to find rules that look like derivatives (this is not a good way to make a symbolic derivative, but it is illustrative):
This is ok, but it has least two problems. The first is that it would be nice to have the rule work for any polynomial...
Another problem is that it will not work for first-order and zeroeth-order terms...
This could be fixed, but it would be much easier to do so by defining functions of a pattern.
It is also possible to have a pattern apply conditionally using a condition. Here is an example that pulls out cases where the first member of a pair of numbers is less than the second.
Created by Wolfram Mathematica 6.0 (06 September 2007) | ![]() |