s LearnSqueak.com

SMALLTALK LAB

Aho–Corasick in Squeak: Find Many Patterns in One Pass

Find he, she, and hers without starting the search over for each word. Build a shared prefix tree, teach it where to fall back, and report overlapping matches with one-based positions.

6 tested checkpointsNative Squeak screenshotsNative evaluation replay

Before you begin

Open a Squeak 6.1 Workspace. Select each complete checkpoint, including its temporary declarations, and choose Print it. The examples search literal, case-sensitive, nonempty patterns rather than whole words or regular expressions.

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 display equivalent Smalltalk literals with different spaces or delimiters.

01 - Build a trie from shared prefixes

A trie has one node for each distinct prefix and one root for the empty string. This short implementation names each state by its full prefix. For he, she, and hers the states are '', h, he, her, hers, s, sh, and she: eight states in all. her is a valid state even though it is not a complete pattern. shers is not a prefix of any of our patterns.

Independent Workspace expression - select all, then Print it
| patterns prefixes |
patterns := #('he' 'she' 'hers').
prefixes := Set with: ''.
patterns do: [:word |
  1 to: word size do: [:i |
    prefixes add: (word copyFrom: 1 to: i)]].
{prefixes size. prefixes includes: 'her'.
 prefixes includes: 'hers'. prefixes includes: 'shers'}

Expected: #(8 true true false)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Build a trie from shared prefixes
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Count the empty root as a state. If you add hero, only the new prefix hero is needed.

Download this checkpoint

02 - Link each state to its longest usable suffix

When a state cannot extend, discard characters from the left until the remaining suffix is a trie prefix. Stop at the first match because longer candidates are checked first. A failure link is always shorter than its own nonempty state. Notice that hers can fall back to s, which may start another pattern later.

Independent Workspace expression - select all, then Print it
| patterns prefixes failure |
patterns := #('he' 'she' 'hers').
prefixes := Set with: ''.
patterns do: [:word |
  1 to: word size do: [:i |
    prefixes add: (word copyFrom: 1 to: i)]].
failure := Dictionary new.
failure at: '' put: ''.
prefixes do: [:word | | suffix |
  word isEmpty ifFalse: [
    suffix := word.
    [suffix := suffix size <= 1
        ifTrue: [''] ifFalse: [suffix copyFrom: 2 to: suffix size].
     prefixes includes: suffix] whileFalse.
    failure at: word put: suffix]].
{failure at: 'she'. failure at: 'sh'. failure at: 'hers'}

Expected: #('he' 'h' 's')

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Link each state to its longest usable suffix
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Follow the chain from she by hand: she → he → the empty root.

Download this checkpoint

03 - Keep the pattern at the state and any suffix matches

Outputs answer a different question from failure links: which complete patterns end right here? Visit states from shortest to longest so every failure target already has an output list. Put the state's own match first, then append the outputs inherited through its failure link. The state she inherits he, even if the next character never forces a fallback.

Independent Workspace expression - select all, then Print it
| patterns prefixes failure outputs |
patterns := #('he' 'she' 'hers').
prefixes := Set with: ''.
patterns do: [:word |
  1 to: word size do: [:i |
    prefixes add: (word copyFrom: 1 to: i)]].
failure := Dictionary new.
failure at: '' put: ''.
prefixes do: [:word | | suffix |
  word isEmpty ifFalse: [
    suffix := word.
    [suffix := suffix size <= 1
        ifTrue: [''] ifFalse: [suffix copyFrom: 2 to: suffix size].
     prefixes includes: suffix] whileFalse.
    failure at: word put: suffix]].
