Skip to main content

evaluation - Generate assignment code to symbols from string


I want the function to take in string, then assign a value to its corresponding symbol. An implementation using ToExpression is


mySet[str_String, val_] := 
ToExpression["Set[" <> str <> "," <> ToString[val] <> "]"]

How can I do it without ToExpression? I wonder how this can be done with purely evaluation control.


I have read the following posts: Generating assignments and transforming code inside held forms when generating code


How do I evaluate only one step of an expression?


I think the main problem is to evaluate Symbol["x"] partially to x(it can have OwnValues), which can't be achieved with first post's code; and second post's code is indeed returning a HoldForm expression, leaving me generally the same problem.



Answer




Since you referenced How do I evaluate only one step of an expression? I might use:


(* step loaded from referenced Q&A *)

mySet[str_String, val_] := step @ Symbol[str] /. _[s_Symbol] :> (s = val)

Now:


x = 5;

mySet["x", 7];


x


7

(This also makes use of Injecting a sequence of expressions into a held expression.)


For clarity the above is trying to answer in what I think is the spirit of your question.
Pragmatically I usually(1)(2)(3) use MakeExpression, see e.g. my answer to the closely related:



Comments