Re: A ToExpression question

*To*: mathgroup at smc.vnet.net*Subject*: [mg58351] Re: [mg58316] A ToExpression question*From*: Andrzej Kozlowski <andrzej at akikoz.net>*Date*: Tue, 28 Jun 2005 21:56:48 -0400 (EDT)*References*: <200506280913.FAA05098@smc.vnet.net>*Sender*: owner-wri-mathgroup at wolfram.com

On 28 Jun 2005, at 18:13, Ray Koopman wrote: > f1[x_] := Print[x]; > f2[x_] := ToExpression["Print[x]"]; > f3[x_] := Module[{y = x}, ToExpression["Print[y]"]]; > f4[x_] := Block[{y = x}, ToExpression["Print[y]"]]; > > Scan[#[0]&,{f1,f2,f3,f4}] > > 0 > x > y > 0 > > Why don't f2 and f3 print 0 ? > > To analyze this we need a more explicit model for the commonly used construction f[x_]:=Body I believe that, with the above definition, when you evaluate f[u] you get Unevaluated[Body]/.HoldPattern[x]->u So using this model let's first consider f2[0]. This is Unevaluated[ToExpression["Print[x]"]]/.HoldPattern[x]->0 However, there is nothing to match x in the unevaluated ToExpression ["Print[x]"] , ("Print[x]" is a string so the x is not matched) hence the replacement has no effect and x is printed. Now consider f4[0]. This is: Unevaluated[Block[{y = x}, ToExpression["Print[y]"]]]/.HoldPattern[x]->0 This time we get Block[{y = 0}, ToExpression["Print[y]"]]] Now the evaluation of ToExpression["Print[y]"]] proceeds with the value of y set to 0, so first ToExpression["Print[y]"]] is evaluated to Print[y] and then 0 is printed. Finally, consider f3[0]. This gives Unevluated[Module[{y = x}, ToExpression["Print[y]"]]]]/.HoldPattern [x]->0 This is turned into Module[{y=0},ToExpression["Print[y]"]]] but unlike in the case of Block, before evaluation y is renamed as y $somenumber but of course the y in "Print[y]" is not renamed since it is still a part of a string. So in effect we get Block[{y$somenumber=0},ToExpression["Print[y]"]]] and of course this will print y and not 0. Andrzej Kozlowski Chiba, Japan

**References**:**A ToExpression question***From:*"Ray Koopman" <koopman@sfu.ca>