Reject the empty string because it has no positive total count to normalize:The support contains each occurring character once, and a character absent from the string gets mass zero. The occurrence counts sum to the nonzero string length, proving normalization. For a separate example, the string
final class DistFromString(s: String) extends FiniteDist[Char] {
require(s.nonEmpty)
private val frequencies =
s.foldLeft(Map.empty[Char, Int]) { (counts, c) =>
counts.updated(c, counts.getOrElse(c, 0) + 1)
}
def getDom: List[Char] = s.toList.distinct
def getProb(c: Char): Double =
frequencies.getOrElse(c, 0).toDouble / s.length.toDouble
}"aba" gives masses and to its two characters. The interpretation follows Scala's Char elements, so it counts UTF-16 code units rather than imposing a separate Unicode-code-point representation. The Double results approximate the corresponding rational probabilities.Choose the following explicit policy: an edit of pounds recomputes euros; an edit of euros recomputes pounds; an edit of the rate keeps pounds fixed and recomputes euros. Amounts may be any finite signed values, while a rate must be finite and strictly positive. Invalid text, non-finite numbers and overflowing conversions leave the last accepted state intact and restore its display.The numeric state has the invariant and ; euros are derived instead of being stored independently. A proposal is validated before either stored value changes. The update flag prevents a synchronous programmatic display update from recursively committing another edit. Currency amounts display two decimal places, while the rate retains its parsed precision; display rounding is not repeatedly fed back into the numeric model.
import scala.swing._
import scala.swing.event.EditDone
import scala.util.Try
object CurrencyConverter extends SimpleSwingApplication {
def top: Frame = new MainFrame {
title = "Currency converter"
val pounds = new TextField(8)
val euros = new TextField(8)
val rate = new TextField(8)
private var poundsValue = 10.0
private var rateValue = 1.15
private var updating = false
private def finite(x: Double): Boolean =
java.lang.Double.isFinite(x)
private def money(x: Double): String =
java.lang.String.format(java.util.Locale.ROOT, "%.2f",
java.lang.Double.valueOf(x))
private def showValues(): Unit = {
updating = true
try {
pounds.text = money(poundsValue)
euros.text = money(poundsValue * rateValue)
rate.text = java.lang.Double.toString(rateValue)
} finally updating = false
}
private def commit(field: TextField): Unit = {
if (!updating) {
val proposed = Try(field.text.trim.toDouble).toOption
.filter(finite).map { value =>
if (field eq pounds) (value, rateValue)
else if (field eq euros) (value / rateValue, rateValue)
else (poundsValue, value)
}
proposed.foreach { case (newPounds, newRate) =>
if (finite(newPounds) && finite(newRate) && newRate > 0.0 &&
finite(newPounds * newRate)) {
poundsValue = newPounds
rateValue = newRate
}
}
showValues()
}
}
contents = new FlowPanel {
contents += new Label("Pounds")
contents += pounds
contents += new Label("Euros")
contents += euros
contents += new Label("Euros per pound")
contents += rate
}
listenTo(pounds, euros, rate)
reactions += {
case EditDone(source) if source eq pounds => commit(pounds)
case EditDone(source) if source eq euros => commit(euros)
case EditDone(source) if source eq rate => commit(rate)
}
showValues()
}
}Locale.ROOT ensures that formatted decimal points match the input parser.The code handles the
EditDone events used by the paper rather than trying to parse every intermediate keystroke. It uses Scala 2 style and Java 8-or-newer numeric helpers. No Scala compiler or Swing runtime execution was available in the checking environment; the state transitions were checked independently, and the API usage was compared with the supplied contract and official Scala/Swing documentation.[ref]Java 8 Double API documentation. isFinite(double), parseDouble(String) and toString(double)
Worked solutions for the held Oxford preliminary examination of 14 June 2023. Source release: released examination PDF. All eight questions and all 42 answerable leaves are addressed below, without reproducing question statements. The three printed sections are retained as context within the question hierarchy.
Code uses the Scala 2 syntax of the paper. Array inputs described as sorted are assumed nondecreasing and stable during an operation. Unless explicitly discussing machine behavior, mathematical proofs state their arithmetic assumptions. In particular, the printed routines in Question 2 have genuine fixed-width arithmetic limitations, which are analyzed rather than silently attributed exact-integer behavior. Implementations below handle empty structures and document their sentinels, capacity bounds and invalid-input behavior.
Path-dependent type 2026-10-24
A type selected through a stable object path, allowing an object's nested type to retain its association with that instance. In Scala,
editor.Snapshot can differ from otherEditor.Snapshot even when both objects have the same outer class. This is useful for originator-specific mementos and other values that must not be mixed across owners.[ref]Scala 2.13 types specification. Paths and type selections
Programming language polymorphism 2026-10-24
Using an interface or definition across multiple types. Subtype polymorphism dispatches through a common supertype; parametric polymorphism uses a type parameter uniformly; method overloading selects among signatures by static types in languages such as Scala. These mechanisms should be distinguished from genetic or materials-science polymorphism.
Scala 2.12 BigInt API documentation 2026-10-24
Official archived documentation: www.scala-lang.org/api/2.12.8/scala/math/BigInt.html
Relevant locators: remainder
%, gcd, isValidInt and toInt. Scala's BigInt provides arbitrary-precision integer arithmetic; representability must be checked before conversion to a fixed-width integer because narrowing conversion need not preserve the exact value. The archived API corroborates the operations used in the solution without claiming a particular installed Oxford course library version. Scala 2.12 iterator API documentation 2026-10-24
Archived official Scala API. Relevant locators: the abstract members
hasNext and next, the exhaustion exception, and the consuming nature of iterators. The associated historical overview is Collections for Scala 2.8–2.12: Iterators. Scala 2.13 iterator API documentation 2026-10-24
Scala Swing 2026-10-24
A Scala wrapper library for Java Swing interfaces. Its event system uses publishers, reactors and partial-function reactions. The examination supplies the central subscription and publication contract; archived and current official documentation corroborate that design without identifying an exact installed course library build.
Scala Swing event-system documentation 2026-10-24
Official source: github.com/scala/scala-swing
Relevant locator: Official library README, About Scala-swing: Publisher/Reactor, listenTo, reactions; archived Reactor API at www.scala-lang.org/api/2.12.7/scala-swing/scala/swing/Reactor.html corroborates listenTo, deafTo and reactions. These corroborate the supplied source contract, not a verified 2021 course dependency version.
Short-circuit evaluation 2026-10-24
Evaluation that skips a later operand once an earlier operand determines the result. In Scala,
p != null && p.field == x does not dereference p when it is null, and i < n && a(i) != x avoids an out-of-range access at . The order is part of the safety argument: exchanging these operands can preserve a Boolean formula in mathematics while changing whether a program raises an exception. Stackable trait modification 2026-10-24
A Scala trait can intercept a method, call the next implementation through
super, and add behavior before or after it. abstract override marks such an implementation as requiring an appropriate concrete method later in the class linearization. A character-counting plugin can update its cached counts only after a successful underlying document edit, preserving its additional representation invariant without changing the edit's abstract result. Tail recursion 2026-10-24
Recursion in which the recursive call is the last operation required to obtain the current call's result. An accumulator can encode the state that would otherwise be updated by a loop. A suitable compiler can replace the call by a jump, avoiding growing call stack storage. In Scala, a tail-recursion annotation requests a check that the recursive method is eligible for this transformation.
Trait 2026-10-24
A reusable type and collection of members that can be composed into a class in object-oriented programming. In Scala, a trait can declare required members and provide concrete implementations. Several traits can contribute mixin behavior to one class, subject to linearization and member-conflict rules.