This is documentation for Mathematica 5, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.2)

Documentation / Mathematica / The Mathematica Book / Principles of Mathematica / Transformation Rules and Definitions /

2.5.2 Manipulating Sets of Transformation Rules

You can manipulate lists of transformation rules in Mathematica just like other symbolic expressions. It is common to assign a name to a rule or set of rules.

This assigns the "name" sinexp to the trigonometric expansion rule.

In[1]:= sinexp = Sin[2 x_] -> 2 Sin[x] Cos[x]


You can now request the rule "by name".

In[2]:= Sin[2 (1 + x)^2] /. sinexp


You can use lists of rules to represent mathematical and other relations. Typically you will find it convenient to give names to the lists, so that you can easily specify the list you want in a particular case.

In most situations, it is only one rule from any given list that actually applies to a particular expression. Nevertheless, the /. operator tests each of the rules in the list in turn. If the list is very long, this process can take a long time.

Mathematica allows you to preprocess lists of rules so that /. can operate more quickly on them. You can take any list of rules and apply the function Dispatch to them. The result is a representation of the original list of rules, but including dispatch tables which allow /. to "dispatch" to potentially applicable rules immediately, rather than testing all the rules in turn.

Here is a list of rules for the first five factorials.

In[3]:= facs = Table[f[i] -> i!, {i, 5}]


This sets up dispatch tables that make the rules faster to use.

In[4]:= dfacs = Dispatch[facs]


You can apply the rules using the /. operator.

In[5]:= f[4] /. dfacs


Creating and using dispatch tables.

For long lists of rules, you will find that setting up dispatch tables makes replacement operations much faster. This is particularly true when your rules are for individual symbols or other expressions that do not involve pattern objects. Once you have built dispatch tables in such cases, you will find that the /. operator takes a time that is more or less independent of the number of rules you have. Without dispatch tables, however, /. will take a time directly proportional to the total number of rules.