Math 350 - Lecture 8

Nest, Fold, and more.

Nest

One specific looping operation is composition of functions

This is accomplished with Nest:

Nest[function, input, number of compositions]

Nest[Log,x,5]

Nest[#^2&, 2, 3]

We might also want to keep a list of everything performed along the way - NestList

NestList[Log, x, 5]

NestList[#^2&, 2, 3]

Instead of a fixed number of iterations, we might want to proceed until a condition is met.

NestWhileList[Most, {a, b, c, d, e}, #≠{}&]

FixedPointList[Floor[#/2]&, 983]

Most[{a, b, c}]

Fold

Fold[f, x, {a, b, c}]

FoldList[f, x, {a, b, c}]

FoldList[Plus, 0, {1, 2, 3}]

Problem 7.15

1, 2, 3, 4, can you find some combination of plus and minus so that
(1^2) ± 2^2 ± 3^2 ±(4^2)=0?

Plus@@Range[4]^2==0

Range[4]^2

Tuples[{1,-1},3]

A = Map[Prepend[#, 1]&, Tuples[{1,-1},3]]

B=Table[Range[4]^2, {i, 8}]

Map[Apply[Plus],A B]

Odds and Ends

What is a rule? (Exercise 7.8)

Rule[a,b]

2x + 3 y + x a + y a^2 /.a->b

ReplaceAll[2x + 3 y + x a + y a^2 , a->b]

2x + 3 y + x a + y a^2 /.{a->1, x->0, y->2}

Table[(Subscript[x, i]), {i, 1, 10}]

Partition[Table[(Subscript[x, i]), {i, 1, 10}], 2, 1]

Map[Rule, Partition[Table[(Subscript[x, i]), {i, 1, 10}], 2, 1]]

Map[Apply[Rule], Partition[Table[(Subscript[x, i]), {i, 1, 10}], 2, 1]]