outputs := Dictionary new.
outputs at: '' put: #().
(prefixes asSortedCollection: [:a :b | a size <= b size])
  do: [:word | | own |
    word isEmpty ifFalse: [
      own := (patterns includes: word) ifTrue: [{word}] ifFalse: [#()].
      outputs at: word put: own , (outputs at: (failure at: word))]].
{outputs at: 'her'. outputs at: 'she'. outputs at: 'hers'}

Expected: {#(). #('she' 'he'). #('hers')}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Keep the pattern at the state and any suffix matches
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: The trie state her is not a pattern and its failure target is the root, so her emits nothing.

Download this checkpoint

04 - Retry the same character after a failed edge

Try the current state plus the new character. sher is not a state, so follow she → he and try the very same r on he, giving her. Do not consume r until the attempt succeeds or reaches the root without a match. If x has no extension even at the root, return to the root.

Independent Workspace expression - select all, then Print it
| patterns prefixes failure advance |
patterns := #('he' 'she' 'hers').
prefixes := Set with: ''.
patterns do: [:word |
  1 to: word size do: [:i |
    prefixes add: (word copyFrom: 1 to: i)]].
failure := Dictionary new.
failure at: '' put: ''.
prefixes do: [:word | | suffix |
  word isEmpty ifFalse: [
    suffix := word.
    [suffix := suffix size <= 1
        ifTrue: [''] ifFalse: [suffix copyFrom: 2 to: suffix size].
     prefixes includes: suffix] whileFalse.
    failure at: word put: suffix]].
advance := [:state :character | | next base |
  base := state.
  next := base , (String with: character).
  [(prefixes includes: next) not and: [base notEmpty]] whileTrue: [
    base := failure at: base.
    next := base , (String with: character)].
  (prefixes includes: next) ifTrue: [next] ifFalse: ['']].
{advance value: 'sh' value: $e.
 advance value: 'she' value: $r.
 advance value: 'her' value: $x}

Expected: #('she' 'her' '')

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Retry the same character after a failed edge
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Try r from she and you get her rather than the empty root. A plain trie with no fallback would miss that extension.

Download this checkpoint

05 - Scan the text and report every overlapping match

Each record contains the pattern, its one-based start, and its inclusive end. When the scanner reads the e at position 4, two patterns end there. Later, hers ends at position 6; that match overlaps he and she. The start is the end minus the pattern length plus one. The source index only moves forward; fallback changes the state, not the source index.

Independent Workspace expression - select all, then Print it
| patterns prefixes failure outputs advance scan |
patterns := #('he' 'she' 'hers').
prefixes := Set with: ''.
patterns do: [:word |
  1 to: word size do: [:i |
    prefixes add: (word copyFrom: 1 to: i)]].
failure := Dictionary new.
failure at: '' put: ''.
prefixes do: [:word | | suffix |
  word isEmpty ifFalse: [
    suffix := word.
    [suffix := suffix size <= 1
        ifTrue: [''] ifFalse: [suffix copyFrom: 2 to: suffix size].
     prefixes includes: suffix] whileFalse.
    failure at: word put: suffix]].
outputs := Dictionary new.
outputs at: '' put: #().
(prefixes asSortedCollection: [:a :b | a size <= b size])
  do: [:word | | own |
    word isEmpty ifFalse: [
      own := (patterns includes: word) ifTrue: [{word}] ifFalse: [#()].
      outputs at: word put: own , (outputs at: (failure at: word))]].
advance := [:state :character | | next base |
  base := state.
  next := base , (String with: character).
  [(prefixes includes: next) not and: [base notEmpty]] whileTrue: [
    base := failure at: base.
    next := base , (String with: character)].
  (prefixes includes: next) ifTrue: [next] ifFalse: ['']].
scan := [:source | | state hits |
  state := ''. hits := OrderedCollection new.
  1 to: source size do: [:end |
    state := advance value: state value: (source at: end).
    (outputs at: state) do: [:word |
      hits add: {word. end - word size + 1. end}]].
  hits asArray].
scan value: 'ushers'

Expected: {{'she'. 2. 4}. {'he'. 3. 4}. {'hers'. 3. 6}}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Scan the text and report every overlapping match
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Circle positions 2–4, 3–4, and 3–6 on paper. They should spell she, he, and hers.

Download this checkpoint

06 - Stress-test repeated characters and reset between searches

Four one-letter hits, three two-letter hits, and two three-letter hits make nine. The result order is by ending position, with the longest match first among hits ending together. Each scan starts from the root, even if it reuses the same prepared dictionaries. Case matters: uppercase A and lowercase a are different characters.

Independent Workspace expression - select all, then Print it
| patterns prefixes failure outputs advance scan |
patterns := #('a' 'aa' 'aaa').
prefixes := Set with: ''.
patterns do: [:word |
  1 to: word size do: [:i |
    prefixes add: (word copyFrom: 1 to: i)]].
failure := Dictionary new.
failure at: '' put: ''.
prefixes do: [:word | | suffix |
  word isEmpty ifFalse: [
    suffix := word.
    [suffix := suffix size <= 1
        ifTrue: [''] ifFalse: [suffix copyFrom: 2 to: suffix size].
     prefixes includes: suffix] whileFalse.
    failure at: word put: suffix]].
outputs := Dictionary new.
outputs at: '' put: #().
(prefixes asSortedCollection: [:a :b | a size <= b size])
  do: [:word | | own |
    word isEmpty ifFalse: [
      own := (patterns includes: word) ifTrue: [{word}] ifFalse: [#()].
      outputs at: word put: own , (outputs at: (failure at: word))]].
advance := [:state :character | | next base |
  base := state.
  next := base , (String with: character).
  [(prefixes includes: next) not and: [base notEmpty]] whileTrue: [
    base := failure at: base.
    next := base , (String with: character)].
  (prefixes includes: next) ifTrue: [next] ifFalse: ['']].
scan := [:source | | state hits |
  state := ''. hits := OrderedCollection new.
  1 to: source size do: [:end |
    state := advance value: state value: (source at: end).
    (outputs at: state) do: [:word |
      hits add: {word. end - word size + 1. end}]].
  hits asArray].
{(scan value: 'aaaa') size.
 (scan value: 'aaaa') last.
 scan value: 'AAAA'. scan value: ''}

Expected: {9. {'a'. 4. 4}. #(). #()}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Stress-test repeated characters and reset between searches
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Try aaaaa. You should get 5 + 4 + 3 = 12 matches; if you get fewer, check the failure and output steps.

Download this checkpoint

Replay the checkpoints

NATIVE SQUEAK CAPTURE
Aho–Corasick in Squeak: Find Many Patterns in One Pass native Workspace replay
Replay of successive native Squeak Workspace evaluations, not an interaction recording. The static checkpoints appear above.

Reason about correctness and limits

A plain trie stores shared beginnings. Failure links preserve eligible suffixes when a continuation is missing, and cached outputs report all matches that end at the current character. The fallback idea is related to KMP, which tracks progress through one pattern.

With constant-time transitions, a conventional Aho–Corasick automaton scans n characters and emits z matches in O(n + z) time. This teaching version allocates and hashes strings when checking edges, tries suffix strings during setup, and copies inherited output lists. Its setup, memory, and scan costs therefore depend on pattern lengths and shared suffixes too. A practical version can use integer node IDs, character-keyed child maps, a breadth-first failure-link pass, and output links rather than copied lists.

Use distinct nonempty patterns and be explicit about overlap policy. An empty pattern would require a separate rule about matching between characters. These examples find literal substrings, not just whole words; they do not normalize case or Unicode. Record coordinates refer to the exact Squeak string scanned.

Three practice challenges

Find two endings at once

With the original patterns, scan 'she'. Which records appear?

Show solution

{'she'. 1. 3} then {'he'. 2. 3}. Both are outputs of the state she.

Add another literal

Add the pattern 'her' to the original set, rebuild the dictionaries, and predict its record in 'ushers'.

Show solution

The new record is {'her'. 3. 5}. The state her already existed; it now has an output of its own.

Reuse the dictionary without reusing the cursor

Search 'sh' and then 'e' with two separate calls. Why are both outputs empty, and how would you detect 'she' across a chunk boundary?

Show solution

Separate calls reset to the root, so neither string completes a pattern. A streaming scanner must carry the state and running text offset into the next chunk.

Continue learning

Prefix Trie | Kmp Search | State Machines

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