Module¶
Module creates a local scope for variables, ensuring they don't interfere
with variables in the surrounding context.
Basic Local Variable¶
Multiple Local Variables¶
Local Variables Don't Leak to Outer Scope¶
Local Variables Shadow Outer Variables¶
Using Outer Variables in Local Initialization¶
Uninitialized Local Variables¶
Local variables without initialization are treated as unique symbols.
Nested Module¶
Module in Function Definition¶
Module with Computations in Body¶
Module Returning Complex Expressions¶
Module with Symbolic Computation¶
Module with Condition in Body¶
Conditions (/;) inside Module bodies are evaluated while local variables
are still in scope.
Malformed Local Variable Specifications¶
Every local must be a symbol or an assignment to a symbol. A pattern variable is substituted into the local list as well, so a parameter cannot be re-declared as a local.
$ wo 'f[x_] := Module[{x}, x]; f[5]'
Module::lvsym: Local variable specification {5} contains 5, which is not a symbol or an assignment to a symbol.
Module[{5}, 5]
$ wo 'Module[{x[1] = 3}, 4]'
Module::lvset: Local variable specification {x[1] = 3} contains x[1] = 3, which is an assignment to x[1]; only assignments to symbols are allowed.
Module[{x[1] = 3}, 4]
$ wo 'Module[{x, x}, 3]'
Module::dup: Duplicate local variable x found in local variable specification {x, x}.
Module[{x, x}, 3]
With differs in that it needs a value for every local:
$ wo 'With[{x}, x]'
With::lvws: Variable x in local variable specification {x} requires a value.
With[{x}, x]
Delayed Local Assignment¶
x := v keeps the right-hand side unevaluated until the body reads x.