Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2005
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: a dangerous feature of Module[]?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg57497] Re: a dangerous feature of Module[]?
  • From: Gennady Stupakov <stupakov at yahoo.com>
  • Date: Sun, 29 May 2005 21:00:16 -0400 (EDT)
  • References: <d76ol2$7si$1@smc.vnet.net>
  • Reply-to: Gennady Stupakov <stupakov at yahoo.com>
  • Sender: owner-wri-mathgroup at wolfram.com

Thanks to everybody who replied to my post.

Experts are aware of this feature of Module, and I was referred to a 
recent discussion of a related issue in
http://forums.wolfram.com/mathgroup/archive/2005/May/msg00112.html

I checked the description of scoping in Mathematica book (section 2.6) to 
find out that most examples there use Set, rather then them SetDelayed, to 
illustrate the mechanism of local variables in Module. The book totally 
ignores all the subtleties of the scoping issues. That is frustrating -- 
after more then 10 years programming in Mathematica I realised that many of my 
codes might have serious bugs.


Gennady.


On Fri, 27 May 2005, Gennady Stupakov wrote:

> 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.
>
>


  • Prev by Date: making an animated picture from many pictures
  • Next by Date: Two related question. Question 1
  • Previous by thread: Re: a dangerous feature of Module[]?
  • Next by thread: Re: a dangerous feature of Module[]?