# Applying Transformation Rules

expr/.lhs->rhs | apply a transformation rule to expr |

expr/.{lhs_{1}->rhs_{1},lhs_{2}->rhs_{2},...} | try a sequence of rules on each part of expr |

Applying transformation rules.

In[1]:= |

Out[1]= |

In[2]:= |

Out[2]= |

Applying lists of transformation rules.

In[3]:= |

Out[3]= |

In[4]:= |

Out[4]= |

In[5]:= |

Out[5]= |

When you use , each rule is tried in turn on each part of expr. As soon as a rule applies, the appropriate transformation is made, and the resulting part is returned.

In[6]:= |

Out[6]= |

In[7]:= |

Out[7]= |

The replacement tries each rule just once on each part of expr.

In[8]:= |

Out[8]= |

In[9]:= |

Out[9]= |

Sometimes you may need to go on applying rules over and over again, until the expression you are working on no longer changes. You can do this using the repeated replacement operation (or ReplaceRepeated[expr, rules]).

expr/.rules | try rules once on each part of expr |

expr//.rules | try rules repeatedly until the result no longer changes |

Single and repeated rule application.

In[10]:= |

Out[10]= |

In[11]:= |

Out[11]= |

In[12]:= |

Out[12]= |

In[13]:= |

Out[13]= |

When you use (pronounced "slash-slash-dot"), *Mathematica* repeatedly passes through your expression, trying each of the rules given. It goes on doing this until it gets the same result on two successive passes.

If you give a set of rules that is circular, then can keep on getting different results forever. In practice, the maximum number of passes that makes on a particular expression is determined by the setting for the option MaxIterations. If you want to keep going for as long as possible, you can use ReplaceRepeated[expr, rules, MaxIterations->Infinity]. You can always stop by explicitly interrupting *Mathematica*.

In[14]:= |

Out[14]= |

The replacement operators and share the feature that they try each rule on every subpart of your expression. On the other hand, Replace[expr, rules] tries the rules only on the whole of expr, and not on any of its subparts.

You can use Replace, together with functions like Map and MapAt, to control exactly which parts of an expression a replacement is applied to. Remember that you can use the function ReplacePart[expr, new, pos] to replace part of an expression with a specific object.

In[15]:= |

Out[15]= |

In[16]:= |

Out[16]= |

In[17]:= |

Out[17]= |

In[18]:= |

Out[18]= |

expr/.rules | apply rules to all subparts of expr |

Replace[expr,rules] | apply rules to the whole of expr only |

Replace[expr,rules,levspec] | apply rules to parts of expr on levels specified by levspec |

Applying rules to whole expressions.

In[19]:= |

Out[19]= |

In[20]:= |

Out[20]= |

In[21]:= |

Out[21]= |

In[22]:= |

Out[22]= |

In[23]:= |

Out[23]= |

Replace[expr,rules] | apply rules in one way only |

ReplaceList[expr,rules] | apply rules in all possible ways |