RE: Do Modules Produce Side Effects?
- To: mathgroup at smc.vnet.net
- Subject: [mg47992] RE: [mg47964] Do Modules Produce Side Effects?
- From: "David Park" <djmp at earthlink.net>
- Date: Wed, 5 May 2004 08:10:59 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
Harold, But you didn't include m in the list of local Module variables. Therefore it treated it as the already defined Global variable. m = i^2; Module[{m = 4}, 2m] m 8 i^2 For a case like this, the more efficient statement is probably With[{m = 4}, 2m] 8 With, as the first step, replaces every occurrence of m in the body of the expression by 4. Module creates a new internal variable and initializes it to the value 4. It replaces every occurrence of m in the body by the new internal variable. If we don't give the new internal variable a value, then it will return the new internal variable. Module[{m}, 2m] m 2 m$29 i^2 Block creates a new value (but not variable) for m, which is only used internally. Block[{m = 4}, 2m] m 8 i^2 If we don't give m a value, which is really a misuse of Block, then we see that the original value of the original variable is used. Block[{m}, 2m] m 2 i^2 i^2 David Park djmp at earthlink.net http://home.earthlink.net/~djmp/ From: Harold Noffke [mailto:Harold.Noffke at wpafb.af.mil] To: mathgroup at smc.vnet.net $Version "5.0 for Microsoft Windows [2000] (November 18, 2003)" MathGroup: The MathBook definition of Module tells me, "Module creates new symbols to represent each of its local variables every time it is called." I am led by this, and other Module descriptions, to conclude Modules do not produce side effects, like Blocks do. However, we have ... In[1]:= m=i^2 Out[1]= i^2 In[2]:= Module[ {}, m=4; 2*m ] Out[2]= 8 In[3]:= m Out[3]= 4 I expected m to remain unchanged from its original i^2. But Module changed m to 4, just as I would expect a Block to do. Am I misunderstanding something about the "side effect safety" of Modules? Regards, Harold