Local Constants
| With[{x=x0,y=y0,...},body] | define local constants x, y, ... |
Defining local constants.
Module allows you to set up local
variables, to which you can assign values and then change them. Often, however, all you really need are local
constants, to which you assign a value only once. The
Mathematica With construct allows you to set up such local constants.
This defines a global value for

.
| Out[1]= |  |
This defines a function using

as a local constant.
This uses the definition of

.
| Out[3]= |  |

still has its global value.
| Out[4]= |  |
Just as in
Module, the initial values you define in
With are evaluated before
With is executed.
The expression

which gives the value of the local constant

is evaluated using the global

.
| Out[5]= |  |
The way
With
works is to take
body, and replace every occurrence of
x, etc. in it by

, etc. You can think of
With as a generalization of the

operator, suitable for application to
Mathematica code instead of other expressions.
This replaces

with

.
| Out[6]= |  |
After the replacement, the body of
With is

, so

gets the global value

.
| Out[7]= |  |
This clears the value of

.
In some respects,
With is like a special case of
Module, in which each local variable is assigned a value exactly once.
One of the main reasons for using
With rather than
Module is that it typically makes the
Mathematica programs you write easier to understand. In a module, if you see a local variable
x at a particular point, you potentially have to trace through all of the code in the module to work out the value of
x at that point. In a
With construct, however, you can always find out the value of a local constant simply by looking at the initial list of values, without having to trace through specific code.
If you have several
With constructs, it is always the innermost one for a particular variable that is in effect. You can mix
Module and
With. The general rule is that the innermost one for a particular variable is the one that is in effect.
With nested
With constructs, the innermost one is always the one in effect.
| Out[9]= |  |
| Out[10]= |  |
Local variables in inner constructs do not mask ones outside unless the names conflict.
| Out[11]= |  |
Except for the question of when
x and
body are evaluated,
With
works essentially like

. However,
With behaves in a special way when the expression
body itself contains
With or
Module constructs. The main issue is to prevent the local constants in the various
With constructs from conflicting with each other, or with global objects. The details of how this is done are discussed in
"How Modules Work".
The

in the inner
With is renamed to prevent it from conflicting with the global

.
| Out[12]= |  |