Functional Programming
Level 1 introduced Map, Apply, and pure functions. This lesson adds
the other functions that let you replace almost every loop.
The examples in this level use symbols like x, f, a, and b
without values. If you assigned them earlier, start a fresh kernel
(Evaluation → Quit Kernel) or run Clear[x, f, a, b, c] first.
Fold: accumulate over a list
Fold[f, x, {a, b, c}]
Fold[Plus, 0, {1, 2, 3, 4}]
FoldList[Plus, 0, {1, 2, 3, 4}]
Fold[10 #1 + #2 &, 0, {4, 7, 2}]
f[f[f[x, a], b], c]
10
{0, 1, 3, 6, 10}
472
Fold[f, start, list] feeds each element into the running result.
FoldList keeps every intermediate value. The last line builds a number
from its digits.
Nest: repeat a function
Nest[f, x, 3]
NestList[2 # &, 1, 5]
NestWhile[#/2 &, 96, EvenQ]
NestWhileList[If[EvenQ[#], #/2, 3 # + 1] &, 6, # != 1 &]
FixedPoint[(# + 2/#)/2 &, 1.]
f[f[f[x]]]
{1, 2, 4, 8, 16, 32}
3
{6, 3, 10, 5, 16, 8, 4, 2, 1}
1.41421
NestWhile[f, x, test]keeps applyingfwhiletestis true.- The fourth line is the Collatz sequence starting at 6.
FixedPointrepeats until the result stops changing — here Newton's method converging to √2.
Working with several lists
MapThread[f, {{a, b}, {c, d}}]
MapIndexed[f, {a, b}]
Outer[Times, {1, 2}, {3, 4}]
Array[#^2 &, 4]
Through[{Min, Max}[{3, 1, 2}]]
(f @* g)[x]
{f[a, c], f[b, d]}
{f[a, {1}], f[b, {2}]}
{{3, 4}, {6, 8}}
{1, 4, 9, 16}
{1, 3}
f[g[x]]
MapThreadwalks several lists in parallel.MapIndexedalso passes each element's position.Outercombines every element of one list with every element of another.Throughapplies several functions to the same argument.f @* gis composition:gfirst, thenf.
Why bother?
Functional code says what to compute, not how to step through it. It is usually shorter, easier to test, and faster than loops that modify variables — and it's the style the rest of this course uses.
Practice
Use FoldList to compute the running balance of an account that starts
at 100 and receives the changes {20, -50, 10, -5}.
Show solution
FoldList[Plus, 100, {20, -50, 10, -5}]
{100, 120, 70, 80, 75}