Use Function[] to make a temporary holding version of a function

Most built-in and user-defined functions let their arguments evaluate by default.  Suppose for a particular line of code, you need a version of Head that doesn't evaluate its arguments.  One way, of course, would be to temporarily give Head the HoldFirst attribute, but it's usually unsafe to change the definition of basic built-in functions.  Fortunately, the language enables you to give pure functions the same attributes you would give to symbols.  Here is the template for constructing a temporary holding version:


This is essentially the same as the more familiar, simpler pure function

  MyHead = Head[#]&

but it has to use the 3-argument form of Function with a named variable in order to give it the HoldFirst attribute.

Now you can use MyHead just like you would use Head.  If the argument comes in unevaluated, it will remain that way.  For instance:


There's no need to give the function a name; I just did that to make the example more concise.  Usually you use Function[] because you want to construct one-shot operators on the fly, to use in a single line of code.

Here's an example of a held list of elements:


We want to group consecutive elements if they have the same head, i.e.

  Head[#1] === Head[#2] &

But this ordinary form of pure function will evaluate #1 and #2, which will destroy the structure in things like Print[1] and 0 + 1, so we have to prevent that.  We do it by converting that function to the longer form:

  Function[{e1, e2}, Head[Unevaluated[e1]] === Head[Unevaluated[e2]], HoldAll]

Again, it's essentially the same as the more familiar form, but it gives this construct the HoldAll attribute.  Here is the result in action:


And here is an example where you want to test unevaluated products to see if they contain spurious zeros:


If you want to delete the zeros so that the products don't evaluate to zero, you can make a holding DeleteCases: