s LearnSqueak.com

SMALLTALK LAB

Adjacent-Swap Typo Distance in Squeak: Optimal String Alignment

Treat a neighboring-letter swap as one typo. Extend an edit-distance grid in Squeak, then find an example where the shortcut is not the full Damerau–Levenshtein distance.

6 tested checkpointsNative Squeak screenshotsNative evaluation replay

Before you begin

Open a native Squeak Workspace. Each checkpoint is independent. Select the whole example, including its temporary declarations, and choose Print it.

These are native Squeak 6.1 examples. Each checkpoint is independent: open the download as text, copy one complete expression into Workspace and choose Print it. Do not file in the checkpoint collection as a class definition.

Expected values are Smalltalk expressions. The printer may show explicit Symbol markers: #(A B) and #(#A #B) represent the same array of Symbols.

01 - Recognize a pair in reverse order

The misspelling 'teh' differs from 'the' where the final two characters cross. A local test checks that each character matches the other end of the opposing pair. These two-character examples are just the detection rule, not the full distance.

Independent Workspace expression - select all, then Print it
| left right flipped |
flipped := [:s :t | (s first = t second) and: [s second = t first]].
left := 'he'. right := 'eh'.
{flipped value: left value: right. flipped value: left value: 'ha'}

Expected: #(true false)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Recognize a pair in reverse order
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Try 'ab' against 'ba', then 'ab' against 'bc'. Only the first pair crosses.

Download this checkpoint

02 - Give the empty prefixes their own cells

The grid cell for prefix lengths i and j lives at array row i + 1, column j + 1. Going from the empty source to a j-character prefix takes j insertions; going from an i-character source to the empty target takes i deletions. Each row is created separately so the cells do not share storage.

Independent Workspace expression - select all, then Print it
| d |
d := (1 to: 3) collect: [:row | Array new: 4].
0 to: 2 do: [:i | (d at: i + 1) at: 1 put: i].
0 to: 3 do: [:j | (d at: 1) at: j + 1 put: j].
{d at: 1. (d at: 2) at: 1. (d at: 3) at: 1}

Expected: #(#(0 1 2 3) 1 2)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Give the empty prefixes their own cells
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Read the first row as four distances from the empty source. The leftmost column is 0, 1, 2.

Download this checkpoint

03 - Compare the same typo with and without swaps

The deletion, insertion and substitution candidates each come from the neighboring prefix cells. When both prefixes have at least two characters and their last two cross, add one more candidate from prefix lengths i - 2 and j - 2, plus the cost of one swap. Keeping the minimum preserves the ordinary edit as an option. Disable the swap branch and the very same grid computes Levenshtein distance.

Independent Workspace expression - select all, then Print it
| distance |
distance := [:s :t :allowSwap | | d m n |
 m := s size. n := t size.
 d := (1 to: m + 1) collect: [:row | Array new: n + 1].
 0 to: m do: [:i | (d at: i + 1) at: 1 put: i].
 0 to: n do: [:j | (d at: 1) at: j + 1 put: j].
 1 to: m do: [:i |
  1 to: n do: [:j | | cost best |
   cost := (s at: i) = (t at: j) ifTrue: [0] ifFalse: [1].
   best := (((d at: i) at: j + 1) + 1)
    min: (((d at: i + 1) at: j) + 1).
   best := best min: (((d at: i) at: j) + cost).
   (allowSwap and: [i > 1 and: [j > 1]]) ifTrue: [
    ((s at: i) = (t at: j - 1) and:
     [(s at: i - 1) = (t at: j)]) ifTrue: [
      best := best min: (((d at: i - 1) at: j - 1) + 1)]].
   (d at: i + 1) at: j + 1 put: best]].
 (d at: m + 1) at: n + 1].
{distance value: 'teh' value: 'the' value: false.
 distance value: 'teh' value: 'the' value: true}

Expected: #(2 1)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Compare the same typo with and without swaps
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: The penultimate cell references a prefix, not a zero-based character index. Translate i - 2 into array row i - 1.

Download this checkpoint

04 - Combine a local swap with a separate edit

A swap can be followed by an edit to a separate portion of the alignment. The extra s in 'froms' is one insertion on top of swapping o and r; the third example uses two disjoint swaps. The grid chooses the cheapest alignment, not a prescribed order of edits.

Independent Workspace expression - select all, then Print it
| distance |
distance := [:s :t :allowSwap | | d m n |
 m := s size. n := t size.
 d := (1 to: m + 1) collect: [:row | Array new: n + 1].
 0 to: m do: [:i | (d at: i + 1) at: 1 put: i].
 0 to: n do: [:j | (d at: 1) at: j + 1 put: j].
 1 to: m do: [:i |
  1 to: n do: [:j | | cost best |
   cost := (s at: i) = (t at: j) ifTrue: [0] ifFalse: [1].
   best := (((d at: i) at: j + 1) + 1)
    min: (((d at: i + 1) at: j) + 1).
   best := best min: (((d at: i) at: j) + cost).
   (allowSwap and: [i > 1 and: [j > 1]]) ifTrue: [
    ((s at: i) = (t at: j - 1) and:
     [(s at: i - 1) = (t at: j)]) ifTrue: [
      best := best min: (((d at: i - 1) at: j - 1) + 1)]].
   (d at: i + 1) at: j + 1 put: best]].
 (d at: m + 1) at: n + 1].
{distance value: 'form' value: 'from' value: true.
 distance value: 'form' value: 'froms' value: true.
 distance value: 'abcd' value: 'badc' value: true}

