I had a problem on a program of mine that I could avoid by developing the code through other ways. On the other hand, I still do not know how to solve the simple problem below:

Consider these two definitions:

f = p; p = 2;

One can use Clear[p] to clear the value of p, which will lead the output of f to be p, instead of 2.

Is there a way to clear the value of p through the definition of the variable f? That is, without explicit writing the variable p.

By using Definition[f], the output is "f=p", but if I try to pick the variable "p" from the definition, trough Definition[f][[1]], I cannot apply Clear on it, since p is automatically evaluated to 2, thus the application of Clear in the last case leads to "Clear[2]", instead of "Clear[p]".

Context on where this problem may appear: Consider a larger program in which the variable name p was automatically built and depends on the input of the user (in this case the name of the variable will typically be larger, but let us stick with the name p). If the name of the variable was generated automatically, and depends on the user input, I cannot explicitly type in the code "Clear[p]". One can use Clear[f], but this will not clear the value of p. To sove the issue, I simply avoided using variables whose names depend on the user input, nonetheless, I would like to know a solution for the problem above.



2 Answers 2

f = p; p = 2;
Last[MapAt[Clear, First[OwnValues[f]], 2]]


Maybe instead of f = p you should use f = Hold[p] or f = Hold[#]&[p] so the above becomes

ReleaseHold[MapAt[Clear, f, 1]]

which maybe looks a bit better

  • $\begingroup$ Great! Actually the first answer is the one I was looking for. Thanks @Coolwater. $\endgroup$
    – Davi
    May 5, 2017 at 17:21
  • 1
    $\begingroup$ Alternatively: ClearAll @@ (Hold[f] /. OwnValues[f]) $\endgroup$
    – Kuba
    May 30, 2017 at 20:27

Try this

p = 2;
With[{a = p}, f = a]

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.