1

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)
a=1;
assign[a]

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

Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453
cxkoda
  • 305
  • 2
  • 10
  • 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. – Oleksandr R. Jan 13 '14 at 01:35
  • @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. – Oleksandr R. Jan 13 '14 at 03:33
  • @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. – Leonid Shifrin Jan 13 '14 at 04:11

1 Answers1

2

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

SetAttributes[assign, HoldFirst];

assign[z_] := z = 2

a = 1;
assign[a]
assign[b]

{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.

ciao
  • 25,774
  • 2
  • 58
  • 139