= Solution
Reject the empty <string> because it has no positive total count to normalize:
``
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
}
``
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> `"aba"` gives masses $2/3$ and $1/3$ 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.
Back to article page