Re: Funny Behavior of Module
- To: mathgroup at smc.vnet.net
- Subject: [mg124770] Re: Funny Behavior of Module
- From: "Nasser M. Abbasi" <nma at 12000.org>
- Date: Sat, 4 Feb 2012 06:35:06 -0500 (EST)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- References: <jgg195$bnb$1@smc.vnet.net>
- Reply-to: nma at 12000.org
On 2/3/2012 1:10 AM, Louis Talman 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
> Department of Mathematical& Computer Sciences
> Metropolitan State College of Denver
>
> <http://rowdy.mscd.edu/%7Etalmanl>
>
The program is not really a valid Mathematica code, inside
the function, the pattern x_ should always show up on the RHS
of any assignment, not on the LHS.
In your example this line
x=y
is not valid, since the pattern x shows on the left side of
an assignment not on the right side.
As what happens when you wrote it the way you did:
a=x^2 ===> this becomes a=z^2 since x is z
next, you say x=y, which became z=y, since x is z.
next, the last thing you have is 'a'. Now Mathematica
will evaluate 'a', which is z^2. But now 'z' is 'y',
so it does one more transformation rule, Hence 'a' which is 'z^2'
evaluates to 'y^2'
And this is what you see.
This is no different than writing
------------------
Remove["Global`*"]
a=z^2;
z=y;
a
-------------------
and now you'll see that 'a' is y^2 and not z^2. Since
'a' evaluates 'a' to z^2, and 'z' evaluates to 'y^2',
and now the evaluator stops, since there is no more
transformation rules to apply.
One way to do what you did is by introducing a local symbol
-----------------------
Remove["Global`*"]
f[$x_] := Module[{a, x = $x}, a = x^2; x = y; a]
f[z]
--------------------------
now it returns z^2. The reason the above returns z^2 and not
y^2, is because:
a=x^2 ===> this becomes a=z^2 since x is z
next, x=y, but now x is the local x and not z. So, x becomes y.
next, we have'a'. Now Mathematica will evaluate 'a', which is z^2,
and no more. z still is z. So what you get is z^2.
--Nasser