I have seen a number of examples on this site (such as in syntax highlighting and checking evaluation status) in which functions definitions are preceded with
without comment, and even though it seems unnecessary for the specific task at hand. This leads me to believe that at least in some cases it is simply good practice to do so. Is that the case? If so, why? Are there instances in which it would not be the best practice?
My understanding of the situation is that if, for example, I have
x=5 and then pass
1+x to my function
f, the argument as seen internally by
f will still be represented as
1+x instead of
6. But it seems to me that in most cases if this were true I'd simply want to
Evaluate[1+x] before proceeding. This would lead me to conclude that setting
HoldAll would be the exception, not the rule.
My question is not whether the two examples I provided actually require
HoldAll to work, but rather
How do I determine, when writing a new function, whether or not to set
What I am concerned about is the possibility of creating a function which behaves as desired without the
HoldAll setting (or with it, for that matter) for the test cases I throw at it, but which misbehaves later if something else gets passed to it. What possibilities and issues must I consider to ensure I make the correct choice? What are explicit use cases for each of the two options?
HoldAllis unnecessary? Then we can think about why it was a good idea to use it there, maybe even find out that it is in fact necessary to handle all cases. $\endgroup$
HoldAllis unnecessary. In fact it is necessary in both cases you mentioned and the code shown would not work without it. In general I would aggree that setting
HoldAllwould be the exception, but probably among the answers on this site here there are an unusual fraction of exceptional examples :-). $\endgroup$
HoldAllis unnecessary... @Albert, it does make sense that many examples here are exceptional! Perhaps an explanation of why
HoldAllis needed would help to enlighten me. I took the first example I mentioned, syntax highlighting, and entered the code from the accepted answer except for the
SetAttributesline. The result was exactly what was specified it would be in the answer; I see no different behaviour in the syntax highlighting. I'm not sure why I can't then conclude that the line of code I omitted is unnecessary. $\endgroup$
HoldAllis needed for the two examples, is that answering your question? And yes, of course it's good to have exceptional examples here, it just probably makes you think
HoldAllis necessary more often than it actually is. Usually you will know when to use it, since when needed things will just not work without it. $\endgroup$