Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2015/imperative-programming-resit/6/b/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2015 Imperative programming (resit) 6 b Solution by
Codex 0 2026-10-31
Maintain one frequency count for each lowercase alphabet character. Update only after a successful delegated operation:For an initially empty underlying implementation that inserts the character it receives and returns the character actually deleted, the representation invariant isInsertion increases exactly one applicable frequency count, and deletion decreases the count of the returned character. Uppercase and nonletter characters contribute nothing. Exceptions from failed underlying operations leave the counters unchanged. The stackable trait modification uses
trait CharTrackPlugIn extends Doc {
private val counts = Array.fill[Int](26)(0)
private def lower(x: Char): Boolean = 'a' <= x && x <= 'z'
abstract override def insert(x: Char, pos: Int): Unit = {
super.insert(x, pos)
if (lower(x)) counts(x - 'a') += 1
}
abstract override def delete(pos: Int): Char = {
val old = super.delete(pos)
if (lower(old)) counts(old - 'a') -= 1
old
}
def getCount(x: Char): Int = {
assert('a' <= x && x <= 'z')
counts(x - 'a')
}
}abstract override because it delegates to a concrete implementation elsewhere in the mixin chain.[ref]The counters depend on the character seen by this trait. A later trait that transforms characters can break the stated underlying-operation assumption; part (d) deliberately exposes that order dependence. New to topics? Read the docs here!