IntLists
Practice with naked linked lists: printing, structural equality, catenating with and without destroying the originals, squaring primes in place, reversing, and detecting a cycle.
This homework goes with Lessons 27 and 28, like CS61B’s IntList homework.
Start hw12.swift with this class, and add each answer to it or after it.
Write loops, not recursion, for anything that walks a whole list, unless the
problem says otherwise.
final class IntList {
var first: Int
var rest: IntList?
init(_ first: Int, _ rest: IntList?) {
self.first = first
self.rest = rest
}
static func of(_ values: Int...) -> IntList? {
values.reversed().reduce(nil) { IntList($1, $0) }
}
}
Q1: Printing
Make IntList conform to CustomStringConvertible, printing
1 -> 2 -> 3.
Show solution
final class IntList {
var first: Int
var rest: IntList?
init(_ first: Int, _ rest: IntList?) {
self.first = first
self.rest = rest
}
static func of(_ values: Int...) -> IntList? {
values.reversed().reduce(nil) { IntList($1, $0) }
}
}
extension IntList: CustomStringConvertible {
var description: String {
var parts: [String] = []
var node: IntList? = self
while let current = node {
parts.append(String(current.first))
node = current.rest
}
return parts.joined(separator: " -> ")
}
}
assert(IntList.of(1, 2, 3)!.description == "1 -> 2 -> 3")
assert("\(IntList(7, nil))" == "7")Q2: Structural equality
Make IntList Equatable: two lists are equal if they have the same items in
the same order. Then explain why == and === now give different answers
for two separately built lists.
Show solution
final class IntList {
var first: Int
var rest: IntList?
init(_ first: Int, _ rest: IntList?) {
self.first = first
self.rest = rest
}
static func of(_ values: Int...) -> IntList? {
values.reversed().reduce(nil) { IntList($1, $0) }
}
}
extension IntList: Equatable {
static func == (lhs: IntList, rhs: IntList) -> Bool {
var a: IntList? = lhs
var b: IntList? = rhs
while let x = a, let y = b {
if x.first != y.first {
return false
}
a = x.rest
b = y.rest
}
return a == nil && b == nil
}
}
let one = IntList.of(1, 2, 3)!
let two = IntList.of(1, 2, 3)!
assert(one == two && !(one === two))
assert(one != IntList.of(1, 2)! && IntList.of(1, 2)! != one)== compares items and === compares identity: two lists built separately
contain the same values in different objects. The last check after the loop
catches lists of different lengths, in either order.
Q3: Catenating, two ways
Write catenate(_:_:), which returns a new list containing the items of a
followed by those of b and changes neither, and dcatenate(_:_:), which
destructively links the end of a to b and returns the result.
Show solution
final class IntList {
var first: Int
var rest: IntList?
init(_ first: Int, _ rest: IntList?) {
self.first = first
self.rest = rest
}
static func of(_ values: Int...) -> IntList? {
values.reversed().reduce(nil) { IntList($1, $0) }
}
var items: [Int] {
var result: [Int] = []
var node: IntList? = self
while let current = node {
result.append(current.first)
node = current.rest
}
return result
}
}
func catenate(_ a: IntList?, _ b: IntList?) -> IntList? {
guard let a else { return b }
let head = IntList(a.first, nil)
var tail = head
var node = a.rest
while let current = node {
tail.rest = IntList(current.first, nil)
tail = tail.rest!
node = current.rest
}
tail.rest = b
return head
}
func dcatenate(_ a: IntList?, _ b: IntList?) -> IntList? {
guard let a else { return b }
var tail = a
while let next = tail.rest {
tail = next
}
tail.rest = b
return a
}
let a = IntList.of(1, 2)
let b = IntList.of(3, 4)
let joined = catenate(a, b)!
assert(joined.items == [1, 2, 3, 4] && a!.items == [1, 2])
let destroyed = dcatenate(a, b)!
assert(destroyed === a && a!.items == [1, 2, 3, 4])
assert(catenate(nil, b)!.items == [3, 4] && dcatenate(a, nil)!.items == [1, 2, 3, 4])catenate copies a’s nodes but shares b’s: nothing changes b, so
sharing is safe as long as nobody later changes b destructively. Whether
that is acceptable is exactly the kind of decision a data structure’s
documentation must state.
Q4: Squaring the primes
Write squarePrimes(_:), which destructively squares every prime number in
the list and returns whether any item changed.
Show solution
final class IntList {
var first: Int
var rest: IntList?
init(_ first: Int, _ rest: IntList?) {
self.first = first
self.rest = rest
}
static func of(_ values: Int...) -> IntList? {
values.reversed().reduce(nil) { IntList($1, $0) }
}
var items: [Int] {
var result: [Int] = []
var node: IntList? = self
while let current = node {
result.append(current.first)
node = current.rest
}
return result
}
}
func isPrime(_ n: Int) -> Bool {
guard n >= 2 else { return false }
var d = 2
while d * d <= n {
if n % d == 0 { return false }
d += 1
}
return true
}
func squarePrimes(_ list: IntList?) -> Bool {
var changed = false
var node = list
while let current = node {
if isPrime(current.first) {
current.first *= current.first
changed = true
}
node = current.rest
}
return changed
}
let list = IntList.of(14, 15, 16, 17, 18)!
assert(squarePrimes(list) && list.items == [14, 15, 16, 289, 18])
assert(!squarePrimes(IntList.of(1, 4, 9)))
assert(!squarePrimes(nil))Q5: Reverse
Write reversed(_:), which destructively reverses a list and returns its new
first node, creating no nodes. Then write a recursive version.
Show solution
final class IntList {
var first: Int
var rest: IntList?
init(_ first: Int, _ rest: IntList?) {
self.first = first
self.rest = rest
}
static func of(_ values: Int...) -> IntList? {
values.reversed().reduce(nil) { IntList($1, $0) }
}
var items: [Int] {
var result: [Int] = []
var node: IntList? = self
while let current = node {
result.append(current.first)
node = current.rest
}
return result
}
}
func reversed(_ list: IntList?) -> IntList? {
var done: IntList? = nil
var remaining = list
while let node = remaining {
remaining = node.rest
node.rest = done
done = node
}
return done
}
func reversedRecursive(_ list: IntList?) -> IntList? {
guard let list, let rest = list.rest else { return list }
let head = reversedRecursive(rest)
rest.rest = list // the old second node now points back at the first
list.rest = nil
return head
}
let a = IntList.of(1, 2, 3, 4)!
let r = reversed(a)!
assert(r.items == [4, 3, 2, 1] && a.items == [1]) // a is now the last node
let back = reversedRecursive(r)!
assert(back === a && back.items == [1, 2, 3, 4])
assert(reversed(nil) == nil)The recursive version reverses the rest first; afterwards, the old second node
is the last node of the reversed rest, so pointing it back at the old first
node finishes the job. The test a.items == [1] shows what “destructive”
means: the variable a still points at the same node, which is now at the end.
Q6 (optional): Detecting a cycle
A buggy destructive function might make a list point back into itself, so that
walking it never ends. Write hasCycle(_:), which detects this using only a
constant amount of extra memory: move one reference one step at a time and
another two steps at a time. If there is a cycle, the fast one eventually lands
on the slow one.
Show solution
final class IntList {
var first: Int
var rest: IntList?
init(_ first: Int, _ rest: IntList?) {
self.first = first
self.rest = rest
}
static func of(_ values: Int...) -> IntList? {
values.reversed().reduce(nil) { IntList($1, $0) }
}
}
func hasCycle(_ list: IntList?) -> Bool {
var slow = list
var fast = list
while let next = fast?.rest, let nextNext = next.rest {
slow = slow?.rest
fast = nextNext
if slow === fast {
return true
}
}
return false
}
let straight = IntList.of(1, 2, 3, 4, 5)!
assert(!hasCycle(straight) && !hasCycle(nil))
let looped = IntList.of(1, 2, 3, 4, 5)!
var last = looped
while let next = last.rest {
last = next
}
last.rest = looped.rest!.rest // 5 points back to 3
assert(hasCycle(looped))
last.rest = nil // break the cycle, so ARC can free the nodesThis is Floyd’s “tortoise and hare” algorithm. Once both are inside the
cycle, the hare gains one step on the tortoise per move, so it cannot jump
over it and must land on it within one trip around. Comparing with === asks
about identity, not value, which is the question here: two different nodes
could hold the same number. The last line breaks the cycle, because a cycle of
strong references would otherwise never be freed.