Re: Block v. Module
- To: mathgroup at smc.vnet.net
- Subject: [mg68199] Re: Block v. Module
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Sat, 29 Jul 2006 01:00:22 -0400 (EDT)
- Organization: The Open University, Milton Keynes, UK
- References: <eaa23s$nde$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Bruce Colletti wrote:
> Re Mathematica 5.2.0.0.
>
> The Module and Block below "should" return the same result, but they don't. The Module's result makes no sense, while the Block's result is what I want.
>
> What's Module doing? The way I read the Help Text, both should return the same result.
>
> Thankx.
>
> Bruce
>
> f[Y_String]:=Module[{x},x=StringReplace[Y,{x_->x}]];
> x={"yes","no"};
> f@"xyz"
>
> {yes,no}~~{yes,no}~~{yes,no}
>
Hi Bruce,
To solve the issue, use a delayed rule. If we look at the evaluation
process of
f[Y_String] := Module[{x}, x = StringReplace[Y, {x_ -> x}]];
x = {"yes", "no"};
Trace[f["xyz"]]
we can see that the rule x_ -> x is evaluated before Mathematica creates
the temporary variable. Therefore, the value taken by x is the global
value.
Using a delayed rule, everything works as expected:
f[Y_String] := Block[{x}, x = StringReplace[Y, {x_ :> x}]];
x = {"yes", "no"};
Trace[f["xyz"]]
returns "xyz"
HTH,
Jean-Marc