WolframLang: Local Variable

By Xah Lee. Date: . Last updated: .
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 by var = val;
  • Return the value of body.

Module

๐Ÿ’ก TIP: This is similar to โ€œlexical scopedโ€ construct in most programing languages, or lisp's let

๐Ÿ›‘ WARNING: 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. Example: Module[{x = 2, y = x}, y] === x

Module[{x=2, y=x}, y] === x

๐Ÿ’ก TIP: 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. Example: With[{x = 2, y = x}, y] === x

With

With[{x = 3}, x+1] == 4

WolframLang: Variable