The replacement operator /.
allows you to apply transformation rules to a specific expression. Often, however, you want to have transformation rules automatically applied whenever possible.
You can do this by assigning explicit values to Mathematica
expressions and patterns. Each assignment specifies a transformation rule to be applied whenever an expression of the appropriate form occurs.
|expr/.lhs->rhs||apply a transformation rule to a specific expression|
|lhs=rhs||assign a value which defines a transformation rule to be used whenever possible|
Manual and automatic application of transformation rules.
This applies a transformation rule for x
to a specific expression.
By assigning a value to x
, you tell Mathematica
to apply a transformation rule for x
is transformed automatically.
You should realize that except inside constructs like Module
, all assignments you make in a Mathematica
session are permanent
. They continue to be used for the duration of the session, unless you explicitly clear or overwrite them.
The fact that assignments are permanent means that they must be made with care. 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.
There are several ways to avoid this kind of mistake. First, you should avoid using assignments whenever possible, and instead use more controlled constructs such as the /.
replacement operator. Second, you should explicitly use the deassignment operator =.
or the function Clear
to remove values you have assigned when you have finished with them.
Another important way to avoid mistakes is to think particularly carefully before assigning values to variables with common or simple names. You will often want to use a variable such as x
as a symbolic parameter. But if you make an assignment such as x=3
, then x
will be replaced by 3
whenever it occurs, and you can no longer use x
as a symbolic parameter.
In general, you should be sure not to assign permanent values to any variables that you might want to use for more than one purpose. If at one point in your session you wanted the variable c
to stand for the speed of light, you might assign it a value such as 3.*10^8
. But then you cannot use c
later in your session to stand, say, for an undetermined coefficient. One way to avoid this kind of problem is to make assignments only for variables with more explicit names, such as SpeedOfLight
|x=.||remove the value assigned to the object x|
|Clear[x,y,...]||clear all the values of x, y, ... |
This does not give what you might expect, because x
still has the value you assigned it above.
This removes any value assigned to x
Now this gives the result you expect.