Mathematica 9 is now available
Student Support Forum
-----
Student Support Forum: 'Defining a new function in a function' topicStudent Support Forum > General > Archives > "Defining a new function in a function"

< Previous CommentHelp | Reply To Comment | Reply To Topic
Author Comment/Response
Bill Simpson
10/29/12 12:15pm

Use Trace to observe hidden behavior:

In[1]:=
Trace[NestList[Function[x,x^2],2,4]]

Out[1]= {
NestList[Function[x, x^2], 2, 4],
{Function[x, x^2][2],2^2,4},
{Function[x, x^2][4],4^2,16},
{Function[x, x^2][16],16^2,256},
{Function[x, x^2][256],256^2,65536},
{2, 4, 16, 256, 65536}}

Compare with

In[2]:= Trace[test[w_]:=NestList[Function[x,w],2,4];test[x^2]]

Out[2]= {
test[w_] := NestList[Function[x, w], 2, 4];test[x^2],
{test[w_] := NestList[Function[x, w], 2, 4],Null,},
{test[x^2],NestList[Function[x$, x^2], 2, 4],
{Function[x$, x^2][2],x^2},
{Function[x$, x^2][x^2],x^2},
{Function[x$, x^2][x^2],x^2},
{Function[x$, x^2][x^2],x^2},
{2, x^2, x^2, x^2, x^2}}},
{2, x^2, x^2, x^2, x^2}}

Notice those x$ which are different from x.
Compare with

In[6]:= Trace[test[w_]:=NestList[Function[x,w],2,4];test[x$^2]]

Out[6]= {test[w_] := NestList[Function[x, w], 2, 4]; test[x$^2],
{test[w_] := NestList[Function[x, w], 2, 4],Null},{test[x$^2],NestList[Function[x$, x$^2], 2, 4],{Function[x$, x$^2][2],2^2,4},
{Function[x$, x$^2][4],4^2,16},
{Function[x$, x$^2][16],16^2,256},
{Function[x$, x$^2][256,256^2,65536},
{2, 4, 16, 256, 65536}},
{2, 4, 16, 256, 65536}}

There must be a page in the documentation somewhere that explains exactly why this is the correct behavior.

URL: ,

Subject (listing for 'Defining a new function in a function')
Author Date Posted
Defining a new function in a function Simon Emil 10/27/12 08:58am
Re: Defining a new function in a function Bill Simpson 10/29/12 12:15pm
< Previous CommentHelp | Reply To Comment | Reply To Topic