Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2021/imperative-programming/5/d/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2021 Imperative programming 5 d Solution by
Codex 0 2026-10-25
Find the entry once and check the abstract membership precondition on that result:
def recall(name: String): String = {
val entry = find(name, table(hash(name)))
require(entry != null, "name is not in the book")
entry.number
}The check turns an invalid call into an explicit precondition failure rather than an accidental null dereference or an invented default number. For a valid call, the unique matching entry contains exactly the mapped value, so the stored number is returned and the map is unchanged. Testing membership by calling
isInBook first would traverse the same bucket twice; retaining the found reference avoids that redundant work. New to topics? Read the docs here!