Expected: #(1 2 2)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Combine a local swap with a separate edit
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Reverse each pair and evaluate again. The same operation costs apply in either direction.

Download this checkpoint

05 - Check an empty word, a match and a substitution

Empty inputs never enter the nested cell update. Identical characters can advance diagonally at zero cost, while a single different character costs one. These are useful regression tests: a swap optimization should not break the simplest inputs.

Independent Workspace expression - select all, then Print it
| distance |
distance := [:s :t :allowSwap | | d m n |
 m := s size. n := t size.
 d := (1 to: m + 1) collect: [:row | Array new: n + 1].
 0 to: m do: [:i | (d at: i + 1) at: 1 put: i].
 0 to: n do: [:j | (d at: 1) at: j + 1 put: j].
 1 to: m do: [:i |
  1 to: n do: [:j | | cost best |
   cost := (s at: i) = (t at: j) ifTrue: [0] ifFalse: [1].
   best := (((d at: i) at: j + 1) + 1)
    min: (((d at: i + 1) at: j) + 1).
   best := best min: (((d at: i) at: j) + cost).
   (allowSwap and: [i > 1 and: [j > 1]]) ifTrue: [
    ((s at: i) = (t at: j - 1) and:
     [(s at: i - 1) = (t at: j)]) ifTrue: [
      best := best min: (((d at: i - 1) at: j - 1) + 1)]].
   (d at: i + 1) at: j + 1 put: best]].
 (d at: m + 1) at: n + 1].
{distance value: '' value: 'cat' value: true.
 distance value: 'cat' value: '' value: true.
 distance value: 'cat' value: 'cat' value: true.
 distance value: 'cat' value: 'cot' value: true}

Expected: #(3 3 0 1)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Check an empty word, a match and a substitution
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Try 'a' against 'b'. The swap branch must not read a character before the start of either string.

Download this checkpoint

06 - See where the restricted distance differs

Optimal string alignment (OSA), often called restricted Damerau–Levenshtein, cannot realize a path that transposes a pair and then inserts inside that same pair. Unrestricted Damerau–Levenshtein can go CA → AC → ABC in two edits; that is optimal because the lengths differ and an insertion alone cannot reverse C and A. Here the direct OSA score is three, even though the two separate OSA scores add to two.

Independent Workspace expression - select all, then Print it
| distance |
distance := [:s :t :allowSwap | | d m n |
 m := s size. n := t size.
 d := (1 to: m + 1) collect: [:row | Array new: n + 1].
 0 to: m do: [:i | (d at: i + 1) at: 1 put: i].
 0 to: n do: [:j | (d at: 1) at: j + 1 put: j].
 1 to: m do: [:i |
  1 to: n do: [:j | | cost best |
   cost := (s at: i) = (t at: j) ifTrue: [0] ifFalse: [1].
   best := (((d at: i) at: j + 1) + 1)
    min: (((d at: i + 1) at: j) + 1).
   best := best min: (((d at: i) at: j) + cost).
   (allowSwap and: [i > 1 and: [j > 1]]) ifTrue: [
    ((s at: i) = (t at: j - 1) and:
     [(s at: i - 1) = (t at: j)]) ifTrue: [
      best := best min: (((d at: i - 1) at: j - 1) + 1)]].
   (d at: i + 1) at: j + 1 put: best]].
 (d at: m + 1) at: n + 1].
{distance value: 'CA' value: 'AC' value: true.
 distance value: 'AC' value: 'ABC' value: true.
 distance value: 'CA' value: 'ABC' value: true}

Expected: #(1 1 3)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: See where the restricted distance differs
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Use this triple as a reminder not to assume the triangle inequality when choosing a search index for OSA.

Download this checkpoint

Replay the checkpoints

NATIVE SQUEAK CAPTURE
Adjacent-Swap Typo Distance in Squeak: Optimal String Alignment native Workspace replay
Replay of successive native Squeak Workspace evaluations, not an interaction recording. The static checkpoints appear above.

Reason about correctness and limits

This implementation fills (m + 1) × (n + 1) cells, so time and storage are both O(mn) for nonempty strings of lengths m and n. Bound input size before using the full grid to score a large dictionary; if only the score is needed, a rolling three-row version can retain the two-row-back swap dependency.

Character equality here is exact and case-sensitive. Decide whether to normalize case and Unicode before scoring user text. The example operates on Squeak String characters, not grapheme clusters.

The transposition shortcut makes neighboring swaps inexpensive, not arbitrary rearrangements. Use unrestricted Damerau–Levenshtein if editing within a previously transposed pair is part of the intended semantics.

Three practice challenges

Rank an easy typo

Which is closer to 'teh' under OSA, 'the' or 'ten'?

Show solution

They tie at one edit: one swap versus one substitution. Ranking ties requires another signal, such as frequency.

One character cannot swap

What should the solver return for 'a' and 'ba'?

Show solution

One, by inserting b at the beginning. At least two characters are needed in each prefix to consider a swap.

Inspect the finishing move

With swaps enabled, where does the winning swap candidate for 'ab' → 'ba' come from?

Show solution

The cell for two empty prefixes, at row 1 column 1. Its cost is zero, so adding the swap yields one.

Continue learning

Edit Distance | Kmp Search | Palindrome Table

Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.