4
$\begingroup$

This is probably a really simple one, but I'm stumped. I want Symbol["x"]=3 to work just like x=3. However I can't figure out how to get Mathematica to evaluate the Symbol, converting the string to the symbol x, but then not evaluate x.

x = 2

2

Symbol["x"] = 3

Set::write: Tag Symbol in Symbol[x] is Protected. >>

3

Evaluate[Symbol["x"]] = 2

Set::setraw: Cannot assign to raw object 3. >>

2

I know that I can remove the definition, but I have a ton of these and would like to be able to replace their values that have been already set. x=3 doesn't require that I remove the definition of x to set it.

In case it matters, I'm using 10.0.0.

$\endgroup$
16
  • $\begingroup$ This fundamental question has been asked and answered repeatedly: (197) (783) (2651) (2926) (37755). Please review those and pick the one that you feel is closest, and I will close this accordingly. Examples of solutions: Set @@ Append[ToHeldExpression["x"], 3] or MakeExpression@"x" /. _[s_] :> (s = 4) $\endgroup$
    – Mr.Wizard
    Commented Aug 28, 2014 at 16:53
  • $\begingroup$ And: ToExpression["x", StandardForm, Function[s, s = 5, HoldFirst]] $\endgroup$
    – Mr.Wizard
    Commented Aug 28, 2014 at 17:02
  • $\begingroup$ @Mr.Wizard I think I found a possible new solution: Clear[x]; Activate[Inactive[Set][Symbol["x"],3]] I agree we can close this question, as a duplicate of How do you programatically load data into symbols?. Then I'll post my answer there. $\endgroup$
    – Jens
    Commented Aug 28, 2014 at 17:48
  • 2
    $\begingroup$ While ToExpression works, I was hoping for something that gave finer control over evaluation, e.g. allowing only one step of the evaluation to take place. Control of evaluation has always been a bugaboo for me in using Mathematica. $\endgroup$
    – Mark Adler
    Commented Aug 28, 2014 at 18:04
  • 1
    $\begingroup$ @Mark Rather than modifying Set I recommend that you use an UpSet on a special head as WReach did here and I did here. Proposal: Set[svar[s_?StringQ], R_] ^:= MakeExpression@s /. _[L_] :> (L = R) now svar["x"] = 5 works. You should probably then Protect[svar] to prevent unwanted assignments. $\endgroup$
    – Mr.Wizard
    Commented Aug 28, 2014 at 18:27

0

Browse other questions tagged or ask your own question.