Re: a dangerous feature of Module[]?

*To*: mathgroup at smc.vnet.net*Subject*: [mg57447] Re: [mg57422] a dangerous feature of Module[]?*From*: "David Park" <djmp at earthlink.net>*Date*: Sat, 28 May 2005 05:39:11 -0400 (EDT)*Sender*: owner-wri-mathgroup at wolfram.com

Gennady, I agree, this is a trap for many Mathematica users. It's a feature that most old timers know about. The same thing happens with Set and SetDelayed even outside a Module. When Mathematica evaluates a statement, or a Module, if fills in all the value definitions it knows and can. It doesn't notice that x_ is a pattern on the lhs of a Set statement. Nor did it notice that x was a locally defined variable in Module. It seems to only take that into account after the known values are filled in. But it does notice the difference between Set and SetDelayed. The basic precaution is don't assign values to variables and then use them on the right hand side of Set statements, unless you want that value to be used. (And sometimes you might want the Set values to be used and maybe that's why Mathematica behaves this way.) Also, I try to avoid giving values to single character symbols. They are too valuable as symbols and this is the single greatest cause of problems for users. It is much better to assign values with data rules or by filling them into an argument list on specific calls. Stay symbolic and exact as long as you can. Most times substituting specific values is the last step in a calculation. David Park djmp at earthlink.net http://home.earthlink.net/~djmp/ From: Gennady Stupakov [mailto:stupakov at yahoo.com] To: mathgroup at smc.vnet.net 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[1]:= x=3 Out[1]= 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[2]:= g:=Module[{x,f},f[x_]:=x;f[5]] In[3]:= g Out[3]= 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[4]:= h:=Module[{x,f},f[x_]=x;f[5]] In[5]:= h Out[5]= 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[7]:= $Version Out[7]= 5.1 for Microsoft Windows (October 25, 2004) Thanks. Gennady.