Introduction to Programming with Mathematica, Third Edition

The use of rules to transform expressions from one form to another is one of the most powerful and useful tools available in the Mathematica programming language. The thousands of rules built in to Mathematica can be expanded limitlessly through the creation of user-defined rules. Rules can be created to change the form of expressions, to filter data based on some criteria, and can be set up to apply to broad classes of expressions or limited to certain narrow domains through the use of appropriate pattern matching techniques. These rules can perform many of the tasks normally associated with more traditional programming constructs, such as we have discussed in the chapters on procedural and functional programming. In this chapter we will discuss the structure and application of rules to common programming tasks and look at their application in some concrete examples.
Users of Mathematica typically first encounter rules as the output to many built-in functions. For example, the Solve function returns its solutions as a list of rules.

They are also used to specify options for functions and replacement rules in many kinds of computations.
<i class="emphasis">In[2]:=</i> <b class="bold">FactorInteger[5, GaussianIntegers <span class="unicode">?</span> True]</b><span class="inlinequation"><span class="inlinemediaobject"><img alt="Image from book"> border="0"> height="18"> id="IMG_156"> src="https://images.books24x7.com/bookimages/id_10817/figu149_2.jpg"> title=""> width="316"></span></span> <i class="emphasis">In[3]:=</i> <b class="bold">StringReplace ["acgttttccctgagcataaaaacccagcaatacg",</b> <b class="bold">{"ca" <span class="unicode">?</span> "CA", "tt" <span class="unicode">?</span> "TT"}]</b> <i class="emphasis">Out[3]=</i> acgTTTTccctgagCAtaaaaaccCAgCAatacgWhen...