Higher-order functions
Environment diagrams with closures, tracing functions that return functions, and writing keep, makeKeeper, and matchK.
This discussion goes with Lessons 4 and 5. The diagrams now include closures, whose parent is the frame they were created in.
Q1: A closure’s diagram
Draw the environment diagram when this program prints, and give the output.
func makeAdder(_ n: Int) -> (Int) -> Int {
return { k in n + k }
}
let n = 10
let addThree = makeAdder(3)
print(addThree(n))
Show solution
It prints 13.
Global frame
makeAdder │ func makeAdder(_:) [parent = Global]
n │ 10
addThree │ closure [parent = f1]
f1: makeAdder [parent = Global]
n │ 3
Return │ closure
f2: closure [parent = f1]
k │ 10
Return │ 13The argument n in addThree(n) is looked up in the global frame (10) and
becomes k. Inside the closure, n is looked up from f2 to its parent f1,
where it is 3.
Q2: What would Swift print?
What would Swift print?
func twice(_ f: @escaping (Int) -> Int) -> (Int) -> Int {
return { x in f(f(x)) }
}
let addTwo = twice { $0 + 1 }
print(addTwo(5), twice(twice { $0 * 2 })(1))Show answer and explanation
Answer7 16
twice of add-one adds 2, so addTwo(5) is 7. twice(twice(double))
doubles four times: 1 becomes 16.
What would Swift print?
var calls = 0
let f = { (x: Int) -> Int in
calls += 1
return x + calls
}
print(f(10), f(10), calls)Show answer and explanation
Answer11 12 2
The closure changes the captured global calls each time, so the same
argument gives different results. This is why functions with side effects
are harder to reason about than pure ones.
What would Swift print?
func pick(_ useFirst: Bool) -> (Int, Int) -> Int {
useFirst ? { a, _ in a } : { _, b in b }
}
print(pick(true)(3, 4), pick(false)(3, 4))Show answer and explanation
Answer3 4
pick returns one of two closures. _ ignores the argument a closure does
not need.
Q3: Keep
Write keep(_:_:), which returns the numbers from 1 to n for which cond
is true, in order.
func keep(_ n: Int, _ cond: (Int) -> Bool) -> [Int] {
// your code here
}
Show solution
func keep(_ n: Int, _ cond: (Int) -> Bool) -> [Int] {
var kept: [Int] = []
for i in 1...n where cond(i) {
kept.append(i)
}
return kept
}
assert(keep(10, { $0 % 3 == 0 }) == [3, 6, 9])
assert(keep(5, { _ in false }) == [])Q4: Make a keeper
Write makeKeeper(_:), which takes n and returns a function that takes a
condition and does what keep does. Use a closure, not a copy of keep’s
loop.
func makeKeeper(_ n: Int) -> ((Int) -> Bool) -> [Int] {
// your code here
}
Show solution
func keep(_ n: Int, _ cond: (Int) -> Bool) -> [Int] {
var kept: [Int] = []
for i in 1...n where cond(i) {
kept.append(i)
}
return kept
}
func makeKeeper(_ n: Int) -> ((Int) -> Bool) -> [Int] {
return { cond in keep(n, cond) }
}
let upToFive = makeKeeper(5)
assert(upToFive({ $0 % 2 == 1 }) == [1, 3, 5])
assert(upToFive({ $0 > 3 }) == [4, 5])The return type reads right to left: makeKeeper returns a function that
takes a (Int) -> Bool and returns an array. n is captured once and
reused by every call.
Q5: Match k
Write matchK(_:), which returns a function that checks whether every pair
of digits k apart in a number are equal. For example, in 1010 each digit
equals the one two places away, so matchK(2)(1010) is true.
func matchK(_ k: Int) -> (Int) -> Bool {
// your code here
}
Show solution
func matchK(_ k: Int) -> (Int) -> Bool {
var shift = 1
for _ in 0..<k {
shift *= 10
}
return { number in
var rest = number
while rest >= shift {
if rest % 10 != (rest / shift) % 10 {
return false
}
rest /= 10
}
return true
}
}
assert(matchK(2)(1010))
assert(!matchK(2)(2010))
assert(!matchK(1)(1010))
assert(matchK(1)(1))
assert(matchK(3)(123123))shift is 10ᵏ, computed once when matchK is called rather than every
time the returned function runs. Dividing by it moves to the digit k
places to the left.