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.
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.
- 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.
- 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.
- 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.
initialize
super initialize. children := Dictionary new. terminal := falseview := 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.

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.
add: word
| node |
word isString ifFalse: [self error: 'Use a String'].
node := self.
word do: [:letter | node := node childFor: letter].
node markTerminal.
^ selfview 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.

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.
childFor: letter
^ children at: letter ifAbsentPut: [self class new]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'.

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.
includes: word
| node |
node := self nodeFor: word.
^ node notNil and: [node isTerminal]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.

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.
collectWords: prefix into: result
terminal ifTrue: [result add: prefix].
children keys asSortedCollection do: [:letter |
(children at: letter) collectWords: prefix, letter asString into: result]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.

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.
nodeCount
^ 1 + ((children values collect: [:child | child nodeCount]) inject: 0 into: [:sum :n | sum + n])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.

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.
wordsStarting: prefix
| node result |
node := self nodeFor: prefix. result := OrderedCollection new.
node ifNotNil: [node collectWords: prefix into: result].
^ result asArrayview 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.

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.
nodeFor: prefix
| node |
prefix isString ifFalse: [self error: 'Use a String'].
node := self.
prefix do: [:letter | node := node childAt: letter. node ifNil: [^ nil]].
^ nodeview 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.

Replay the native experiments

Verify, extend and know the limits
LSPrefixTest suite runExpected: 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.