Message Boards Message Boards

0
|
451 Views
|
4 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Using "ToExpression" inside a Module creates Global symbols. How to force localized ones?

Posted 1 month ago

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.

POSTED BY: Chris Van Damme
4 Replies

Try using Block[ ] instead of Module[ ].

POSTED BY: Gustavo Delfino

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, Module substitutes new symbols for each of the local variables that appear anywhere in expr 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.

POSTED BY: Michael Rogers

Nice exemple for studying evaluation process, thanks

POSTED BY: Chris Van Damme

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]
POSTED BY: Gianluca Gorni
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract