Blocks Compared with Modules
When you write a program in
Mathematica, you should always try to set it up so that its parts are as independent as possible. In this way, the program will be easier for you to understand, maintain, and add to.
One of the main ways to ensure that different parts of a program do not interfere is to give their variables only a certain "scope".
Mathematica provides two basic mechanisms for limiting the scope of variables: modules and blocks.
In writing actual programs, modules are far more common than blocks. When scoping is needed in interactive calculations, however, blocks are often convenient.
| Module[vars,body] | lexical scoping |
| Block[vars,body] | dynamic scoping |
Mathematica variable scoping mechanisms.
Most traditional computer languages use a so-called "lexical scoping" mechanism for variables, which is analogous to the module mechanism in
Mathematica. Some symbolic computer languages such as LISP also allow "dynamic scoping", analogous to
Mathematica blocks.
When lexical scoping is used, variables are treated as local to a particular section of the
code in a program. In dynamic scoping, the values of variables are local to a part of the
execution history of the program.
In compiled languages like C and Java, there is a very clear distinction between "code" and "execution history". The symbolic nature of
Mathematica makes this distinction slightly less clear, since "code" can in principle be built up dynamically during the execution of a program.
What
Module
does is to treat the form of the expression
body at the time when the module is executed as the "code" of a
Mathematica program. Then when any of the
vars explicitly appears in this "code", it is considered to be local.
Block
does not look at the
form of the expression
body. Instead, throughout the evaluation of
body, the block uses local values for the
vars.
This defines

in terms of

.
| Out[1]= |  |
The local value for

in the block is used throughout the evaluation of

.
| Out[2]= |  |
Here only the

that appears explicitly in

is treated as a local variable.
| Out[3]= |  |