The finishing project
The last lesson is one small tool end to end: a command that reads a text file, counts the words and prints the most frequent ones. It has a pure object that holds the logic, a @main that turns the object into a command, a MUnit suite that specifies it, a formatter configuration, and a run of all three — the shape of a tool a reader can copy for the next one.
The specification
The suite comes first, because it is the contract: four examples, one of which pins the order of two words with the same count. The object it names does not exist yet, which is the point of writing the test first:
WordCountSuite.test.scala
//> using test.dep org.scalameta::munit::1.3.6
class WordCountSuite extends munit.FunSuite:
test("splits on punctuation and case") {
assertEquals(WordCount.words("The fox, the FOX!"), List("the", "fox", "the", "fox"))
}
test("counts each word") {
assertEquals(WordCount.counts("the fox the dog"), Map("the" -> 2, "fox" -> 1, "dog" -> 1))
}
test("orders by count and then by word") {
val ranked = WordCount.top(Map("b" -> 1, "a" -> 1, "c" -> 2), 2)
assertEquals(ranked, List(("c", 2), ("a", 1)))
}
test("the report has one line per word") {
val lines = WordCount.report("the fox the dog", 2).linesIterator.toList
assertEquals(lines, List("the 2", "dog 1"))
}
The tool
WordCount is pure: a string in, a map or a list out, no file and no printing. runWordCount is the thin edge that reads the argument, reads the file and prints the report. Keeping the two apart is what makes the suite above possible without a temporary file:
wordcount.scala
import java.nio.file.{Files, Path}
object WordCount:
def words(text: String): List[String] =
text.toLowerCase.split("[^a-z0-9']+").toList.filter(_.nonEmpty)
def counts(text: String): Map[String, Int] =
words(text).groupBy(identity).view.mapValues(_.size).toMap
def top(counts: Map[String, Int], n: Int): List[(String, Int)] =
counts.toList.sortBy((word, count) => (-count, word)).take(n)
def report(text: String, n: Int): String =
val ranked = top(counts(text), n)
val width = ranked.map(_._1.length).maxOption.getOrElse(0)
ranked.map((word, count) => s"${word.padTo(width, ' ')} $count").mkString("\n")
@main def runWordCount(args: String*): Unit =
args.headOption match
case None => println("usage: wordcount <file> [top]")
case Some(file) =>
val n = args.drop(1).headOption.flatMap(_.toIntOption).getOrElse(5)
println(WordCount.report(Files.readString(Path.of(file)), n))
samples.txt
the quick brown fox
the lazy dog
the fox jumps
The format check and the tests
The configuration is the three lines of the scalafmt lesson, and the check is the one a build would run: it writes nothing and prints one line when every file already matches. scala-cli test compiles the main file and the test file and runs the suite:
.scalafmt.conf
version = 3.11.5
runner.dialect = scala3
maxColumn = 100
scalafmt --check .
All files are formatted with scalafmt :)
scala-cli test --server=false .
Test run WordCountSuite started
WordCountSuite: finished <TIME>
Test run WordCountSuite finished: 0 failed, 0 ignored, 4 total <TIME>
The first argument is the file, and an optional second one is how many words to print. With no argument the tool prints its usage and exits successfully, which is the behaviour a shell expects from a command that was asked for help:
scala-cli run --server=false . -- samples.txt
the 3
fox 2
brown 1
dog 1
jumps 1
scala-cli run --server=false . -- samples.txt 3
the 3
fox 2
brown 1
The output is the ranking the report function promises: by count first, and alphabetically between words with the same count, which is what makes the result stable enough to compare. A tool like this one grows in three directions: a flag parser, a choice of input between a file and standard input, and a test that generates a text and checks that the counts sum to the number of words. Each is one more method and one more test, and the shape stays the same.
Related
- MUnit: the framework the specification is written in.
- scalafmt: the configuration and the check the tool runs.
- Packaging: the jar this tool becomes when it leaves the machine.
- groupBy, sorting and splitting: the transformations the report is built from.
Article author: Arthur Isaev