SetDelayed
lhs := rhs
sets lhs
to stand for rhs
, with rhs
not being evaluated until it is referenced by lhs
.
Attributes[SetDelayed] := {HoldAll, Protected, SequenceHold}
Simple examples
SetDelayed
can be used to define functions:
In[1]:= testa[x_] := x*2 Out[1]= Null
In[2]:= testa[x_Integer] := x*3 Out[2]= Null
In[3]:= testa[x_Real] := x*4 Out[3]= Null
The more "specific" definitions match first:
In[4]:= testa[2.] Out[4]= 8.
In[5]:= testa[2] Out[5]= 6
There is no specific match for testa[k]
, so the general case matches:
In[6]:= testa[k] Out[6]= 2 * k
Further examples
Set
has the HoldFirst
attribute, meaning rhs
is evaluated before assignment:
In[1]:= Attributes[Set] Out[1]= {HoldFirst, Protected, SequenceHold}
SetDelayed
has the HoldAll
attribute, meaning rhs
is not evaluated during assignment:
In[2]:= Attributes[SetDelayed] Out[2]= {HoldAll, Protected, SequenceHold}