1
$\begingroup$

If I have a variable x := "a".
Is there a way I can use it to assign a value to a, by just referring to x?
If I try Evaluate[x]=4 I get error messages about Tag Times in x Null is protected.
I would like some way of having it execute a = 4.

$\endgroup$
  • 2
    $\begingroup$ x = "a"; Evaluate@Symbol[x] = 1; a $\endgroup$ – Dr. belisarius Mar 9 '15 at 16:11
  • 2
    $\begingroup$ This is kind of hard in Mathematica. One way to do this would be Hold[x]/.OwnValues[x]/.Hold[var_]:>(var = 4) assuming that a is a symbol. If a is a string name, then: ToExpression[x, StandardForm, Function[var, var=4, HoldFirst]]. $\endgroup$ – Leonid Shifrin Mar 9 '15 at 16:17
  • 1
    $\begingroup$ Maybe x /: Set[x, y_] := Set[a, y]? $\endgroup$ – Kuba Mar 9 '15 at 18:46
  • $\begingroup$ closely related: Table of references $\endgroup$ – Kuba Mar 9 '15 at 20:15
  • $\begingroup$ Okay I found something on the web that almost helps, but when I try an pass Hold a list rather than hard code things it barfs. If I swap the commented line for the hard coded Hold it does what I expect. cols is {ra,dec,z} Print[cols] l := Length[cols] Print[l] ClearAll[ra, assign] assign[symbols_, idx_, val_] := symbols[[{idx}]] /. _[x_] :> (x = val) symbols = Hold @@ cols; (*symbols=Hold[ra,dec,z]*) Print["Assign"] assign [symbols, 1, 4]; ra $\endgroup$ – Keith Sloan Mar 9 '15 at 20:54
1
$\begingroup$

adding one more and summarizing comments

     ToExpression[x <> "=" <> ToString[10]];

or

     ToExpression[StringJoin @@ ToString /@ {x, "=", 3.14}]

from: @LeonidShifrin

     ToExpression[x, StandardForm, Function[var, var = 42, HoldFirst]]

@belisarius approach only works once:

     Evaluate@Symbol[x] = 1

after "a" has a value, Symbol[x] returns the value so this breaks if you try to use it more than once.

@kuba proposes using TagSetDelayed x:

     x := "a" 
     x /: Set[x, y_] := Set[a, y]

which will let you simply do:

     x=3

with the result being assignment of "a" {x,a} -> {"a",3}

$\endgroup$
  • $\begingroup$ oh i see, i didn't understand.. $\endgroup$ – george2079 Mar 9 '15 at 20:59

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.