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
.
1 Answer
$\begingroup$
$\endgroup$
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}
-
$\begingroup$ oh i see, i didn't understand.. $\endgroup$ Commented Mar 9, 2015 at 20:59
x = "a"; Evaluate@Symbol[x] = 1; a
$\endgroup$Hold[x]/.OwnValues[x]/.Hold[var_]:>(var = 4)
assuming thata
is a symbol. If a is a string name, then:ToExpression[x, StandardForm, Function[var, var=4, HoldFirst]]
. $\endgroup$x /: Set[x, y_] := Set[a, y]
? $\endgroup$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$