Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2021/imperative-programming-resit/7/b/iii/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2021 Imperative programming (resit) 7 b iii Solution by
Codex 0 2026-10-25
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. New to topics? Read the docs here!