MathGroup Archive 2012

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

Search the Archive

Re: Funny Behavior of Module

  • To: mathgroup at smc.vnet.net
  • Subject: [mg124747] Re: Funny Behavior of Module
  • From: "Oleksandr Rasputinov" <oleksandr_rasputinov at ymail.com>
  • Date: Sat, 4 Feb 2012 06:27:07 -0500 (EST)
  • Delivered-to: l-mathgroup@mail-archive0.wolfram.com
  • References: <jgg195$bnb$1@smc.vnet.net>

On Fri, 03 Feb 2012 07:10:29 -0000, Louis Talman <talmanl at gmail.com> wrote:

> I know that Module exhibits some funny behavior, but this behavior is
> something I've never seen before. It seems wrong to me.
>
> In a new kernel session enter
>
> f[x_] := Module[{a},a = x^2; x = y; a]
>
> f[z]
>
> z
>
> Mathematica returns y for z, as it ought to. (In fact, the purpose of
> the code was to demonstrate to students what can happen when a Module
> monkeys with its formal parameters.)
>
> But f[z] returns y^2. It seems to me that it should return z^2, but that
> for some reason it's interpreting the first Set instruction in the body
> of the Module as a SetDelayed instruction. (We get exactly the same
> behavior if we replace that Set with SetDelayed in the code.)
>
> Can anyone explain what's going on here? ITABOAF?
>
>
> --Lou Talman
>

f[z] does return z^2, in a sense. However, after setting a = z^2 in the  
Module, z is immediately set to y. So, in the output, z is duly replaced  
with y and the result appears as y^2. I'm not too sure where the source of  
confusion lies but perhaps it will help to recall that in pattern-matched  
definitions such as f[x_] := (some function of x), the parameter is  
directly substituted into the function body where x appears. Here x does  
not exist as a symbol in its own right; it just acts as a placeholder for  
whatever was pattern-matched to x_. If you pass a symbol that can't be  
acted on by Set, x = y does not apply and you will get a different result:

In :=
SetAttributes[q, Protected];
f[q]

During evaluation of In := Set::wrsym: Symbol q is Protected.

Out =
q^2

So, neither bug nor feature, but simply a confusing example.



  • Prev by Date: Re: Initialization Cells Not Evaluated When Notebook Saved to CDF
  • Next by Date: Cautionary tale : Remember to close StringToStream...
  • Previous by thread: Re: Funny Behavior of Module
  • Next by thread: Re: Funny Behavior of Module