WolframLang: Local Variable
- To create local variables, use
Module
. - To create local constants, use
With
.
Module[{var1, var2 etc}, body]
-
- Eval body with temp local variables.
- Each of the variable var can be the form
var = val
or you can set the value in the body byvar = val;
- Return the value of body.
Tip: This is similar to “lexical scoped” construct in most programing languages, or lisp's
let
When the body is more than one expression, add semicolon between them. [see CompoundExpression and Semicolon]
Module[{x = 3}, x+1] == 4
x = 5; Module[{x}, x = 3; x+1] == 4 x == 5 (* x is still 5 *)
Warning: The latter variable's value expression do not know the previous variable's value. E.g.
Module[{x = 2, y = x}, y] === x
Module[{x=2, y=x}, y] === x
To assign variable that depends on previous variable value, put the assignment in body:
Module[{x=2, y}, y=x; y] == 2
Local constants
With
, is similar to Module
, except the variables must have a value and cannot be changed.
With[{c1 = v1, c2 = v2 etc}, body]
-
- Eval body with temp local constants.
- Return the value of body.
Warning: The latter constant's value expression do not know the previous constant's value. E.g.
With[{x = 2, y = x}, y] === x
With[{x = 3}, x+1] == 4