Spelling Suggestion on the JVM #2: Implementing Norvig’s Algo in Java
This tutorial project implements a basic spelling suggestion service. The motivation is didactic: becoming familiar with “better java” languages around a simple but instructional example. Ease of implementation outranks optimal performance so readers can focus on the JVM languages as such. Examples and new concepts are introduced in Java 9 first so they’re immediately understandable to the experienced Java programmer. Crucially, the Java implementation is accompanied by equivalent (but idiomatic) implementations in today’s most relevant alternative JVM languages: Kotlin, Scala and Xtend. Code is available at Spellbound_’s Github repo.
This second post illustrates how to implement Norvig’s spelling corrector in Java 9 following a functional style.
The next post Implementing Norvig’s Algo in Kotlin presents an idiomatic Kotlin implementation of Norvig’s spelling corrector.
The previous post (Norvig’s Approach to Spelling Correction) discusses Norvig’s approach to generating typo corrections.
If you haven’t already, taking a cursory look at Norvig’s Python script may be useful in digesting this Java implementation.
Everything having to do with spelling correction revolves around a curated list of valid words we refer to as the the dictionary.
In our dictionary implementation we accompany every word with an integer rank indicating how frequently the word is used in relation to all other words. The lower the rank, the more frequently used the word is. Thus, for instance, the has rank
1 while triose has rank
The dictionary declaration is:
Transforming the typo into a set of word splits
In order to hold word splits we define an inner data class WordSplit as follows:
Note: no getter/setter or other boilerplate needed. This is an immutable data class visible to the
SpellingCorrectorand its tests only.
Armed with this definition we can now formulate the rather trivial implementation of
split() method takes a string (the typo) and returns all possible pairs of word splits. Thus, for our beloved but misspelt hero dlbert we get the equivalent of:
By the way, all four edit implementations take a
List<WordSplit> argument rather than a simple
List<String>. All of them return a
IntStream.rangeClosed(int startInclude, int endInclusive) generates an
IntStream. In our example this means all integers between
6. Because we want to generate a
Stream<String> (not an
IntStream) we apply
boxed() to the range
IntStream so it becomes a
Subsequently, each successive integer value is used as a substring index for splitting the word into a pair of
right fragments. This
Stream<String> is finally collected as a
Edits #1: deletes
Generating all possible deletes for a word is also quite simple:
Here, we stream over the input
List<WordPair> selecting only the ones where
right is not empty (which is equivalent to all splits but the very first one). Next, we concatenate each word split into a string formed by the
left part followed by the "tail" of the
Given the typo waly
deletes() yields the equivalent of:
Edits #2: inserts
Inserts are the opposite of deletes and while their implementation is still quite simple:
In this method our friend
LETTERS makes its first appearance. Again for the sake of simplicity we deal only with lowercase ASCII characters. There is no support for diacritics (though its implementation is simple anyways).
LETTERS is statically defined as:
Splitting on an empty regex results in each string’s character becoming a 1-char string on its own right.
For our canine friend dgbert
inserts() would yield the equivalent of:
Edits #3: transposes
Implementing transposition requires the
right fragment to have more than one character in length, which makes sense as transposing involves not one but two letters:
For our heroine alice
transposes() yields the equivalent of:
Edits #4: replaces
replace edit is very prolific requiring the substitution of every letter in the typo for each letter in the alphabet. It also requires the right segment not to be empty (as something needs to be replaced). Because we're nesting the processing of each letter inside the processing of every typo character we need to apply
flatMap rathen than
For our little friend asok
replaces() yields the equivalent of:
edit1: Applying All Edits Hoping for Valid Words
To cover all our bases we need to run and then concatenate all four edits. For this we define a static list of edits as follows:
This is an instance of a common functional pattern where code is treated as data. Here, we have a list of functions mapping from
Stream<String> (which is, precisely, the type of transformation our four edits implement). In this context Java method references shine as they, effectively, provide us with a data-centric view of executable code.
We make use of this list of functions to implement
edit1 as follows:
Because the four edits are independent of one another we can parallelize their execution. This is transparently handled by Java by means of the
Also, because each edit returns a nested
Stream<String> we need to use
flatMap instead of
What is this
pack() method surrounding everything?
As it happens,
edit1 is not yet done when all edits have been concatenated.
edit1 generates all possible edits we need to screen them for duplicates as well as for actual appearance in the dictionary. We also need to order the resulting valid words so the most frequently used ones are shown first. This is all achieved as follows:
As customary, results are collected into a
List<String> suitable for displaying suggestions to the user.
Despite generating lots of possible suggestions,
edit1 can fail to yield a dictionary word In this case we assume our typo stems not from one but two transcription mistakes.
edit2 is quite simply defined in terms of
edit1 as follows:
Here we see our friend
pack() in action once again to ensure word uniqueness, validity and order.
Again, we use
flatMap because we generate candidate suggestions from the nested
Stream of results.
Putting it All Together
We’re almost there now. Our workhorse method
getCorrections() method looks as follows:
Note we return
Optional<List<String>> rather than a plain
We need to express the absence of suggestions not because the typo doesn’t match anything known but, on the contrary, because it was handed a valid dictionary word for which the notion of suggestion simply doesn’t make sense. In this scenario we return
It could be argued that returning
List.empty() would be appropriate to indicate such inapplicability.
In reality, however, it is perfectly possible for a word absent from the dictionary (.i.e, a typo) not to resemble any known word. In this case we still need to make it explicit we’re dealing with a typo. Thus,
List.empty() is not semantically equivalent to
We there yet?
Yes, we are ;-)
The complete Java implementation has 300+ lines including comments and empty lines. Its neutron star-dense incarnation comes down to 120 lines.
Compare that to Norvig’s feat of packing the whole thing in 44 lines of Python code!
Java’s verbosity is precisely one of the most important reason alternative JVM languages have emerged. In the next 3 posts we’ll see how the Kotlyn, Scala and Xtend versions improve upon Java in terms of economy of expression and clarity of intent.
Next in our plate: Implementing Norvig’s Algo in Kotlin