s LearnSqueak.com

TEXT · SHARED PREFIXES

Prefix tries: build an autocomplete index

Build a native Squeak prefix trie, distinguish words from prefixes, and explore sorted autocomplete results with ten SUnit tests.

8 native experiments10 SUnit testsComplete source

Install and open the native lab

A search box often needs every stored word that starts with a few typed letters. A trie organizes the characters along paths, so cat and car share the c and a nodes instead of repeating that beginning. Unlike the site’s binary search tree, this structure follows characters rather than comparing entire keys. Unlike Huffman’s coding tree, its edges are the original characters, not compressed bits.

  1. Use a copy of Squeak 6.1 with its matching changes and sources files. This is a native-only workshop; these classes are not installed in the SqueakJS playground.
  2. Download prefix-trie.st. Select the file in Squeak’s File List and choose fileIn. Do not paste the entire chunk-format file into a Workspace.
  3. Keep one Workspace open for the numbered commands. Read method definitions in the Browser, not as Workspace expressions. The complete model and view are installed before you start; the steps explain and exercise that source.

Prerequisites: classes and objects, the related foundations lesson, and SUnit basics.

SUnit tests · Complete source kit

Keep the fixed-layout native window at least 980 × 620 pixels. No network, file saving or timers are used by the app. Close the window to clean up; Reset returns the view to its initial experiment.

01 · Start with a root, not a word

An empty trie still has a root node. Each node owns a Dictionary of character-to-child associations and a Boolean terminal flag. A node can exist without ending a word: that distinction is the heart of this lesson. initialize prepares these two independent responsibilities.

LSPrefixNode method · read in Browser
initialize
 super initialize. children := Dictionary new. terminal := false
Same Workspace · select and Do it
view := LSPrefixView open.

Expected: The index is empty, has one node, and returns no suggestions.

Inspect view model in the Inspector. Its children dictionary is empty and terminal is false. The view asks the model for results; it does not maintain a second list of words.

NATIVE SQUEAK CAPTURE
Native Squeak Prefix tries: build an autocomplete index, experiment 1: Start with a root, not a word
Genuine Squeak Morphic window after experiment 1.

02 · Insert cat one character at a time

add: starts at the root, walks the input string, and asks for a child at each character. childFor: uses at:ifAbsentPut: to allocate only a missing child. Once the walk ends, markTerminal records that this path is a complete word.

LSPrefixNode method · read in Browser
add: word
 | node |
 word isString ifFalse: [self error: 'Use a String'].
 node := self.
 word do: [:letter | node := node childFor: letter].
 node markTerminal.
 ^ self
Same Workspace · select and Do it
view next.

Expected: cat appears; the root plus c, a and t make four nodes.

Read childFor: in the Browser too. The block is evaluated only when that character is absent. A separate Dictionary at every node means the same letter can appear at many different positions without a collision.

NATIVE SQUEAK CAPTURE
Native Squeak Prefix tries: build an autocomplete index, experiment 2: Insert cat one character at a time
Genuine Squeak Morphic window after experiment 2.

03 · Reuse the prefix when adding car

The next word walks through existing c and a nodes. Only r is new, so the node count becomes five, not seven. The picture displays complete word paths in rows for readability; repeated letters in those rows are not duplicate stored nodes.

LSPrefixNode method · read in Browser
childFor: letter
 ^ children at: letter ifAbsentPut: [self class new]
Same Workspace · select and Do it
view next.

Expected: car and cat appear in character-sorted order; five nodes exist.

Print view model nodeCount. Then inspect the child at $c and its child at $a. The a node owns r and t children. Dictionary keys here are Characters such as $c, not one-character Strings such as 'c'.

NATIVE SQUEAK CAPTURE
Native Squeak Prefix tries: build an autocomplete index, experiment 3: Reuse the prefix when adding car
Genuine Squeak Morphic window after experiment 3.

04 · Let one word be a prefix of another

Adding cart follows the complete car path and extends it with t. The r node stays terminal. This allows both car and cart to be stored, while ca remains only a prefix. A terminal flag is not equivalent to having no children.

LSPrefixNode method · read in Browser
includes: word
 | node |
 node := self nodeFor: word.
 ^ node notNil and: [node isTerminal]
Same Workspace · select and Do it
view next.

Expected: car, cart and cat are stored; includes: 'car' answers true.

Print view model includes: 'ca'. It answers false even though nodeFor: 'ca' finds a node. Then Print view model includes: 'cart'. It answers true. Word membership requires both an existing path and a terminal endpoint.

NATIVE SQUEAK CAPTURE
Native Squeak Prefix tries: build an autocomplete index, experiment 4: Let one word be a prefix of another
Genuine Squeak Morphic window after experiment 4.

05 · Create an independent branch

