Functional abstraction
Generalizing with functions, iterative improvement and Newton’s method, contracts written as documentation and preconditions, and functions that wrap other functions.
- CS61A
- Abstraction · Function Examples · Composing Programs 1.6
A function is an abstraction when you can use it without knowing how it
works. max(3, 9) is 9; you have never needed to see its body. This lesson
is about writing functions that others can use the same way: general enough
to reuse, with a clear promise about what they do.
Generalizing
Lesson 4 turned three sums into one summation by making the varying part
a parameter. The same function handles much less obvious terms. This sum
converges, very slowly, to π:
8/(1·3) + 8/(5·7) + 8/(9·11) + ⋯
func summation(_ n: Int, _ term: (Int) -> Double) -> Double {
var total = 0.0
for k in 1...n {
total += term(k)
}
return total
}
func piSum(_ n: Int) -> Double {
summation(n) { k in 8.0 / Double((4 * k - 3) * (4 * k - 1)) }
}
print(piSum(1000)) // 3.141092653621038
summation now adds Doubles, and piSum only has to say what the kth
term is.
Iterative improvement
Many numerical methods follow one pattern: start with a guess, and keep improving it until it is close enough. The pattern itself can be a function that takes the two varying parts, how to improve and how to judge, as arguments:
func improve(_ update: (Double) -> Double, _ close: (Double) -> Bool, _ guess: Double = 1) -> Double {
var guess = guess
while !close(guess) {
guess = update(guess)
}
return guess
}
// The golden ratio is the positive number x with x * x == x + 1.
let golden = improve({ x in 1 / x + 1 }, { x in abs(x * x - (x + 1)) < 1e-10 })
print(golden) // 1.6180339887802426
guess: Double = 1 gives the parameter a default value, so callers can
leave it out.
Newton’s method is an improvement rule for square roots: a better guess
for √a is the average of x and a / x.
func improve(_ update: (Double) -> Double, _ close: (Double) -> Bool, _ guess: Double = 1) -> Double {
var guess = guess
while !close(guess) { guess = update(guess) }
return guess
}
func squareRoot(_ a: Double) -> Double {
improve({ x in (x + a / x) / 2 }, { x in abs(x * x - a) < 1e-10 })
}
print(squareRoot(2)) // 1.4142135623746899
print(squareRoot(256)) // 16.00000000000039
The second result is not exactly 16: close accepts any guess whose square
is within 10⁻¹⁰ of 256. Floating-point answers are compared with a
tolerance, never with ==.
Put the lines in order
Put the lines in order. improve should keep updating the guess until close accepts it; the program prints true.
}var guess = 1.0func improve(_ update: (Double) -> Double, _ close: (Double) -> Bool) -> Double {while !close(guess) {return guessguess = update(guess)let golden = improve({ 1 / $0 + 1 }, { abs($0 * $0 - ($0 + 1)) < 1e-10 })print(golden > 1.618 && golden < 1.619)}
Show the correct program
func improve(_ update: (Double) -> Double, _ close: (Double) -> Bool) -> Double {
var guess = 1.0
while !close(guess) {
guess = update(guess)
}
return guess
}
let golden = improve({ 1 / $0 + 1 }, { abs($0 * $0 - ($0 + 1)) < 1e-10 })
print(golden > 1.618 && golden < 1.619)Newton’s method in general
The square-root update is one case of a general method. To find a zero of
any differentiable function f, a better guess than x is
x − f(x) / f′(x): follow the tangent line down to where it crosses zero.
The derivative can be approximated numerically, so one higher-order function
solves every such equation:
func findZero(_ f: @escaping (Double) -> Double, _ guess: Double = 1) -> Double {
let dx = 1e-6
var x = guess
while abs(f(x)) > 1e-10 {
let slope = (f(x + dx) - f(x)) / dx
x = x - f(x) / slope
}
return x
}
print(findZero({ $0 * $0 - 2 })) // about 1.4142135623754
print(findZero({ $0 * $0 * $0 - 27 }, 5)) // about 3.0
findZero knows nothing about square or cube roots. The caller describes
the problem as “where is this function zero?” and the method does the rest.
That separation is the reason to write it as a higher-order function.
A function’s contract
To use a function without reading its body, you need to know three things:
what it takes, what it returns, and anything it assumes. Swift writes the
first two in the signature. The rest belongs in a documentation comment,
written with /// directly above the function:
/// Returns the number of ways to choose `k` items from `n`.
///
/// - Precondition: `0 <= k` and `k <= n`.
func choose(_ n: Int, _ k: Int) -> Int {
precondition(0 <= k && k <= n, "k must be between 0 and n")
var result = 1
for i in 0..<k {
result = result * (n - i) / (i + 1)
}
return result
}
print(choose(5, 2)) // 10
Xcode and other editors show these comments when you use the function. The
precondition line turns the assumption into a check: if a caller breaks
the contract, the program stops right there, instead of returning a
meaningless number.
What would Swift print?
func half(_ n: Int) -> Int {
precondition(n % 2 == 0, "n must be even")
return n / 2
}
print(half(half(10)))Show answer and explanation
AnswerError
The inner call half(10) returns 5. The outer call receives 5, which is
odd, so the precondition fails and the program stops with a runtime error.
Nothing is printed: print never receives a value.
Tests as examples
CS61A writes examples as doctests. In Swift, assert lines play the same
role in a lab file: assert(choose(5, 2) == 10) does nothing when the
answer is right and stops the program when it is wrong. In Unit 3 we will
move to Swift’s testing library.
Debugging
CS61A gives debugging its own lecture; here are the habits worth starting now.
- Read the first error. A compile error names a file, line, and column. Later errors are often consequences of the first, so fix it and compile again.
- Print what you assume. A
printthat shows the arguments and the result of a function is the quickest way to find where reality and your expectations part. Remove it once you know. - Assert what must be true. An
assertplaced where a condition must hold turns a wrong result far away into a stop right where things went wrong. - Shrink the input. If
f(1000)is wrong, tryf(0),f(1),f(2). The smallest failing case is usually the base case or the boundary.
The trace function below automates the second habit for any function.
Functions that wrap functions
A higher-order function can add behavior to any function without changing
it. trace prints each argument before calling the function it wraps,
which is handy when debugging:
func trace(_ f: @escaping (Int) -> Int) -> (Int) -> Int {
return { x in
print("->", x)
return f(x)
}
}
let tracedSquare = trace { $0 * $0 }
print(tracedSquare(3))
What would Swift print?
func trace(_ f: @escaping (Int) -> Int) -> (Int) -> Int {
return { x in
print("->", x)
return f(x)
}
}
let t = trace { $0 + 1 }
print(t(t(1)))Show answer and explanation
Answer-> 1\n-> 2\n3
The inner call t(1) runs first: it prints -> 1 and returns 2. Then
t(2) prints -> 2 and returns 3, which the outer print writes.
Searching
search finds the smallest non-negative integer for which a condition
holds:
func search(_ condition: (Int) -> Bool) -> Int {
var x = 0
while !condition(x) {
x += 1
}
return x
}
print(search { $0 * $0 > 30 }) // 6
What would Swift print?
func search(_ condition: (Int) -> Bool) -> Int {
var x = 0
while !condition(x) {
x += 1
}
return x
}
print(search { $0 % 7 == 3 && $0 > 10 })Show answer and explanation
Answer17
The condition asks for a number above 10 that leaves remainder 3 when divided by 7. The candidates with remainder 3 are 3, 10, 17, …; the first one above 10 is 17.
Lab 5: Abstraction
Q0: What would Swift print?
What would Swift print?
func improve(_ update: (Int) -> Int, _ done: (Int) -> Bool, _ start: Int) -> Int {
var x = start
while !done(x) {
x = update(x)
}
return x
}
print(improve({ $0 * 2 }, { $0 > 100 }, 3))Show answer and explanation
Answer192
Starting from 3 and doubling: 6, 12, 24, 48, 96, 192. The first value above 100 is 192.
What would Swift print?
func search(_ condition: (Int) -> Bool) -> Int {
var x = 0
while !condition(x) {
x += 1
}
return x
}
print(search { $0 * $0 >= 50 }, search { _ in true })Show answer and explanation
Answer8 0
7 × 7 is 49, too small, so the first square at least 50 is 8 × 8. A condition that is always true is satisfied immediately, at 0.
What would Swift print?
func check(_ n: Int) -> Int {
assert(n > 0, "n must be positive")
return n * 2
}
print(check(3))
print(check(0))Show answer and explanation
AnswerError
check(3) prints 6, but then check(0) fails its assertion and stops the
program. A crash anywhere makes the whole answer Error.
Q1: Inverse
Using search, write inverse(f): given a function f that is increasing
on the non-negative integers, return a function g such that g(f(x)) == x.
func inverse(_ f: @escaping (Int) -> Int) -> (Int) -> Int {
// your code here
}
Show solution
func search(_ condition: (Int) -> Bool) -> Int {
var x = 0
while !condition(x) { x += 1 }
return x
}
func inverse(_ f: @escaping (Int) -> Int) -> (Int) -> Int {
return { y in search { x in f(x) == y } }
}
let squareRoot = inverse { $0 * $0 }
assert(squareRoot(16) == 4)
assert(squareRoot(144) == 12)
let halve = inverse { $0 * 2 }
assert(halve(10) == 5)The inverse of f at y is “the x whose f(x) is y”, which is exactly
a search. If y is not a value f ever takes, the search never stops,
which is why the problem promises y is in range.
Q2: Count the calls
Write countCalls(f), which returns two functions in a tuple: call, which
behaves exactly like f, and count, which returns how many times call
has been called.
func countCalls(_ f: @escaping (Int) -> Int) -> (call: (Int) -> Int, count: () -> Int) {
// your code here
}
Show solution
func countCalls(_ f: @escaping (Int) -> Int) -> (call: (Int) -> Int, count: () -> Int) {
var calls = 0
let call = { (x: Int) -> Int in
calls += 1
return f(x)
}
return (call, { calls })
}
let counted = countCalls { $0 * 10 }
assert(counted.count() == 0)
assert(counted.call(2) == 20)
assert(counted.call(3) == 30)
assert(counted.count() == 2)Both closures capture the same calls variable from the frame of this call
to countCalls, so count sees the updates that call makes.
Q3: Cube roots
Using improve from this lesson, write cubeRoot(_:) with Newton’s update
for cube roots: a better guess for ∛a is (2x + a / x²) / 3.
Stop when |x³ − a| < 10⁻¹⁰.
Show solution
func improve(_ update: (Double) -> Double, _ close: (Double) -> Bool, _ guess: Double = 1) -> Double {
var guess = guess
while !close(guess) { guess = update(guess) }
return guess
}
func cubeRoot(_ a: Double) -> Double {
improve({ x in (2 * x + a / (x * x)) / 3 }, { x in abs(x * x * x - a) < 1e-10 })
}
assert(abs(cubeRoot(27) - 3) < 1e-9)
assert(abs(cubeRoot(2) * cubeRoot(2) * cubeRoot(2) - 2) < 1e-9)Only the two small closures change; the loop, the stopping logic, and the
default starting guess all come from improve.
Q4: Any root
Using improve, write nthRoot(_:_:), the nth root of a positive number.
Newton’s update for the nth root of a is
((n − 1)·x + a / xⁿ⁻¹) / n. Stop when |xⁿ − a| < 10⁻⁹.
Show solution
func improve(_ update: (Double) -> Double, _ close: (Double) -> Bool, _ guess: Double = 1) -> Double {
var guess = guess
while !close(guess) { guess = update(guess) }
return guess
}
func power(_ x: Double, _ k: Int) -> Double {
var result = 1.0
for _ in 0..<k {
result *= x
}
return result
}
func nthRoot(_ a: Double, _ n: Int) -> Double {
let degree = Double(n)
return improve(
{ x in ((degree - 1) * x + a / power(x, n - 1)) / degree },
{ x in abs(power(x, n) - a) < 1e-9 }
)
}
assert(abs(nthRoot(32, 5) - 2) < 1e-9)
assert(abs(nthRoot(81, 4) - 3) < 1e-9)
assert(abs(nthRoot(2, 2) * nthRoot(2, 2) - 2) < 1e-9)With n of 2 this is the square-root update from the lesson, and with n
of 3 the cube-root update from Q3. One general function replaces both.
Q5: Smoothing
Smoothing a function f means replacing each value f(x) with the average of
f(x − dx), f(x), and f(x + dx). Write smooth(_:dx:), which returns the
smoothed function, with dx defaulting to 0.001.
func smooth(_ f: @escaping (Double) -> Double, dx: Double = 0.001) -> (Double) -> Double {
// your code here
}
Show solution
func smooth(_ f: @escaping (Double) -> Double, dx: Double = 0.001) -> (Double) -> Double {
return { x in (f(x - dx) + f(x) + f(x + dx)) / 3 }
}
let smoothSquare = smooth { $0 * $0 }
assert(abs(smoothSquare(2) - 4.000000666666667) < 1e-12)
assert(smooth({ _ in 7 })(100) == 7) // a constant stays constantFor x², smoothing adds 2·dx²/3 to every value, which is the tiny difference from 4 in the first check.
Q6 (optional): Smooth it again
Write nFoldSmooth(_:_:), which smooths a function n times. Use smooth
and no loops over values, only a loop or reduce over the number of times.
Show solution
func smooth(_ f: @escaping (Double) -> Double, dx: Double = 0.001) -> (Double) -> Double {
return { x in (f(x - dx) + f(x) + f(x + dx)) / 3 }
}
func nFoldSmooth(_ f: @escaping (Double) -> Double, _ n: Int) -> (Double) -> Double {
(0..<n).reduce(f) { smoothed, _ in smooth(smoothed) }
}
assert(abs(nFoldSmooth({ $0 * $0 }, 2)(2) - 4.0000013333333335) < 1e-12)
assert(nFoldSmooth({ $0 * 3 }, 0)(5) == 15) // zero times: unchangedEach step wraps the previous function in another smooth. Nothing is
computed until the final function is called, at which point every layer
calls the one inside it three times.
What’s next
Next lesson: recursion, where a function’s body calls the function itself.