Transformation Rules and Function Definitions

Index

This index gives a list of keywords that are associated with various cells in this Notebook. If you Command-Double-click one of the keywords below,  Mathematica  will find the cell associated with that keyword, select it, and display it in the center of  your window.

Assignments 
Clear   
Definition`function 
Definition`showing
Transformation`Rule 
Value`removing

Basic Transformation Rules and Function Definitions

Syntax (see pages 72, 113, 243 and 251)

Transformation Rule

expr  /. lhs  -> rhs   applies a transformation rule, trying rules once on each part of expr.

Assignments

x   = value   assigns a value for x   which will always be used.

Removing a Defined Value

x   = .  removes any value defined for x .

Function Definition

f [x _]: = expr   defines the function f.

Showing  Definition

?f    shows the definition of f.

Clear

Clear[f  ]  clears all definitions of f.

Basic Replacements

x + y /. x -> 3

x + y /. {x -> a, y -> b}

x + y /. {{x -> 1, y -> 2}, {x -> 4, y -> 2}}

Replacements Using Pattern Matching

1 + f[x] + f[y] /. x -> 3

1 + f[x] + f[y] /. f[x] -> p

1 + f[x] + f[y] /. f[t_] -> t^2

A Function Definition

f[x_] := x^2

f[a+1]

f[4]

f[3x + x^2]

A Note on Function Definitions

Probably the most powerful aspect of transformation  rules in Mathematica  is that they can involve not only literal expression, 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.

Function with Two Arguments

hump[x_, xmax_] := (x - xmax)^2 / xmax

2 + hump[x, 3.5]

Showing and Clearing a Function Definition

func[ x_ ] := Sin[x] x^2

?func

Clear[func]

?func

Replacing a Variable with a Number

1 + 2x /. x -> 3

Assigning a Numerical Value to a Variable

x = 3

1 + 2x

Removing an Assigned Value

x = 3 - a

(1 + x)^7

x = .

(1 + x )^7

A Note on Assignments and Replacement Rules

The replacement operator /. allows you to apply transformation rules to a particular expression.  Sometimes, however, you will want to define transformation rules that should always be applied. In this case you would use an assigment such as x  = 3. You should understand that explicit definitions such as x  = 3 have a global effect. On the other hand, a replacement such as expr  /. x -> 3  affects only the specific expression expr . It is usually much easier to keep things straight if you avoid using explicit definitions except when necessary. Once you explicitly give a definition, such as x  = 3,  then x  will always be replaced by 3, and can no longer serve as a formal variable.

Probably the single most common mistake in using Mathematica  is to make an assignment for a variable like x  at one point in your session, and then later to use x  having forgotten about the assignment you made. For this reason, it is good to be particularly careful about assigning values to variables with simple or common names such as x , f , etc. One way to avoid this problem is to make assignments only for variables with more explicit names, such as SpeedOfLight .

Transformation Rules

Syntax (see pages 72 and 243)

expr /. lhs  -> rhs   applies a transformation rule, trying rules once on each part of expr.

expr /.{lhs1  -> rhs , lhs2  -> rhs2 , ...}  tries a sequence of rules on each part of expr.

expr /.{rules1, rules2, ...} gives a list of the results from applying each of the rulesi  to expr.

expr //. rules   tries rules  repeatedly until the result no longer changes.

Basic Replacements

x + y /. x -> 3

x + y /. {x -> a, y -> b}

x + y /. {{x -> 1, y -> 2}, {x -> 4, y -> 2}}

Replacements Using Pattern Matching

1 + f[x] + f[y] /. x -> 3

1 + f[x] + f[y] /. f[x] -> p

1 + f[x] + f[y] /. f[t_] -> t^2

Naming the Replacement Rules

sinexp = Sin[2 x_] -> 2 Sin[x] Cos[x]

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

Single and Repeated Replacement

Note that when you use the single replacement operator /.  a result is returned as soon as a rule has been applied. Thus, the inner instance of h  is  not replaced.

h[ x + h[y]] /. h[u_] -> u^2

h[ x + h[y]] //. h[u_] -> u^2

A Repeated Replacement

Note that when you use the repeated replacement operator //. the  rules are tried repeatedly until the expression no longer changes.

x^2 + y^6 /. {x -> 2 + a, a -> 3}

x^2 + y^6 //. {x -> 2 + a, a -> 3}

A Note on Applying Transformation Rules

When you use expr /. rules , 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 returned. 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 expr //. rules . If you give a set of rules that is circular, then //. can keep 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. For more information, see page 244.

Function Definitions

Syntax (see pages 113 and 251)

f  [x_ ]:= expr    defines a function that is evaluated each time it is called.

