ReplaceAll, ReplaceRepeated
The next cell demonstrates the basic use of ReplaceAll.
Evaluation of the previous cell doesn't change the value of (y) or (expr).
If we provide a list of rules or delayed rules on the right side of ReplaceAll several replacements are made. The difference between (lhs→rhs) and (lhs:→rhs) is covered in the section on Rule instead of RuleDelayed.
ReplaceAll considers a list of rules starting from the left. In the next
cell the rule (y→5) is used and the symbol (y) is no longer in the
expression. As a result the rules (y→3) and (y→4) are not
used.
If we provide a list of lists of replacement rules on the right side of
ReplaceAll we get a list of results from making several sets of replacements.
Any combination of pattern matching constructs can be used on the left side of rules. The next cell gives a non-trivial example. Nuances of pattern matching are discussed in another section.
Once ReplaceAll changes a part of an expression no further replacements are
made on that portion of the expression or any of it's subparts. For example
the rule in the next cell is used once on each logrithm.
ReplaceRepeated works just like ReplaceAll except it continues trying the
rules until the result no longer changes. In the next cell ReplaceRepeated
fully expands each logrithm.
The order of matching patterns and making replacements
If we put a Print statment at the right place we can see the order that the
pattern matcher considers different parts of an expression for replacement.
Notice the Print statement never returns True, so nothing can match the
pattern, but each pattern considered is printed.
Since ReplaceAll starts making replacements at the highest level, Log[x] in
the next cell is changed to Log[x+1].
Replace makes replacements starting at the deepest level, so in the next cell Log[x] is changed to Log[a x].
In the next cell we can see (expr/.rules) evaluates (expr), then it evaluates (rules), it makes the replacements without evaluating the new results. A new expression is returned in this case, and this new expression is allowed to evaluate to 11.
In the next cell we can see (expr//.rules) evaluates (expr), then it evaluates (rules). The first replacement made is and evaluates to 5. Then the replacement rule is used again to change Log[a b] to (Log[a]+Log[b] ).
Created by Mathematica (May 16, 2004)