Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2017/imperative-programming/8/a/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming 8 a Solution by
Codex 0 2026-10-31
class MSet[T](contents: List[T]) {
protected var data: List[T] = contents
def add(x: T): Unit = {
data = x :: data
}
def delete(): T = data match {
case x :: xs => data = xs; x
case Nil => throw new NoSuchElementException("MSet.delete")
}
}The representation invariant interprets the list by its multiset of occurrences; order is immaterial and duplicates remain distinct occurrences.
add increases one multiplicity, while delete returns and removes one occurrence. The field is protected so the minimum-search subclass in part (d) can inspect it. Both successful updates take list operations. Deleting from an empty bag raises an explicit exception. New to topics? Read the docs here!