By default, all symbols are “global” in Mathics3, i.e. they can be read and written in any part of your program.
However, sometimes “local” variables are needed in order not to disturb the global namespace. Mathics3 provides two ways to support this:
Module
, andBlock
.Module
[{vars}, expr]name$number
, where number is the current value of $ModuleNumber
. Each time a module$ModuleNumber
is incremented.Block
[{vars}, expr]Both scoping constructs shield inner variables from affecting outer ones:
t = 3;
Module[{t}, t = 2]
Block[{t}, t = 2]
t
Module
creates new variables:
y = x ^ 3;
Module[{x = 2}, x * y]
Block
does not:
Block[{x = 2}, x * y]
Thus, Block
can be used to temporarily assign a value to a variable:
expr = x ^ 2 + x;
Block[{x = 3}, expr]
x
Block
can also be used to temporarily change the value of system parameters:
Block[{$RecursionLimit = 30}, x = 2 x]
f[x_] := f[x + 1]; Block[{$IterationLimit = 30}, f[1]]
It is common to use scoping constructs for function definitions with local variables:
fac[n_] := Module[{k, p}, p = 1; For[k = 1, k <= n, ++k, p *= k]; p]
fac[10]
10!