3
$\begingroup$

The expression Head[Plot[x, {x, 0, 1}]] returns Graphics. Might it be possible to extract the original head of an expression without evaluation transforming it into something else?

My ultimate objective is to be able to pass any expression say, f[x] as an argument arg to another function g[arg] and then within g do something like this:

IN:: f[x]:= x; g[arg] := Module[{head}, **Some other stuff**; head = Head@arg; head]; g[f@x]

OUT:: f

However, doing:

IN:: g[arg] := Module[{head}, **Some other stuff**; head = Head@arg; head]; g[Plot[x, {x, 0, 1}]]]

I get:

OUT:: Graphics

This also happens when setting the Attributes of g to HoldFirst etc.

$\endgroup$
  • $\begingroup$ That's because arg gets evaluated before being passed to Head. Try using Unevaluated: Head@Unevaluated@arg $\endgroup$ – Lukas Lang Oct 12 '17 at 9:51
  • $\begingroup$ It works! So simple too, thanks a lot. $\endgroup$ – Jiren Oct 12 '17 at 9:56
  • 1
    $\begingroup$ Recommended reading: Working with unevaluated expressions. $\endgroup$ – Szabolcs Oct 12 '17 at 10:06
4
$\begingroup$

In a practical scenario, you may be storing your expression in a variable. To be able to do so, it must be held unevaluated.

expr = Hold[Plot[x, {x, 0, 1}]]
(* Hold[Plot[x, {x, 0, 1}]] *)

Then you can simply use Part.

expr[[1, 0]]
(* Plot *)

Unevaluated will be useful (only) when the expression is inserted literally into Unevaluated.

Head@Unevaluated@Plot[x, {x, 0, 1}]
(* Plot *)

SetAttributes[fun, HoldAll]
fun[expr_] := Head@Unevaluated[expr]

fun[Plot[x, {x, 0, 1}]]
(* Plot *)

This does not work:

expr := Plot[x, {x, 0, 1}]

Head@Unevaluated[expr]
(* Symbol *)

Recommended reading:

$\endgroup$
  • $\begingroup$ This is very useful! I have been going with Unevaluated for explicitly passing expressions to functions with Hold attributes, and then Part for modifying those expressions within functions. The reference is also very good. Thanks. $\endgroup$ – Jiren Oct 12 '17 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.