MathGroup Archive 1999

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

Search the Archive

Re: Block vs. Module

  • To: mathgroup at smc.vnet.net
  • Subject: [mg15692] Re: Block vs. Module
  • From: "Allan Hayes" <hay at haystack.demon.co.uk>
  • Date: Mon, 1 Feb 1999 14:54:12 -0500 (EST)
  • References: <78umac$982@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Fred Simons wrote in message <78umac$982 at smc.vnet.net>...
>Eckhard,
>
>When using Block, there might be an interaction between the local
>variables defined in Block and the variables you use yourself. Have a
>look at the following example:
>
> In[1]:= f[x_] := Block[ {i}, Sum[x^i, {i, 1, 5} ]]
>
>In[2]:= f[a]
>
>Out[2]= \!\(a + a\^2 + a\^3 + a\^4 + a\^5\)
>
>In[3]:= f[i]
>
>Out[3]= 3413
>
>In this situation I would like to see a polynomial in i instead of a
>number. With Module, this cannot happen because Module creates names
>for the local variables that the user is supposed not to use:
>
>In[4]:= g[x_] := Module[ {i}, Sum[x^i, {i, 1, 5} ]]
>
>In[5]:= g[a]
>
>Out[5]= \!\(a + a\^2 + a\^3 + a\^4 + a\^5\)
>
>In[6]:= g[i]
>
>Out[6]= \!\(i + i\^2 + i\^3 + i\^4 + i\^5\)
>
>If you are only interested in variables that have numerical values,  you
>can safely use Block instead of Module.
>
>Hope this helps,
>
>
>Fred Simons
>Eindhoven University of Technology

Fred

It might be useful to analyse the evaluation of the Module version - it
is scoping that does the trick:

After

g[x_] := Module[ {i}, Sum[x^i, {i, 1, 5} ]]

The first step in the evaluation of

g[i].

should apparently generate the result of replacing x inside Module[...]
by i; that is

Module[ {i}, Sum[i^i, {i, 1, 5} ]]

which would not be what we want.

But because Module is a scoping construct, and in the the original
Module[...]  the i in {i} is bound to the i in x^i, the replacement of
the x triggers a change of
the original i's to i$, so that we get

Module[ {i$}, Sum[i^i$, {i, 1, 5} ]]

Then Module replaces i$ in  Sum[...] with i&n (where n is the current
vale of $ModuleNumber) and gives

Sum[i^i$n, {i, 1, 5} ]]

which then evaluates.

We can see this by using

TracePrint[g[i]].

We can use scoping alone (in a contrived way!)

Clear[g,a]

g[x_] :=( i_->Sum[x^i,{i,2}])[[2]]

g[a]

    a + a^2

g[i]

    i + i^2

The first step in evaluating g[i], including scoping, gives

    ( i$_->Sum[i^i$,{i$,2}])[[2]]

Allan

---------------------
Allan Hayes
Mathematica Training and Consulting
www.haystack.demon.co.uk
hay at haystack.demon.co.uk
Voice: +44 (0)116 271 4198
Fax: +44 (0)870 164 0565








  • Prev by Date: Re: 4th order DE, NDSolve no solution, why?
  • Next by Date: RE: Help to clarify 'Map', 'Apply', and 'Thread'.
  • Previous by thread: Re: 4th order DE, NDSolve no solution, why?
  • Next by thread: RE: Help to clarify 'Map', 'Apply', and 'Thread'.