Back: Programming
Previous: Anonymous Functions
Next: Compiling functions, timing

Programming in Mathematica

Iterating a function with Nest and Fold

Nest: iterates a function (of one variable) on an initial value n times


Nest[ (7+#^2)&,  z,  4]

	                    2 2 2 2
	7 + (7 + (7 + (7 + z ) ) )


NestList gives a list of the original expression and all n "Nest" values


NestList[ (7+#^2)&,  z,  4]

	         2            2 2                 2 2 2
	{z, 7 + z , 7 + (7 + z ) , 7 + (7 + (7 + z ) ) , 
	 
	                      2 2 2 2
	  7 + (7 + (7 + (7 + z ) ) ) }


Fold: operates on a function of TWO parameters, taking the 2nd parameter (at each iteration) from a list of n expressions


Fold[ (#1 - z)^#2 &,   XXX,  {L1,L2,L3} ]

	          L1     L2     L3
	(((XX - z)   - z)   - z)


FoldList: returns the complete list of Fold values


FoldList[  (#1 - z)^#2 &,   XXX,  {L1,L2,L3} ]

	               L1            L1     L2
	{XXX, (XXX - z)  , ((XXX - z)   - z)  , 
	 
	             L1     L2     L3
	  (((XXX - z)   - z)   - z)  }


Example: using FoldList with monthly mortgage payments/debt


remaining[princ_, paymt_] := princ(1+rate/1200) - paymt

rate = 7.75;	(* percent *)

FoldList[remaining, 90000., {880,880,880, 0, 880}]

	{90000., 89701.2, 89400.6, 89097.9, 89673.4, 89372.5}