dog begins with d, which is absent from the root. It adds three nodes. Recursive traversal visits each sorted child key and extends the prefix string; it emits the prefix only at terminal nodes. This is why the results are deterministic despite Dictionary having no useful display order.

LSPrefixNode method · read in Browser
collectWords: prefix into: result
 terminal ifTrue: [result add: prefix].
 children keys asSortedCollection do: [:letter |
  (children at: letter) collectWords: prefix, letter asString into: result]
Same Workspace · select and Do it
view next.

Expected: car, cart, cat and dog are listed; the node count is nine.

Read the recursive send carefully: the receiver is the child node, while prefix, letter asString creates the text associated with that child. Existing strings are not modified. The result collection belongs to this one query.

NATIVE SQUEAK CAPTURE
Native Squeak Prefix tries: build an autocomplete index, experiment 5: Create an independent branch
Genuine Squeak Morphic window after experiment 5.

06 · Make duplicate insertion harmless

Adding cat again walks an existing path and sets its terminal flag to true again. No extra word or node is created. This model behaves as a set of strings, not a bag of word frequencies. nodeCount recursively counts each stored node exactly once.

LSPrefixNode method · read in Browser
nodeCount
 ^ 1 + ((children values collect: [:child | child nodeCount]) inject: 0 into: [:sum :n | sum + n])
Same Workspace · select and Do it
view next.

Expected: The same four words and nine nodes remain.

Compare with a search ranking application: repeated inputs might need a frequency counter, but that would be a deliberate model extension. Do not infer popularity from node count or insertion order. Add a frequency field and tests before claiming ranked autocomplete.

NATIVE SQUEAK CAPTURE
Native Squeak Prefix tries: build an autocomplete index, experiment 6: Make duplicate insertion harmless
Genuine Squeak Morphic window after experiment 6.

07 · Search from the prefix node

wordsStarting: first walks only the prefix. If it finds that node, it collects terminal paths underneath it. The query 'ca' visits the c/a subtree and returns car, cart and cat, without walking dog’s branch.

LSPrefixNode method · read in Browser
wordsStarting: prefix
 | node result |
 node := self nodeFor: prefix. result := OrderedCollection new.
 node ifNotNil: [node collectWords: prefix into: result].
 ^ result asArray
Same Workspace · select and Do it
view next.

Expected: The ca query returns #('car' 'cart' 'cat').

Print view model wordsStarting: 'ca'. Then Print view model wordsStarting: 'car' and expect #('car' 'cart'). Prefix lookup takes one dictionary lookup per prefix character on the normal path; listing all completions also costs traversal and output work.

NATIVE SQUEAK CAPTURE
Native Squeak Prefix tries: build an autocomplete index, experiment 7: Search from the prefix node
Genuine Squeak Morphic window after experiment 7.

08 · Handle a missing prefix and empty text

nodeFor: returns nil as soon as one character is missing. The public query then returns an empty Array, not an exception. The empty prefix performs no walk, leaving the root as the starting node, so it lists all words.

LSPrefixNode method · read in Browser
nodeFor: prefix
 | node |
 prefix isString ifFalse: [self error: 'Use a String'].
 node := self.
 prefix do: [:letter | node := node childAt: letter. node ifNil: [^ nil]].
 ^ node
Same Workspace · select and Do it
view next.

Expected: The z query returns #(); the stored words remain unchanged.

Print view model wordsStarting: '' to list all four words. The model also permits storing the empty string by marking the root terminal. It is case-sensitive and does not normalize Unicode or combine equivalent spellings. Long recursive paths and unbounded suggestion output need limits in a production service.

NATIVE SQUEAK CAPTURE
Native Squeak Prefix tries: build an autocomplete index, experiment 8: Handle a missing prefix and empty text
Genuine Squeak Morphic window after experiment 8.

Replay the native experiments

NATIVE SQUEAK CAPTURE
Prefix tries: build an autocomplete index before the experiment sequence
Eight genuine native window captures after the scripted lesson commands, not a mouse recording or interpolated animation.

Verify, extend and know the limits

File in the tests first · select and Print it
LSPrefixTest suite run

Expected: 10 tests, 10 passes, 0 failures and 0 errors. File the test source in through the File List before evaluating the suite. Tests were run in Squeak 6.1 build 23976.

Try adding 'cap' through view model add: 'cap', then run view changed. Print view model wordsStarting: 'ca' to see cap join the suggestions; nodeCount increases by one. After step 8 the display still queries z, so that panel stays empty. The stored-word rows do show cap. Add a test first if you extend this set to support deletion: removing a terminal marker and pruning now-unused children are different jobs. This lab has no persistence, fuzzy search, ranking, result limit or network service.

Princeton Algorithms: TrieSET provides background for the underlying idea; this Smalltalk implementation and tutorial are original. Official Squeak documentation covers the environment and language.

Continue with Topological ordering: schedule prerequisites · Affine transforms: move shapes with six numbers.