:=
)
SetDelayed
[expr, value] SetDelayed
is like Set
, except it has attribute HoldAll
, thus it does not evaluate the right-hand side immediately, but evaluates it when needed.
Attributes[SetDelayed]
a = 1
x := a
x
Changing the value of a affects x:
a = 2
x
Condition
(/;
) can be used with SetDelayed
to make an
assignment that only holds if a condition is satisfied:
f[x_] := p[x] /; x>0
f[3]
f[-3]
It also works if the condition is set in the LHS:
F[x_, y_] /; x < y /; x>0 := x / y;
F[x_, y_] := y / x;
F[2, 3]
F[3, 2]
F[-3, 2]
We can use conditional delayed assignments to define symbols with values conditioned to the context. For example,
ClearAll[a,b]; a/; b>0:= 3
Set a to have a value of $3$ if certain variable b is positive. So, if this variable is not set, a stays unevaluated:
a
If now we assign a positive value to b, then a is evaluated:
b=2; a