Rougly my question is about constructing a function that maps Hold[var] to "var"
even when var has an assigned value. In details :

In[1] var=22; A=Hold[var];

Can we construct a function F such that F[A] becomes the string, "var" ?

In fact, I can do it like :

In[2] F[x_]:=StringDrop[StringDrop[ToString[x],5],-1];
In[3] F[A]//InputForm
Out[3] "var"

But above method seems somewhat unnatural.

One natural,ideal way I think possible is :

  1. uncover Hold in Hold[var], with its content(=var) untouched, and apply ToString to the content.

Another natural,ideal way I think possible is :

  1. Change Hold in Hold[var] to ToString, with its content(=var) untouched.

Can you suggest natural ways to do it?

  • 4
    $\begingroup$ How about: F[Hold[x_]] := ToString@Unevaluated@x? $\endgroup$
    – Carl Woll
    Jun 11, 2021 at 21:40
  • 3
    $\begingroup$ (Also, not sure if you're using this in a larger context, but SetAttributes[F, HoldFirst], F[x_] := ToString@Unevaluated@x lets you dispense with the Hold and use F[var] directly, in case that's useful to you!) $\endgroup$
    – thorimur
    Jun 11, 2021 at 21:42
  • $\begingroup$ Thank you answeres! Solved my problem. $\endgroup$
    – imida k
    Jun 11, 2021 at 21:59
  • 1
    $\begingroup$ An option using SymbolName and pure function syntax Function[Null, SymbolName[Unevaluated[#]], HoldFirst] $\endgroup$
    – b3m2a1
    Jun 11, 2021 at 22:03
  • 1
    $\begingroup$ & is short for Function, so it's redundant here (even though the syntax highlighter doesn't get that # is bound). try simply Function[Null, SymbolName[Unevaluated[#]], HoldFirst][A]. Equivalently, Function[v, SymbolName[Unevaluated[v]], HoldFirst][A] $\endgroup$
    – thorimur
    Jun 12, 2021 at 2:47


Your Answer

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

Browse other questions tagged or ask your own question.