f [x_ ]= expr    defines a function which gives the value expr  for any particular value of x .  expr  is `evaluated when the assignment is made.

f [x_,k_:kdef ]:= value   gives a definition for a function whose second option is optional. When it is absent it is given the default value of kdef.

?f    shows the definition of f.

Clear[f  ]  clears all definitions of f.

f [x_ ]:= f  [x_ ]= rhs    defines a function which remembers values that it finds.

Function Definition

f[x_] := x^2

f[a+1]

f[4]

f[3x + x^2]

Function with Two Arguments

hump[x_, xmax_] := (x - xmax)^2 / xmax

2 + hump[x, 3.5]

List as an Argument

This gives two ways of defining the same function.

g[list_] := Part[list, 1] ^ Part[list, 2]

h[{x_, y_}] := x^y

g[{3, a}]

h[{3, a}]

Function as a Procedure

exprod[n_] := Expand[ Product[ x + i, {i, 1, n}]]

exprod[2]

exprod[3]

A Note on Functions as Procedures

In many kinds of calculations, you may find yourself typing the same input to Mathematica  over and over again. You can often save yourself a lot of typing by defining a function that contains your input commands.

Recursive Definition

fac[n_] := n fac[n - 1]

fac[1] := 1

fac[10]

Definition with Conditions

This gives two ways of defining the same step function.

step[x_] := 1 /; x >= 0

step[x_] := -1 /; x < 0

sstep[x_ /; x >= 0] := 1

sstep[x_ /; x < 0] := -1

Showing and Clearing a Function Definition

Clear[func]

func[ x_ ] := Sin[x] / x /; x != 0

func[0] = 1

?func

Clear[func]

?func

Parameter Checking

The pattern n_Integer matches only integers.

hilbert[n_Integer] := 
            Table[1/(i + j - 1), {i, n}, {j, n}]

hilbert[3]

hilbert[3.5]

Function with an Optional Argument

When only one argument is given this gives the usual sine function.

sinpow[x_, n_:1] := Sin[x]^n

sinpow[Pi/3, 2]

sinpow[Pi/3]

Immediate and Delayed Definitions

When you execute ex, the Expand is performed, while iex simply substitutes its argument into the already expanded form, giving a different answer.

ex[x_] := Expand[(1 + x)^2]

iex[x_] = Expand[(1 + x)^2]

ex[y + 2]

iex[y + 2]

A Note on Immediate and Delayed Definitions

As you can see from the previous example, both =  and :=  can be useful in defining functions, but they have different meanings, and you must be careful about which one to use in a particular case. One rule of thumb is the following. If you think of an assignment as giving the final "value" of an expression, use the  =  operator. If instead you think of the assignment as specifying a "command" for finding the value, use the  := operator. When in doubt, it is usually better to use :=  than  = .  One  exception is when you do a calculation, and get an answer in terms of a symbolic parameter. You often want to go on and find results for various specific values of x . In this case it is convenient to use   =  to define a function whose argument is x .  This is illustrated in the next example

Using a Previous Calculation as a Function Definition

D[Log[Sin[x]]^2, x]

dlog[x_] = %

dlog[2]

dlog[1 + a]

Function That Remembers ValuesThat It Finds

f[x_] :=  f[x] = f[x - 1] + f[x - 2]

f[0] = f[1] = 1

?f

f[5]

?f

An Example: Defining Your Own Integration Function

From a mathematical point of view, the integration function is defined by a sequence of mathematical relations. By setting up transformation rules for patterns, you can implement these mathematical relations directly in Mathematica .  In the example below, a function called integrate is defined by a sequence of transformation rules. The effect of each new rule is illustrated by evaluating an example.

Implementing the Linearity

integrate[y_ + z_, x_] :=
                  integrate[y, x] + integrate[z, x]

integrate[a x + b x^2 + 3, x]

Pulling Out Independent Factors

The function FreeQ[c, x ] returns true if c  is independent of x .

integrate[c_ y_, x_] := 
              c integrate[y, x] /; FreeQ[c, x]

integrate[a x + b x^2 + 3, x]

Integral of a Constant

integrate[c_, x_] := c x /; FreeQ[c, x]

integrate[a x + b x^2 + 3, x]

Integral of a Power

By using the pattern x_ ^n_. rather than x_ ^n_ , we include the case of    x  = x ^1. The expression n  != -1 means n  doesn't equal -1.

integrate[x_^n_., x_] :=
        x^(n+1)/(n+1) /; FreeQ[n, x] && n != -1

integrate[a x + b x^2 + 3, x]

Integral of the Reciprocal of a Linear Function

integrate[1/ (a_. x_ + b_.), x_] :=
            Log[a x + b]/a  /; FreeQ[{a, b}, x]

integrate[1/x, x]

integrate[ 1/ (2 p x - 1), x]