PREFIX CODES · LOSSLESS COMPRESSION
Build a Huffman coding laboratory
Merge weighted trees, derive binary prefix codes and test a lossless encode/decode round trip in native Squeak Smalltalk.
Install the native coding laboratory
Build a native Squeak 6.1 laboratory for Huffman coding: count characters, merge a forest into one tree, derive prefix codes, and verify a lossless round trip. This is a source-guided workshop, not a prebuilt web simulation or a production compressor.
- Use a disposable copy of a Squeak 6.1 learning image.
- Download huffman-coding.st below. In Squeak’s File List, select it and choose fileIn. Do not paste the complete chunk-format file into a Workspace.
- Open a Workspace and run the step-1 launcher with Do it. Keep this Workspace so the variable view continues to refer to the same window.
- Read the method excerpts in the System Browser. They are definitions from the complete source, not separate expressions to paste into a Workspace.
- Run the eight experiments in order. To restart, close the window and run the launcher again.
Prerequisites: classes, collections, blocks and the idea of a tree. Compare the binary heap lesson to understand another way to select the smallest values.
Complete native source (.st) · SUnit tests (.st) · Workshop kit
Native Squeak only; this application is not installed in the site’s SqueakJS image. The app performs no network calls or filesystem writes. Its fixed drawing layout is intended for the small fixtures shown here; use a window around 1020 × 670 pixels.
01 · Count symbols before choosing bit codes
ABRACADABRA has 11 characters but only five distinct symbols. A occurs five times; B and R twice each; C and D once each. Huffman coding uses these frequencies to assign short codes to common symbols. It does not encode the spelling of a word as one dictionary entry.
- File in the complete application before using the launcher. Keep the same Workspace for all eight experiments.
- Each node is an Array: weight, label, left child, right child. A leaf has nil children.
- SortedCollection uses weight first and label second. The label tie-breaker makes this example reproducible; another valid tie rule can produce different codes.
load: aString
| counts |
text := aString copy. codes := Dictionary new. counts := Dictionary new.
text do: [:ch | counts at: ch put: (counts at: ch ifAbsent: [0]) + 1].
forest := SortedCollection sortBlock: [:a :b |
a first = b first ifTrue: [a second <= b second] ifFalse: [a first < b first]].
counts keysAndValuesDo: [:ch :count | forest add: {count. ch asString. nil. nil}].
note := 'Count each symbol; merge the two lightest trees.'.
forest size = 1 ifTrue: [self assign: forest first prefix: '']view := LSHuffmanView open.Expected: Five one-node trees appear, in weight order: C:1, D:1, B:2, R:2, A:5. These leaves already account for all 11 input characters.

02 · Merge the two smallest weights
Remove the two lightest trees and join them under a new parent. The parent weight is their sum. C:1 and D:1 become a weight-2 subtree. Put it back into the sorted forest so it can compete with every other tree in the next step.
- Compare the first two removals with the old roots. Do not simply merge adjacent original letters forever.
- The parent retains references to both child arrays; combining weights does not discard the leaves.
- The method answers true when a merge happened, and false when fewer than two roots remain.
merge
| left right parent |
forest size < 2 ifTrue: [^ false].
left := forest removeFirst. right := forest removeFirst.
parent := {left first + right first. left second, right second. left. right}.
forest add: parent.
note := 'Merged ', left second, ' + ', right second, ' = ', parent first printString.
forest size = 1 ifTrue: [self assign: forest first prefix: ''].
^ trueview merge.Expected: Four roots remain: B:2, CD:2, R:2 and A:5. The edge to the left child is labeled 0; the edge to the right child is labeled 1.

03 · Reinsert a subtree, then compare again
The new CD subtree has the same weight as B and R. Our deterministic label ordering chooses B and CD next. Their weight-4 parent is reinserted after R:2 and before A:5. Internal nodes participate in the same ordering as leaves.
- Count the frequency sum under each root. The total is still 11.
- forest answers an Array snapshot of the root collection, not a deep copy of every node. Treat it as read-only teaching data.
- For a large implementation, compare a heap-based priority queue. This small lesson uses SortedCollection for clarity, not a promise of optimal insertion complexity.
forest
^ forest asArrayview merge.Expected: Three roots remain: R:2, BCD:4 and A:5. The BCD subtree has three leaves, but its priority is total frequency 4, not leaf count 3.

04 · Keep the entire partial tree
R:2 and BCD:4 are now the two smallest roots. Their parent has weight 6. A:5 becomes the lightest remaining tree. Notice that the most common symbol has not yet acquired a long path: the greedy merges have grouped rarer symbols first.
- The Finish tree button repeatedly calls merge until it answers false. Here we deliberately use one merge so you can inspect the intermediate state.
- Calling encode before completion raises an error instead of returning an incomplete bit string.
- For n distinct symbols, exactly n-1 merges produce the final tree when n is greater than zero.
finish
[self merge] whileTrue.
^ selfview merge.Expected: Two roots remain: A:5 and RBCD:6. No final code table is shown yet, because the root-to-leaf paths are still incomplete.

