5
$\begingroup$

Is it possible to extract n-th part of an expression as a string, without any evaluation?
For example,

In[1]   x=1;y=2;z=3;
In[2]   SomeCode[Plus[x,y,z], 2]
Out[2]  "y" (* y as a string! *)

I've tried

  In[2] Defer[Unevaluated[Plus[x,y,z]][[2]]]

but failed :

  Out[2] Unevaluated[Plus[x, y, z]][[2]] (* fail *)
$\endgroup$
1
  • $\begingroup$ As far as I can tell, y would not be a string if you pulled it from the example expression. Instead, you would need to somehow have it be changed to a string. $\endgroup$ Mar 21, 2021 at 13:58

1 Answer 1

6
$\begingroup$

One way of doing this is to use Extract with Hold and Unevaluated to make it into a string, like:

x = 1; y = 2; z = 3;
t = Extract[Hold[Plus[x, y, z]], {1, 2}, Hold ];
t /. Hold[y_] -> ToString[Unevaluated[y]]

(* y *)
$\endgroup$
1
  • 2
    $\begingroup$ +1. Similar: Construct[ToString, Extract[Hold[Plus[x, y, z]], {1, 2}, Unevaluated]]. Another variation close to the OP's initial attempt: Extract[Unevaluated[Plus[x, y, z]], 2, Defer]. $\endgroup$
    – WReach
    Mar 21, 2021 at 16:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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