Pattern matching
A robot that follows nested commands, classifying poker hands by pattern, printing expressions with the fewest parentheses, a file-system tree, run-length encoding, and merging lists by matching two at once.
This homework uses Lesson 19. Put everything in hw08.swift with the
assert lines, and run it. In every problem, let the shape of the data
decide the shape of the code: one case per kind of value, and a pattern
wherever you would otherwise check a condition by hand.
Q1: Robot commands
A robot on a grid starts at (0, 0) facing north. It understands four
commands, one of which contains other commands. Write run(_:), which
returns the robot’s final position.
enum Command {
case forward(Int)
case left
case right
case repeatTimes(Int, [Command])
}
Facing north, forward(2) moves to (0, 2); facing east, it moves to (2, 0).
left and right turn 90 degrees.
Show solution
enum Command {
case forward(Int)
case left
case right
case repeatTimes(Int, [Command])
}
struct Robot {
var x = 0
var y = 0
var dx = 0
var dy = 1 // facing north
mutating func perform(_ command: Command) {
switch command {
case .forward(let steps):
x += dx * steps
y += dy * steps
case .left:
(dx, dy) = (-dy, dx)
case .right:
(dx, dy) = (dy, -dx)
case .repeatTimes(let times, let body):
for _ in 0..<times {
for inner in body {
perform(inner)
}
}
}
}
}
func run(_ commands: [Command]) -> (Int, Int) {
var robot = Robot()
for command in commands {
robot.perform(command)
}
return (robot.x, robot.y)
}
assert(run([.forward(2), .right, .forward(3)]) == (3, 2))
assert(run([.repeatTimes(4, [.forward(5), .left])]) == (0, 0)) // a square
assert(run([.repeatTimes(2, [.forward(1), .repeatTimes(3, [.right])])]) == (-1, 1))Storing the direction as a vector turns turning into arithmetic: rotating
(dx, dy) left gives (−dy, dx). repeatTimes holds commands, so perform
calls itself on them: a recursive data type gets a recursive function. Three
right turns equal one left turn, which the last test checks.
Q2: Poker hands
Write classify(_:), which names a hand of five card ranks. Count how many
times each rank appears, sort the counts from largest to smallest, and
switch on that array. Ignore straights and flushes.
| Counts | Hand |
|---|---|
[4, 1] |
four of a kind |
[3, 2] |
full house |
[3, 1, 1] |
three of a kind |
[2, 2, 1] |
two pair |
[2, 1, 1, 1] |
one pair |
| otherwise | high card |
Show solution
func classify(_ ranks: [Int]) -> String {
precondition(ranks.count == 5, "a hand has five cards")
var counts: [Int: Int] = [:]
for rank in ranks {
counts[rank, default: 0] += 1
}
switch counts.values.sorted(by: >) {
case [4, 1]: return "four of a kind"
case [3, 2]: return "full house"
case [3, 1, 1]: return "three of a kind"
case [2, 2, 1]: return "two pair"
case [2, 1, 1, 1]: return "one pair"
default: return "high card"
}
}
assert(classify([9, 9, 9, 9, 2]) == "four of a kind")
assert(classify([3, 13, 3, 13, 3]) == "full house")
assert(classify([5, 8, 5, 11, 2]) == "one pair")
assert(classify([2, 7, 7, 2, 12]) == "two pair")
assert(classify([1, 4, 6, 9, 13]) == "high card")An array literal in a case is an expression pattern: it matches when the
value equals it. Sorting the counts first means the order of the cards does
not matter, which turns the whole classification into a lookup table.
Q3: Fewer parentheses
Lesson 19’s show wrapped every addition in parentheses. Write show(_:) so
that it adds parentheses only where they are needed: around an addition
that is an operand of a multiplication. Addition and multiplication are
associative, so 1 + (2 + 3) can be written 1 + 2 + 3.
indirect enum Expr {
case number(Int)
case variable
case add(Expr, Expr)
case multiply(Expr, Expr)
}
Show solution
indirect enum Expr {
case number(Int)
case variable
case add(Expr, Expr)
case multiply(Expr, Expr)
}
func show(_ expr: Expr) -> String {
func factor(_ e: Expr) -> String {
if case .add = e {
return "(\(show(e)))"
}
return show(e)
}
switch expr {
case .number(let n): return "\(n)"
case .variable: return "x"
case .add(let a, let b): return "\(show(a)) + \(show(b))"
case .multiply(let a, let b): return "\(factor(a)) * \(factor(b))"
}
}
let x = Expr.variable
assert(show(.add(.number(1), .add(x, .number(3)))) == "1 + x + 3")
assert(show(.multiply(.add(x, .number(1)), .number(3))) == "(x + 1) * 3")
assert(show(.add(.multiply(.number(2), x), .number(1))) == "2 * x + 1")
assert(show(.multiply(.number(2), .multiply(x, x))) == "2 * x * x")if case .add = e asks only which case e is, without binding anything.
The helper factor handles the one situation that needs parentheses; every
other combination prints the same with or without them.
Q4: A file system
A file system is a tree: a folder holds files and other folders. Write
totalSize(_:), and largeFiles(_:over:), which returns the paths of all
files larger than a limit, like "home/photos/cat.jpg", in the order they
appear.
indirect enum Item {
case file(name: String, size: Int)
case folder(name: String, contents: [Item])
}
Show solution
indirect enum Item {
case file(name: String, size: Int)
case folder(name: String, contents: [Item])
}
func totalSize(_ item: Item) -> Int {
switch item {
case .file(_, let size):
size
case .folder(_, let contents):
contents.map(totalSize).reduce(0, +)
}
}
func largeFiles(_ item: Item, over limit: Int) -> [String] {
switch item {
case .file(let name, let size):
return size > limit ? [name] : []
case .folder(let name, let contents):
return contents.flatMap { largeFiles($0, over: limit) }.map { "\(name)/\($0)" }
}
}
let home = Item.folder(name: "home", contents: [
.file(name: "notes.txt", size: 4),
.folder(name: "photos", contents: [
.file(name: "cat.jpg", size: 900),
.file(name: "dog.jpg", size: 700),
]),
.folder(name: "empty", contents: []),
.file(name: "movie.mp4", size: 5000),
])
assert(totalSize(home) == 6604)
assert(largeFiles(home, over: 800) == ["home/photos/cat.jpg", "home/movie.mp4"])
assert(largeFiles(.file(name: "a", size: 1), over: 0) == ["a"])Each folder puts its own name in front of every path its contents return,
the same way Lesson 12’s allPaths put a label in front of every path from a
branch.
Q5: Run-length encoding
Run-length encoding compresses repeated characters: "aaabccdddd" becomes a
single a repeated 3 times, then b, then c twice, then d 4 times.
Write encode(_:) and decode(_:) using this enum, and check that decoding
an encoding gives back the original.
enum Run: Equatable {
case single(Character)
case repeated(Character, Int)
}
Show solution
enum Run: Equatable {
case single(Character)
case repeated(Character, Int)
}
func encode(_ text: String) -> [Run] {
var runs: [Run] = []
for character in text {
switch runs.last {
case .single(let c) where c == character:
runs[runs.count - 1] = .repeated(c, 2)
case .repeated(let c, let n) where c == character:
runs[runs.count - 1] = .repeated(c, n + 1)
default:
runs.append(.single(character))
}
}
return runs
}
func decode(_ runs: [Run]) -> String {
var text = ""
for run in runs {
switch run {
case .single(let c): text.append(c)
case .repeated(let c, let n): text += String(repeating: c, count: n)
}
}
return text
}
assert(encode("aaabccdddd") == [.repeated("a", 3), .single("b"), .repeated("c", 2), .repeated("d", 4)])
assert(encode("") == [])
for text in ["aaabccdddd", "", "abc", "zzzzzzzzzz"] {
assert(decode(encode(text)) == text)
}runs.last is an optional, and matching it against .single(let c) works
without unwrapping first: Swift lifts enum case patterns through optionals
automatically, so nil simply matches nothing but default. The round-trip
check at the end is a property test from Lesson 23, in miniature.
Q6 (optional): Merging two lists
Write merge(_:_:), which merges two sorted linked lists into one sorted
list, with a single switch on the pair (a, b).
indirect enum List: Equatable {
case empty
case node(Int, List)
}
Show solution
indirect enum List: Equatable {
case empty
case node(Int, List)
}
func merge(_ a: List, _ b: List) -> List {
switch (a, b) {
case (.empty, let rest), (let rest, .empty):
return rest
case let (.node(x, restA), .node(y, _)) where x <= y:
return .node(x, merge(restA, b))
case let (.node, .node(y, restB)):
return .node(y, merge(a, restB))
}
}
func list(_ values: Int...) -> List {
values.reversed().reduce(List.empty) { .node($1, $0) }
}
assert(merge(list(1, 4, 6), list(2, 3, 7, 8)) == list(1, 2, 3, 4, 6, 7, 8))
assert(merge(list(), list(5)) == list(5))
assert(merge(list(2, 2), list(2)) == list(2, 2, 2))The first case handles either list being empty with one pattern. After it,
both are nodes, and the where clause chooses which head comes first. The
compiler checks that the three cases together cover every pair.
Int... makes list take any number of arguments, as an array.