I'm currently trying very hard to assign a variable inside a function.
Therefore I'm using a function like this, which should reassign a predefined variable.

assign[a_] := (HoldForm@a = 2)

The problem is that Mathematica uses the value of "a" instead of its name.
Any suggestions?

  • $\begingroup$ You should investigate attributes. Specifically, the ones whose names start with Hold. Alternatively you could perhaps use Unevaluated. But, trying to do the assignment as HoldForm[a] = whatever is not valid since HoldForm is Protected. $\endgroup$ – Oleksandr R. Jan 13 '14 at 1:35
  • $\begingroup$ @LeonidShifrin thanks--I had been looking for a duplicate but didn't succeed in finding it. Actually, I was looking for a different one, but your suggestion is a good match. $\endgroup$ – Oleksandr R. Jan 13 '14 at 3:33
  • $\begingroup$ @OleksandrR. No problem. This seems to be a common question, you are right - there were at least several related discussions here and on SO - and on MathGroup before that. $\endgroup$ – Leonid Shifrin Jan 13 '14 at 4:11

As Oleksandr R. commented, you can do this by setting the appropriate attributes, e.g.

SetAttributes[assign, HoldFirst];

assign[z_] := z = 2

a = 1;

{a, b}

(* {2,2} *)

However, there's a reason for scoping rules and constructs, I'd think long and hard before 'circumventing' them, whatever that may mean in your case.


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