Iterators and efficiency
Write a sequence type, predict what lazy code evaluates, classify orders of growth, and memoize a tree-recursive count.
This discussion goes with Lessons 17 and 18.
Q1: What would Swift print?
What would Swift print?
let lazySquares = (1...).lazy.map { $0 * $0 }
let bigOnes = lazySquares.filter { $0 > 20 }
print(Array(bigOnes.prefix(2)))Show answer and explanation
Answer[25, 36]
Nothing is computed until Array asks for elements. Squares 1 to 16 are
filtered out; 25 and 36 are the first two above 20, and the infinite range
is never exhausted.
What would Swift print?
var calls = 0
let numbers = [1, 2, 3, 4].lazy.map { n -> Int in
calls += 1
return n * 10
}
_ = numbers.first
_ = numbers.first
print(calls)Show answer and explanation
Answer2
A lazy sequence does not remember its results: each first computes the
first element again. Collect it into an Array to compute each element only
once.
Q2: Repeat
Write a sequence Repeat that yields the same value a given number of
times, using Sequence and IteratorProtocol.
Show solution
struct Repeat: Sequence, IteratorProtocol {
let value: Int
var remaining: Int
mutating func next() -> Int? {
guard remaining > 0 else {
return nil
}
remaining -= 1
return value
}
}
assert(Array(Repeat(value: 7, remaining: 3)) == [7, 7, 7])
assert(Repeat(value: 2, remaining: 4).reduce(0, +) == 8)
assert(Array(Repeat(value: 1, remaining: 0)) == [])Q3: Orders of growth
Give the order of growth of each function’s running time in terms of n.
func one(_ n: Int) -> Int {
var total = 0
for i in 0..<n {
total += i
}
return total
}
func two(_ n: Int) -> Int {
var total = 0
var i = 1
while i < n {
total += i
i *= 2
}
return total
}
func three(_ values: [Int]) -> Bool {
for i in values.indices {
for j in values.indices where i != j && values[i] == values[j] {
return true
}
}
return false
}
func four(_ n: Int) -> Int {
n <= 1 ? 1 : four(n - 1) + four(n - 2)
}
print(one(10), two(10), three([1, 2, 3]), four(10))
Show solution
oneis linear, Θ(n): one pass of constant work.twois logarithmic, Θ(log n):idoubles each time, so it reachesnafter about log₂ n steps.threeis quadratic, Θ(n²), in the worst case (no duplicates), where every pair is compared. When a duplicate appears early it returns sooner; orders of growth usually describe the worst case.fouris exponential: it has the call tree of Lesson 8’sfib, which grows by about 1.6× with each step up inn.
Q4: Memoize grid paths
Lab 7’s paths(m, n) counted routes through a grid with tree recursion, and
takes a long time for an 18 by 18 grid. Memoize it with a dictionary kept
inside the function.
Show solution
func paths(_ m: Int, _ n: Int) -> Int {
var memo: [[Int]: Int] = [:]
func count(_ m: Int, _ n: Int) -> Int {
if m == 1 || n == 1 {
return 1
}
if let known = memo[[m, n]] {
return known
}
let result = count(m - 1, n) + count(m, n - 1)
memo[[m, n]] = result
return result
}
return count(m, n)
}
assert(paths(5, 7) == 210)
assert(paths(18, 18) == 2_333_606_220)There are only m × n different argument pairs, so the memoized version does about that much work. The unmemoized one would make billions of calls for the 18 by 18 grid.