TEXT · DYNAMIC PROGRAMMING
Edit distance: compare words with dynamic programming
Build a Levenshtein distance table in Squeak Smalltalk, explain its one-based indexes, rank spelling candidates, and verify it against a tiny independent oracle.
Before you start
A misspelled search term may share neither an exact word nor a complete prefix with an indexed word. Instead of asking whether two strings are identical, this workshop counts how many single-character edits separate them. This is a different job from the prefix trie: a trie follows exact character paths, while edit distance compares alternative alignments.
Use a copy of native Squeak 6.1. Download edit-distance.st and choose fileIn in Squeak’s File List. It installs one class, LSEditDistance, in LearnSqueak-EditDistance. Do not paste this chunk-format file into a Workspace. The method definitions below are for reading in the Browser; the shorter checkpoint expressions are for selecting and printing in a Workspace.
No extra package, network connection, timer or persistent data file is used by the model. The class remains in the image unless you remove it or discard your image changes. These classes are not preinstalled in the SqueakJS playground. Review classes, collections and blocks if these are new.
Download the complete source and verification kit. Keep the visual window at least 960 × 650; close each old window before opening another state.
01 · Choose the allowed edits
We allow insertion, deletion and substitution, each with cost one. Keeping an already equal character costs zero. The distance is the cheapest total, not the number of positions that differ. That distinction matters when a character is inserted near the beginning: many later positions shift, but only one edit was needed.
distanceFrom: source to: target
^ (self tableFrom: source to: target) last lastLSEditDistance distanceFrom: 'cat' to: 'cat'Expected: 0
Start with the smallest sanity check: the same word has distance zero. The method is a class-side method. In the Browser, select LSEditDistance, then class, then calculating. distanceFrom:to: asks the table method for its bottom-right entry; the larger method does the work. Nothing modifies either input string.

02 · Reserve the empty prefixes
The first row and first column describe comparisons with empty text. To turn an empty string into cat requires three insertions. In the opposite direction, three deletions remove all three letters. This gives a boundary for every later cell, including the case where both inputs are empty.
tableFrom: source to: target
| rows columns table cost deletion insertion substitution |
rows := source size + 1.
columns := target size + 1.
table := (1 to: rows) collect: [:r | Array new: columns].
1 to: rows do: [:r | (table at: r) at: 1 put: r - 1].
1 to: columns do: [:c | (table at: 1) at: c put: c - 1].{LSEditDistance distanceFrom: '' to: 'cat'.
LSEditDistance distanceFrom: 'cat' to: ''.
LSEditDistance distanceFrom: '' to: ''}Expected: #(3 3 0)
Mathematically we label prefix lengths from zero. Squeak Arrays start at one, so prefix length i is stored at position i + 1. There is no access at position zero. The outer array contains rows; each row is a separately allocated Array. Repeating the same mutable row object would alias all rows and silently corrupt the table.

03 · Evaluate the three neighboring choices
For any interior cell, compare three ways to finish an alignment. Above plus one deletes the last source character. Left plus one inserts the last target character. Diagonal plus zero or one keeps or replaces the last character. Choose the smallest cost. This accounts for every possible final edit without committing to a greedy local replacement.
2 to: rows do: [:r |
2 to: columns do: [:c |
cost := (source at: r - 1) = (target at: c - 1)
ifTrue: [0] ifFalse: [1].
deletion := ((table at: r - 1) at: c) + 1.
insertion := ((table at: r) at: c - 1) + 1.
substitution := ((table at: r - 1) at: c - 1) + cost.
(table at: r) at: c
put: ((deletion min: insertion) min: substitution)]].
^ table{LSEditDistance distanceFrom: 'cat' to: 'cut'.
LSEditDistance distanceFrom: 'cat' to: 'cart'.
LSEditDistance distanceFrom: 'cart' to: 'cat'}Expected: #(1 1 1)
The three checkpoint pairs each require exactly one edit. Read the nested min: sends in the method: parentheses make the intended comparison explicit. The row loop begins at two because row one already represents the empty source prefix. The character comparison reads source at: r - 1 and target at: c - 1, compensating for that extra boundary row and column.

04 · Read the table as prefix questions
The table for cat and cut has four rows and four columns, not three by three. Row one asks about an empty source prefix, row two about c, row three about ca, and row four about cat. Columns similarly describe empty text, c, cu and cut. Every cell answers a complete smaller question.
LSEditDistance tableFrom: 'cat' to: 'cut'Expected: #(#(0 1 2 3) #(1 0 1 2) #(2 1 1 2) #(3 2 2 1))
The value at row three, column three is one: ca can become cu by replacing a. The final diagonal step compares t with t, so it adds zero and the bottom-right stays one. Rows are filled top to bottom, and cells left to right. Above, left and diagonal have therefore already been computed. This evaluation order is the dynamic-programming idea, not a Squeak-specific trick.

05 · Follow a longer transformation
For kitten and sitting the answer is three. One possible route replaces k with s, replaces e with i, then inserts g. It is an explanation of the returned distance, not a path reconstructed by this program. The model currently returns costs only, and multiple optimal edit sequences can exist.
LSEditDistance distanceFrom: 'kitten' to: 'sitting'Expected: 3
Use the native table replay below to inspect the six source prefixes. A green row shows the currently revealed source prefix; question marks hide rows not yet revealed. The renderer calculates the complete table first and reveals it one row at a time. That display is honest about its purpose: it illustrates dependency order rather than measuring execution time.

