HoldAll, HoldFirst, HoldRest

If a function (f) has the HoldAll attribute (f) does it's work before it's arguments evaluate.
It's easy to see why Clear must have the HoldAll attribute.  Consider the cell where values are assigned to (x,y,z).

x = 2 ; y = 3 ; z = 6 ;

If Clear didn't have the HoldAll attribute the following would evaluate to Clear[2,3,6] which is nonsense.

Clear[x, y, z]

The example in the next cell is from Power Programming With Mathematica by David Wagner.

ClearAll[f, g] SetAttributes[f, HoldAll] ; f[x_] := g[x] Trace[f[2 + 2]]

{f[2 + 2], g[2 + 2], {2 + 2, 4}, g[4]}

In the example above the unevaluated sum (2+2) is substituted for (x) on the right side of the definition  f[x_]:=g[x].  The sum is only evaluated when it's time for (g) to evaluate it's arguments.  If (g) also held it's arguments the sum wouldn't evaluate at all.

The FullForm of (x=2) is Set[x,2].  Set has the HoldFirst attribute and it's important that is does.  If Set didn't hold it's first argument the second assignment in the next cell would evaluate to (2=5) which is nonsense.

x = 2 ; x = 5

5

Also it's easy to see why the symbol If has the attribute HoldRest.  Whe given an expression such as  
If[ Test, T, F]  we want to only evaluate 'T' when the Test is True, and we only want to evaluate 'F' when the Test is False.  If the Test is neither True or False we want neither 'T' or 'F' to evaluate.

Built-in Symbols with attributes HoldAll, HoldFirst, HoldRest

The next cell makes a list of all built-in symbols.

symbs = Cases[ToExpression/@Names["System`*"], _Symbol] ;

The next cell gives a list of all built-in symbols with the HoldAll attribute.

Select[symbs, MemberQ[Attributes[#], HoldAll] &]

{AbortProtect, Alias, And, Attributes, Block, Check, CheckAbort, CheckAll, Clear, ClearAll, Co ... , UnAlias, Unprotect, UpSetDelayed, UpValues, ValueQ, Which, While, With, $ConditionHold, $Failed}

The next cell gives a list of all built-in symbols with the HoldFirst attribute.

Select[symbs, MemberQ[Attributes[#], HoldFirst] &]

{AddTo, AppendTo, Catch, ClearAttributes, Context, Debug, Decrement, DivideBy, Increment, Mess ... crement, PrependTo, RuleCondition, Set, SetAttributes, Stack, SubtractFrom, TimesBy, Unset, UpSet}

The next cell gives a list of all built-in symbols with the HoldRest attribute.

Select[symbs, MemberQ[Attributes[#], HoldRest] &]

{DumpSave, If, PatternTest, RuleDelayed, Save, Switch}


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page