05 · Turn root-to-leaf paths into codes
The final merge combines weights 5 and 6. Recursively visit the tree, appending 0 on a left edge and 1 on a right edge. Store the prefix only at a leaf. A complete leaf code cannot be the prefix of another leaf code, so code boundaries can be recovered without separators.
- Read assign:prefix: in the Browser. The accumulated prefix belongs to a path, not to a frequency number.
- These codes depend on the stated tie rule. Different left/right choices or tie order can still be correct.
- No symbol is stored at an internal node. This is the property that prevents ambiguity while decoding.
assign: node prefix: prefix
(node at: 3) isNil
ifTrue: [codes at: node second first put: (prefix isEmpty ifTrue: ['0'] ifFalse: [prefix])]
ifFalse: [self assign: (node at: 3) prefix: prefix, '0'.
self assign: (node at: 4) prefix: prefix, '1']view merge.Expected: The root weight is 11. Codes are A=0, R=10, B=110, C=1110 and D=1111. The frequent A needs one bit; the rare C and D need four each.

06 · Encode and decode with the same tree
Encoding replaces each original character with its code. Decoding walks from the root for each bit and emits a character whenever it reaches a leaf, then restarts at the root. The decoder rejects non-binary input and a final path that stops inside the tree.
- Use Print it on this expression if you want the returned text displayed in the Workspace; Do it evaluates it without inserting the answer.
- Against a fixed 3-bit code for five symbols, the payload is 23 instead of 33 bits. Against 11 ASCII bytes, it is 23 instead of 88 bits. Neither comparison includes tree/codebook overhead.
- The model returns a String of characters 0 and 1. It does not pack bits into bytes or create a compressed file, so the returned object itself is not a storage saving.
decode: bits
| root node |
forest size > 1 ifTrue: [self error: 'Finish the tree first'].
(bits allSatisfy: [:ch | ch = $0 or: [ch = $1]]) ifFalse: [self error: 'Only 0 and 1 are allowed'].
forest isEmpty ifTrue: [bits isEmpty ifFalse: [self error: 'No tree']. ^ ''].
root := forest first.
(root at: 3) isNil ifTrue: [
(bits allSatisfy: [:ch | ch = $0]) ifFalse: [self error: 'Single-symbol code is 0'].
^ String new: bits size withAll: root second first].
node := root.
^ String streamContents: [:stream |
bits do: [:bit |
node := node at: (bit = $0 ifTrue: [3] ifFalse: [4]).
(node at: 3) isNil ifTrue: [stream nextPut: node second first. node := root]].
node == root ifFalse: [self error: 'Incomplete final code']]view model decode: view model encode.Expected: The expression answers ABRACADABRA. The view shows payload 01101001110011110110100, exactly 23 bits. This step leaves the same tree visible.

07 · Try a different frequency distribution
Changing the source requires rebuilding the frequency table, forest and codes. The alternate fixture MISSISSIPPI contains M once, I four times, S four times and P twice. Its tree has a different shape. The codebook is part of the decoding context: old codes must not be reused with a new tree.
- The Try MISSISSIPPI button calls load: followed by finish, then asks Morphic to redraw.
- The page is a fixed-fixture visual laboratory. The model can process other strings, but long text or many symbols can exceed this simple drawing layout.
- Huffman coding is lossless for the characters supplied here. It is not encryption and offers no secrecy or corruption detection.
encode
forest size > 1 ifTrue: [self error: 'Finish the tree first'].
^ String streamContents: [:stream | text do: [:ch | stream nextPutAll: (codes at: ch)]]view alternate.Expected: The native window shows MISSISSIPPI with 21 payload bits and a successful round trip. Its root weight is again 11, but the code table differs from ABRACADABRA.

08 · Handle one symbol and test the edge cases
With only one distinct symbol, the tree has no edges. A pure empty path would not record the number of occurrences, so this implementation explicitly uses code 0 for that symbol. Empty input produces an empty payload and empty decoded string. These conventions are part of the format, not universal Huffman requirements.
- File in huffman-coding-tests.st after the application, then Print it: LSHuffmanTest suite run.
- Tests cover frequencies, first merge, root weight, exact codes and payload, prefix freedom, empty and single-symbol inputs, reset, unfinished trees, malformed bits and seven round-trip fixtures.
- A general file format must store or reconstruct the tree, define character encoding, frame the bit count, pack bytes and handle damaged data. This educational app intentionally does not implement those layers.
view model load: 'AAAA'.
view changed.Expected: The sole leaf A has weight 4, code 0 and payload 0000. Decoding restores four As. The included test suite passes 12 test methods with no failures or errors.

Watch the forest become a code tree

Test it, then design a real format
LSHuffmanTest suite runExpected: 12 tests pass, with zero failures and errors. The supplied decoder checks syntax and incomplete paths, but a different valid bit string can still decode to incorrect text. Add a checksum if you need corruption detection. Checkpoints and screenshots demonstrate selected inputs; tests are not a proof for every possible string.
The greedy choice minimizes the weighted path length among binary prefix codes for the given positive frequencies. It is not a guarantee of the best possible compressor: repeated patterns, context models, headers and tiny files change the practical result. This teaching version uses a sorted collection, so do not assign it a heap-based O(n log n) construction bound without examining collection costs.
Try extending the model to calculate weighted code length, replace the sorted collection with a heap, or pack the payload into a ByteArray while preserving its exact bit length. Keep these changes separate from the view and test empty/single-symbol cases again.
SUnit testing · Compare a binary search tree · Official Squeak documentation · Princeton Algorithms: data compression