       Re: a dangerous feature of Module[]?

• To: mathgroup at smc.vnet.net
• Subject: [mg57515] Re: a dangerous feature of Module[]?
• From: dh <dh at metrohm.ch>
• Date: Tue, 31 May 2005 04:59:06 -0400 (EDT)
• References: <d76ol2\$7si\$1@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```Hello Gennady,
Concerning localization of pattern variables, it seems to me that
"Module" has been improperly implemented. It would be nice if Daniel
Lichtblau or one of his colleagues could make a "comment from the
creators" on this.
Not only function definitions show this dangerous behaviour, but also
ReplacementRules:

Functions:
x=2;Module[{x=3},f[x_]=x;f]  gives 2
x=.;Module[{x=3},f[x_]=x;f]  gives 4
x=2;Module[{x=3,y=1},f[x_]=x y;f] gives 4
x=.;Module[{x=3,y=1},f[x_]=x y;f] gives 4

Rules:
x = 2;Module[{x=3},4/.x_->x] gives 2
x = .;Module[{x=3},4/.x_->x] gives 4
x = 2;Module[{x=3,y=1},4/.x_->x y] gives 4
x = .;Module[{x=3,y=1},4/.x_->x y] gives 4

> I've spent considerate time recently debugging my Mathematica code until I figured
> out that the problem is in a strange behaviour of the Module[] function.
> Here is a simple example that demonstrate this feature.
>
> I have a gloval variable x:
>
> In:= x=3
>
> Out= 3
>
> Now I define a module with local varibles x and f, call g, and get the
> expected result. The value of global variable x does not interfere with
> the local x, as expected.
>
> In:= g:=Module[{x,f},f[x_]:=x;f]
>
> In:= g
>
> Out= 5
>
> However, if I use Set (=) instead of SetDelayed (:=) in the definition of
> my function f inside the module, the result will be different:
>
> In:= h:=Module[{x,f},f[x_]=x;f]
>
> In:= h
>
> Out= 3
>
> In this case the Module ignores the fact that x is supposed to be a local
> variable, and for some reason uses the value of the global x inside the
> module.
>
> Can somebody explain me if this is an expected behaviour of the Module[]?
>
> I am using version 5.1 on a PC:
> In:= \$Version
>
> Out= 5.1 for Microsoft Windows (October 25, 2004)
>
> Thanks.