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.
(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]
x = 5; Module[{x}, x = 3; x+1] == 4 x == 5 (* x is still 5 *)
Module[{x = 3}, x+1] == 4
Later values in variable is not available:
Module[{x=2, y=x}, y] =!= 2
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.
The latter constant does not know the previous constant. E.g.
With[{x = 2, y = x}, y] === x
With[{x = 3}, x+1] == 4