1

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.

Karsten7
  • 27,448
  • 5
  • 73
  • 134
  • 2
    x = "a"; Evaluate@Symbol[x] = 1; a – Dr. belisarius Mar 09 '15 at 16:11
  • 2
    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]]. – Leonid Shifrin Mar 09 '15 at 16:17
  • 1
    Maybe x /: Set[x, y_] := Set[a, y]? – Kuba Mar 09 '15 at 18:46
  • 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 – Keith Sloan Mar 09 '15 at 20:54

1 Answers1

1

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}

george2079
  • 38,913
  • 1
  • 43
  • 110