Wolfram: Set, SetDelayed
Set[x, y]
-
🔸 SHORT SYNTAX:
x=y
Create a transformation rule so that left-hand-side becomes the right-hand-side. The right-hand-side is evaluated before the rule is defined.
The rule is associated to the left most symbol of left-hand-side expression.
(* global variable, of current session *) x = 5
In most programing languages, this is setting a value to a variable. In WolframLang, it's actually defining a transformation rule. The effect is the same .
The left-hand-side can be any expression.
(* make f[3] to always become 5. Effectively defining a function's value at 3. *) f[3] = 5 f[3] (* 5 *) f[4] (* f[4] *) (* no change *) (* clear the rule associated with f *) Clear[f]
The left-hand-side can be a Pattern.
(* make the pattern g[x_] to always become 5. Effectively defining a constant function. *) g[x_] = 5 (* all of the following evalutes to 5 *) g[3] g[4] g[{1,2}] g[y] (* clear the rule associated with g *) Clear[g]
SetDelayed[x, y]
-
🔸 SHORT SYNTAX:
x:=y
Like
Set
, but right-hand-side is evaluated at the time the replacement happens.
This is usually used to define a function by way of pattern matching. 〔see Define Function by Pattern〕
Set vs SetDelayed
To create a transformation rule, use
Set
or
SetDelayed
The difference is:
Set
eval the right-hand-side when the rule is defined.SetDelayed
eval the right-hand-side at the time the replacement happens.
Set
is often used to set a variable.
(e.g. x = 3
)
, or set a function that remember its value.