Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2004
*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 2004

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

Search the Archive

Re: Defining a function in module problem?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg45988] Re: [mg45975] Defining a function in module problem?
  • From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
  • Date: Mon, 2 Feb 2004 05:20:22 -0500 (EST)
  • References: <200401311020.FAA26919@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

On 31 Jan 2004, at 11:20, jose flanigan wrote:

> why does this
>
> a[x_] := Module[{f, g}, g = z/3; f = Function[z, Evaluate[g]]; f[x]]
>
> produce
>
> a[1] = z/3
>
> instead of
>
> a[1]=1/3
>
> I don't understand the philosophy here.
>
> thanks in advance.
>
>
>

Module and Function are both scoping constructs. Form the documentation:

When nested scoping constructs are evaluated, new symbols are 
automatically generated in the inner scoping constructs so as to avoid 
name conflicts with symbols in outer scoping constructs.
In general, symbols with names of the form xxx are renamed xxx$.

This is somewhat vague so let's see it in action:

In[3]:=
Function[a,g]

Out[3]=
Function[a,g]

but

In[4]:=
Module[{g},Function[a,g]]

Out[4]=
Function[a$,g$477]

So now look at what happens in your case:


a[x_] := Module[{f, g}, g = z/3;
      f = Function[z, Evaluate[g]]; f[x]]; a[1]


z/3

Your definition of a has a local variable g in the body of the 
function. This local variable then appears in the definition of f. 
Inside Module g is replaced by another unique variable whose name has 
the form g$SomeNuber. But this automatically cases  z to be replaced by 
a local name z$SomeOtherNumber and so it no longer is the original z. 
Then g evaluates to the original z. The rest is obvious.

To sum up: the reason why the name of z inside Function was changed was 
to prevent code like this working the way you wanted ;-)


Andrzej Kozlowski
Chiba, Japan
http://www.mimuw.edu.pl/~akoz/


  • Prev by Date: Re: changing replacement rule arrow ( ->) to equal sign(==)...
  • Next by Date: RE: How to make the Mathematica Kernel return DisplayPackets?
  • Previous by thread: Re: Defining a function in module problem?
  • Next by thread: RE: Re: Defining a function in module problem?