Converting text to useful expressions is a nice feature. In the exemple (first part) one can see that the symbols created in the “ToExpression” function are global. But I want these created symbols localized in a defined function. Logical solution is using a Module. But this went wrong, see exemple (second part). I tried a lot of other solutions in vain. So I’am missing something and asking for some help.
I think that Module creates the local variables before the body of the module is evaluated. If it meets ToExpression["a"], no local variables are replaced; only after evaluation a new variable a will appear, too late for localization. For example:
Clear[a];
Module[{a}, Print[a]; ToExpression["a"]]
This may be a workaround:
Clear[a, b];
Module[{a, b}, ToExpression["a+b"] /. ToExpression["a"] -> a]
Not sure what you’re after, but here’s a way to get the desired behavior:
test[x0_] :=
Thread[ToExpression[#, StandardForm, Hold] & /@ x0, Hold] /.
Hold[exprs_] :>
Module @@ Hold[{a = 111, b = 222, x = x0}, exprs; Print[a, " ", b, " ", x]]
test[xxx]
(* 3 4 {a=3,b=a+1} *)
From the documentation for Module[{x, y, ...}, expr]:
Before evaluating
expr,Modulesubstitutes new symbols for each of the local variables that appear anywhere inexpr except as local variables in scoping constructs.
I would stress that the substitution is lexical; that is, the variables must literally appear in the unevaluated expr, which does not happen in the original code.
Nice exemple for studying evaluation process, thanks
Try using Block[ ] instead of Module[ ].