4
$\begingroup$

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.

Thanks.

$\endgroup$
2
$\begingroup$
f = p; p = 2;
Last[MapAt[Clear, First[OwnValues[f]], 2]]
p

p

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

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

Try this

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

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.