This is documentation for Mathematica 3, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.1)
 Documentation / Mathematica / The Mathematica Book / Practical Introduction / Functions and Programs  /

1.7.4 Transformation Rules for Functions

Section 1.4.2 discussed how you can use transformation rules of the form x->value to replace symbols by values. The notion of transformation rules in Mathematica is, however, quite general. You can set up transformation rules not only for symbols, but for any Mathematica expression.

  • Applying the transformation rule x->3 replaces x by 3.
  • In[1]:= 1 + f[x] + f[y] /. x -> 3


  • You can also use a transformation rule for f[x]. This rule does not affect f[y].
  • In[2]:= 1 + f[x] + f[y] /. f[x] -> p


  • f[t_] is a pattern that stands for f with any argument.
  • In[3]:= 1 + f[x] + f[y] /. f[t_] -> t^2


    Probably the most powerful aspect of transformation rules in Mathematica is that they can involve not only literal expressions, but also patterns. A pattern is an expression such as f[t_] which contains a blank (underscore). The blank can stand for any expression. Thus, a transformation rule for f[t_] specifies how the function f with any argument should be transformed. Notice that, in contrast, a transformation rule for f[x] without a blank, specifies only how the literal expression f[x] should be transformed, and does not, for example, say anything about the transformation of f[y].
    When you give a function definition such as f[t_]:=t^2, all you are doing is telling Mathematica to automatically apply the transformation rule f[t_]->t^2 whenever possible.

  • You can set up transformation rules for expressions of any form.
  • In[4]:= f[a b] + f[c d] /. f[x_ y_] -> f[x] + f[y]


  • This uses a transformation rule for x^p_.
  • In[5]:= 1 + x^2 + x^4 /. x^p_ -> f[p]


    Sections 2.3 and 2.4 will explain in detail how to set up patterns and transformation rules for any kind of expression. Suffice it to say here that in Mathematica all expressions have a definite symbolic structure; transformation rules allow you to transform parts of that structure.