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.

"index_72.gif"

"index_73.gif"

"index_74.gif"

"index_75.gif"

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:

"index_76.gif"

"index_77.gif"

"index_78.gif"

"index_79.gif"

"index_80.gif"

A qualifier on a pattern can be used to restrict which expressions will match the pattern:

"index_81.gif"

"index_82.gif"

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 "index_83.gif"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.

"index_84.gif"

"index_85.gif"

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):

"index_86.gif"

"index_87.gif"

"index_88.gif"

"index_89.gif"

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...

"index_90.gif"

"index_91.gif"

"index_92.gif"

"index_93.gif"

"index_94.gif"

"index_95.gif"

Another problem is that it will not work for first-order and zeroeth-order terms...

"index_96.gif"

"index_97.gif"

"index_98.gif"

"index_99.gif"

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.

"index_100.gif"

"index_101.gif"

"index_102.gif"

"index_103.gif"


Created by Wolfram Mathematica 6.0  (06 September 2007) Valid XHTML 1.1!