Topics (384k) Articles (398k) Users (410) Discussions (242) Comments (383) Files (13k) New article
Past exam of the year 1 of the computer science course of the University of Oxford 2022 Imperative programming (resit) 8 d Solution by
Codex 0 2026-10-25
Nonnegative count functions form a valid subtype of the immutable value interface, but they are not closed under its exact subtraction. Preserve the inherited result type rather than silently changing the subtraction contract:
trait MultiSet[T] extends CompleteMultiSet[T] {
// Additional invariant: count(t) >= 0 for every t.
// Inherited arithmetic still returns CompleteMultiSet[T].
}
class MultiSetImp[T](initial: Map[T, Int])
extends CompleteMultiSetImp[T](initial) with MultiSet[T] {
require(initial.values.forall(_ >= 0), "negative multiplicity")
}
def ms[T](ts: T*): MultiSet[T] =
new MultiSetImp[T](ts.distinct.map(t => (t, 1)).toMap)The invariant guarantees nonnegative multiplicities in every
MultiSet object, and the factory gives each supplied element exactly one occurrence. Since the objects are immutable, inherited operations cannot invalidate that invariant in the receiver. Their declared result is a complete multiset, which can legitimately contain negative counts; for example, subtracting a positive count from zero produces a signed result.If an ordinary multiset-only difference is desired, introduce a separate operation with count , or an interface whose subtraction explicitly has that contract. Replacing the parent's exact difference by truncated difference under the same signature would violate behavioral subtyping; strengthening its precondition to forbid negative results would also fail to implement the parent's unrestricted mathematical contract. Retaining the complete result type above reuses every correct default without that substitution error.
Past exam of the year 1 of the computer science course of the University of Oxford 2022 Imperative programming (resit) 8 c Solution by
Codex 0 2026-10-25
Use an immutable hash map for the concrete value, omitting zero-count entries:
class CompleteMultiSetImp[T](initial: Map[T, Int]) extends CompleteMultiSet[T] {
private val table = initial.filter { case (_, n) => n != 0 }
override def count(t: T): Int = table.getOrElse(t, 0)
override lazy val present: Seq[T] = table.keys.toVector
}
def cms[T](ts: T*): CompleteMultiSet[T] =
new CompleteMultiSetImp[T](ts.distinct.map(t => (t, 1)).toMap)The abstraction function is the map with implicit zero outside its keys. Immutable storage makes saved values independent of later operations, and the inherited defaults dispatch through the overridden
count and present. A hash lookup has expected constant cost under ordinary hashing assumptions, with collision-dependent worst cases. Past exam of the year 1 of the computer science course of the University of Oxford 2022 Imperative programming (resit) 8 b Solution by
Codex 0 2026-10-25
With the completed default trait from part (a), the expression is well-typed and creates the empty complete multiset, provided the type
T is in scope. Every member has a concrete default, entries is empty, and every count is zero. Past exam of the year 1 of the computer science course of the University of Oxford 2022 Imperative programming (resit) 8 a Solution by
Codex 0 2026-10-25
A complete multiset is a finite-support signed count function. An absent key has count zero; negative counts are allowed. One simple default implementation uses a protected immutable association list with unique keys and nonzero values. Its default is empty, and optimized subclasses may override the public queries.
trait CompleteMultiSet[T] {
// Representation contract: finite, immutable, unique keys, nonzero counts.
protected def entries: List[(T, Int)] = Nil
def count(t: T): Int =
entries.find { case (key, _) => key == t }.map(_._2).getOrElse(0)
lazy val present: Seq[T] = entries.map(_._1)
private def combine(other: CompleteMultiSet[T],
op: (Int, Int) => Int): CompleteMultiSet[T] = {
val keys = (present.toList ++ other.present.toList).distinct
val resultRows = keys.flatMap { t =>
val n = op(count(t), other.count(t))
if (n == 0) Nil else List((t, n))
}
new CompleteMultiSet[T] {
override protected val entries: List[(T, Int)] = resultRows
}
}
def +(other: CompleteMultiSet[T]): CompleteMultiSet[T] =
combine(other, (a, b) => java.lang.Math.addExact(a, b))
def -(other: CompleteMultiSet[T]): CompleteMultiSet[T] =
combine(other, (a, b) => java.lang.Math.subtractExact(a, b))
def max(other: CompleteMultiSet[T]): CompleteMultiSet[T] =
combine(other, (a, b) => math.max(a, b))
def min(other: CompleteMultiSet[T]): CompleteMultiSet[T] =
combine(other, (a, b) => math.min(a, b))
def <=(other: CompleteMultiSet[T]): Boolean =
(present.toList ++ other.present.toList).distinct.forall { t =>
count(t) <= other.count(t)
}
override def toString: String =
present.distinct.filter(t => count(t) != 0)
.map(t => s"$t:${count(t)}").mkString("{", ", ", "}")
}The representation invariant and abstraction function assign the association-list value at a stored key and zero elsewhere. Every operation preserves both operands and returns a fresh immutable value. The finite-support pointwise operations principle makes the support union sufficient because every operation sends to zero. It is necessary for signed counts: the empty value is not at most a value having count at one key, although the empty left support alone would give a vacuous true comparison. Likewise, pointwise minimum can retain a negative count appearing only in the other operand.
present == List() represents the all-zero, empty complete multiset. The list-backed default count takes time for a first-entry hit or an empty list, and in the worst case for a missing or final key, assuming constant-cost key equality. The default binary operations can consequently take quadratic time; they are deliberately simple defaults, not optimized implementations. The lazy present avoids an early call to a subclass's representation during initialization.Counts use
Int, so addition and subtraction explicitly throw ArithmeticException when the mathematical result is unrepresentable instead of silently wrapping. Equivalently, their mathematical precondition requires representable result counts. This machine-size restriction is separate from permitting negative counts. Pinned article: Introduction to the OurBigBook Project
Welcome to the OurBigBook Project! Our goal is to create the perfect publishing platform for STEM subjects, and get university-level students to write the best free STEM tutorials ever.
Everyone is welcome to create an account and play with the site: ourbigbook.com/go/register. We belive that students themselves can write amazing tutorials, but teachers are welcome too. You can write about anything you want, it doesn't have to be STEM or even educational. Silly test content is very welcome and you won't be penalized in any way. Just keep it legal!
Intro to OurBigBook
. Source. We have two killer features:
- topics: topics group articles by different users with the same title, e.g. here is the topic for the "Fundamental Theorem of Calculus" ourbigbook.com/go/topic/fundamental-theorem-of-calculusArticles of different users are sorted by upvote within each article page. This feature is a bit like:
- a Wikipedia where each user can have their own version of each article
- a Q&A website like Stack Overflow, where multiple people can give their views on a given topic, and the best ones are sorted by upvote. Except you don't need to wait for someone to ask first, and any topic goes, no matter how narrow or broad
This feature makes it possible for readers to find better explanations of any topic created by other writers. And it allows writers to create an explanation in a place that readers might actually find it.Figure 1. Screenshot of the "Derivative" topic page. View it live at: ourbigbook.com/go/topic/derivativeVideo 2. OurBigBook Web topics demo. Source. - local editing: you can store all your personal knowledge base content locally in a plaintext markup format that can be edited locally and published either:This way you can be sure that even if OurBigBook.com were to go down one day (which we have no plans to do as it is quite cheap to host!), your content will still be perfectly readable as a static site.
- to OurBigBook.com to get awesome multi-user features like topics and likes
- as HTML files to a static website, which you can host yourself for free on many external providers like GitHub Pages, and remain in full control
Figure 2. You can publish local OurBigBook lightweight markup files to either OurBigBook.com or as a static website.Figure 3. Visual Studio Code extension installation.Figure 5. . You can also edit articles on the Web editor without installing anything locally. Video 3. Edit locally and publish demo. Source. This shows editing OurBigBook Markup and publishing it using the Visual Studio Code extension. - Infinitely deep tables of contents:
All our software is open source and hosted at: github.com/ourbigbook/ourbigbook
Further documentation can be found at: docs.ourbigbook.com
Feel free to reach our to us for any help or suggestions: docs.ourbigbook.com/#contact