Replay the prefix table

Download the visual expression. Open it as text and select all → Do it after filing in the model. Change stage := 0. to a value from 0 through 6 to reproduce a frame. Green marks the revealed source-prefix row. At stage six, read 3 in the bottom-right cell. Close the window to remove the drawing.
06 · Keep case sensitivity deliberate
Reversing the two strings preserves this unit-cost distance: each insertion can be reversed by a deletion and each replacement can be reversed by a replacement. The table layout changes when source and target swap, but the final minimum does not. This is a useful property to test, not a reason to omit boundary cases.
{LSEditDistance distanceFrom: 'sitting' to: 'kitten'.
LSEditDistance distanceFrom: 'Cat' to: 'cat'}Expected: #(3 1)
Cat and cat are one edit apart because the comparison is case sensitive. If a particular application wants case-insensitive matching, explicitly send asLowercase to both strings before calling the model and document that policy. Do not silently remove accents or punctuation. This lesson works on Squeak Character elements, not user-perceived grapheme clusters; composed and decomposed text may need normalization before comparison.

07 · Separate substitutions from transpositions
Swapping two neighboring letters is not an allowed one-step operation in this model. ab to ba costs two, for example by replacing both positions. A distance that treats the adjacent swap as one operation is a different specification, often discussed as a Damerau–Levenshtein variant.
LSEditDistance distanceFrom: 'ab' to: 'ba'Expected: 2
This test prevents a tempting but incorrect shortcut: counting matching letters without respecting their order. Anagrams are not identical strings. If you extend the recurrence with transpositions, add a separate set of tests and explain which variant you implemented. Do not change this expected result while continuing to call the model ordinary unit-cost Levenshtein distance.

08 · Rank candidates without pretending to know meaning
A small spelling-candidate list becomes an application of the model. Each row stores a numeric distance followed by its word. Sort by cost first, then alphabetically to make ties deterministic. The resulting order is useful for inspection, but distance alone does not know vocabulary, context, frequency or the user’s intent.
| candidates ranked |
candidates := #('cat' 'cut' 'cart' 'dog').
ranked := candidates collect: [:word |
{LSEditDistance distanceFrom: 'cot' to: word. word}].
ranked := ranked asSortedCollection: [:a :b |
a first = b first
ifTrue: [a second <= b second]
ifFalse: [a first < b first]].
ranked asArrayExpected: #(#(1 'cat') #(1 'cut') #(2 'cart') #(2 'dog'))
Both cat and cut cost one edit from cot. cart and dog both cost two. The alphabetical tie rule is explicit in the block rather than an accidental side effect of collection order. For a large dictionary this naive approach builds a table for every candidate. Start with a measured workload, then consider length-difference filtering, bounded-distance algorithms or a suitable index instead of claiming this small demo is a production search engine.

Verify beyond the happy path
Download the assertion script, open it as text, select all and Print it after installing the model. The final value must be 233; any mismatch raises an Error before that value is reached.
The bundle repeats the eight exact checkpoints, then compares the model with an independently written recursive definition on all 225 ordered pairs of binary strings of length zero through three. That is 233 assertions, not 233 SUnit methods. The small recursive oracle is deliberately inefficient and only suitable for these tiny inputs. It is kept in the test script, not used by the production model.
Additional investigations: print the same table twice and confirm equal results; change the inputs and inspect their new dimensions; check that distance is at least the absolute length difference. When testing a future weighted-cost variant, revisit symmetry rather than inheriting assumptions from this one.
Understand the cost and choose the next experiment
For source length m and target length n, this implementation computes m × n interior cells and stores (m + 1) × (n + 1) entries. Its running time and table memory are quadratic in the two string lengths when both are nonempty. Boundaries still take linear work for an empty input. It is a teaching model: very long strings can allocate a large table or keep the UI busy.
If you only need the final number, retain the previous and current rows instead of the full table. Swapping references after each row reduces auxiliary storage to a pair of rows; use the shorter string as the column dimension. If you want an edit script, the full table is useful for tracing backward through choices. Define tie-breaking, return explicit operations, and test that applying them produces the target. These are extensions, not features claimed by this download.
The source deliberately exposes tableFrom:to: for inspection. Its returned nested arrays are mutable, but every call allocates a new table. The model performs no type validation; supply String inputs as shown. A production API should decide what to reject, normalize or coerce before allocating the grid.
Continue with SUnit to package the checks as test methods, measurement before optimization, or document search to compare distance-based ranking with token indexing.
Sources and reproducibility
The algorithmic definition and complexity were checked against the NIST Dictionary of Algorithms and Data Structures entry and the University of Waterloo string-distance notes. These sources support the insertion/deletion/substitution model and dynamic-programming cost; this Smalltalk implementation, examples and prose are original.
Native verification used Squeak 6.1 build 23976 on 26 October 2026. The kit contains the exact model, checkpoints, assertion script, visual expression, verification report and a Python runner requiring your own Squeak VM and image paths. It runs in a temporary image copy and exits without saving the image. Screenshots show real Squeak Morphic and Workspace rendering; no browser facsimile was used.