**2.2.2 Applying Functions Repeatedly**

Ways to apply functions of one argument repeatedly.

Nest[f,x,n] takes the "name" f of a function, and applies the function n times to x.
In[1]:= **Nest[f, x, 4]**

Out[1]=

This makes a list of each successive nesting.
In[2]:= **NestList[f, x, 4]**

Out[2]=

Here is a simple function.
In[3]:= **recip[x_] := 1/(1 + x)**

You can iterate the function using Nest.
In[4]:= **Nest[recip, x, 3]**

Out[4]=

Many programs you write will involve operations that need to be iterated several times. Nest and NestList are powerful constructs for doing this.

Here is a function that takes one step in Newton's approximation to

.
In[5]:= **newton3[x_] := N[ 1/2 ( x + 3/x ) ]**

Here are five successive iterates of the function, starting at

.
In[6]:= **NestList[newton3, 1.0, 5]**

Out[6]=

Using the function FixedPoint, you can automatically continue applying newton3 until the result no longer changes.
In[7]:= **FixedPoint[newton3, 1.0]**

Out[7]=

Here is the sequence of results.
In[8]:= **FixedPointList[newton3, 1.0]**

Out[8]=

You control when FixedPointList stops by giving a function with which to compare successive results.
In[9]:= **FixedPointList[newton3, 1.0,**

SameTest -> (Abs[#1 - #2] < 10.^-4 &)]

Out[9]=

The functional operations Nest and NestList take a function f of one argument, and apply it repeatedly. At each step, they use the result of the previous step as the new argument of f.

It is important to generalize this notion to functions of two arguments. You can again apply the function repeatedly, but now each result you get supplies only one of the new arguments you need. A convenient approach is to get the other argument at each step from the successive elements of a list.

Ways to repeatedly apply functions of two arguments.

Here is an example of what FoldList does.
In[10]:= **FoldList[f, x, {a, b, c}]**

Out[10]=

Fold gives the last element of the list produced by FoldList.
In[11]:= **Fold[f, x, {a, b, c}]**

Out[11]=

This gives a list of cumulative sums.
In[12]:= **FoldList[Plus, 0, {a, b, c}]**

Out[12]=

Using Fold and FoldList you can write many elegant and efficient programs in Mathematica. In some cases, you may find it helpful to think of Fold and FoldList as producing a simple nesting of a family of functions indexed by their first argument.

This defines a function nextdigit.
In[13]:= **nextdigit[a_, b_] := 10 a + b**

Here is a rather elegant definition of a function that gives the number corresponding to a list of digits in base 10.
In[14]:= **tonumber[digits_] := Fold[nextdigit, 0, digits]**

Here is an example of tonumber in action.
In[15]:= **tonumber[{1, 3, 7, 2, 9, 1}]**

Out[15]=