s LearnSqueak.com

SMALLTALK LAB

LZW: build a dictionary while compressing text

Grow phrases from a tiny alphabet, emit integer codes, reconstruct the same dictionary, and explain the decoder’s surprising self-reference case with native Squeak traces.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Use native Squeak 6.1. You need strings, Dictionary, blocks and OrderedCollection. Paste each entire checkpoint into Workspace, select it and choose Print it. Every checkpoint is independent. This deliberately small LZW variant begins with A = 1 and B = 2, accepts only those uppercase characters, and limits the dictionary to 256 entries. It teaches phrase coding, not the GIF or TIFF file formats.

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.

01 - Agree on the initial dictionary

Encoder and decoder must agree on the alphabet and numbering before exchanging codes. Store strings as keys: the one-character string A is not the Character $A.

Independent Workspace expression - select all, then Print it
| dictionary |
dictionary := Dictionary new.
dictionary at: 'A' put: 1; at: 'B' put: 2.
{dictionary at: 'A'. dictionary at: 'B'. dictionary includesKey: 'AB'}

Expected: #(1 2 false)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Agree on the initial dictionary
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Changing initial numbering on only one side silently changes what a code means.

Download this checkpoint

02 - Emit the known phrase, learn the longer phrase

When AB is missing, emit the code for the known phrase A, add AB as code 3, and retain B for the next attempt. The emitted code refers to the old phrase, not the new dictionary entry.

Independent Workspace expression - select all, then Print it
| dictionary phrase joined emitted |
dictionary := Dictionary new.
dictionary at: 'A' put: 1; at: 'B' put: 2.
phrase := 'A'. joined := phrase, 'B'.
emitted := dictionary at: phrase.
dictionary at: joined put: 3. phrase := 'B'.
{emitted. dictionary at: 'AB'. phrase}

Expected: {1. 3. 'B'}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Emit the known phrase, learn the longer phrase
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The decoder can learn AB from the previous phrase A and the first letter of the next phrase B.

Download this checkpoint

03 - Keep extending a known phrase

Once AB exists, seeing AB does not immediately emit it. The encoder keeps extending until the next extension fails, or until input ends. This greedy rule reuses increasingly long phrases.

Independent Workspace expression - select all, then Print it
| dictionary phrase nextPhrase |
dictionary := Dictionary new.
dictionary at: 'A' put: 1; at: 'B' put: 2; at: 'AB' put: 3.
phrase := 'A'. nextPhrase := phrase, 'B'.
(dictionary includesKey: nextPhrase) ifTrue: [phrase := nextPhrase].
{phrase. dictionary includesKey: phrase, 'A'}

Expected: {'AB'. false}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Keep extending a known phrase
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The next missing extension ABA would receive a new code; AB is the phrase emitted at that point.

Download this checkpoint

04 - Encode the complete message

The loop emits a code only on a missing extension. It then starts a new phrase at the current character. At end of input, flush the remaining phrase. For ABABABA the learned phrases are AB, BA and ABA, and the output is four integer codes.

Independent Workspace expression - select all, then Print it
| encode |
encode := [:text | | dictionary next phrase joined output |
 dictionary := Dictionary new.
 dictionary at: 'A' put: 1; at: 'B' put: 2.
 next := 3. phrase := ''. output := OrderedCollection new.
 text do: [:character |
  ('AB' includes: character) ifFalse: [Error signal: 'Use only A and B'].
  joined := phrase, character asString.
  (dictionary includesKey: joined)
   ifTrue: [phrase := joined]
   ifFalse: [
    output add: (dictionary at: phrase).
    next > 256 ifTrue: [Error signal: 'Dictionary capacity reached'].
    dictionary at: joined put: next. next := next + 1.
    phrase := character asString]].
 phrase isEmpty ifFalse: [output add: (dictionary at: phrase)].
 output asArray].
encode value: 'ABABABA'

Expected: #(1 2 3 5)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Encode the complete message
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Remove the final flush experimentally: the last ABA disappears from the output. The empty phrase is never emitted.

Download this checkpoint

05 - Handle empty input and repeated letters

An empty input yields an empty code array. A single letter needs one final flush. Repeated letters rapidly create longer phrases; AAA becomes A followed by AA.

Independent Workspace expression - select all, then Print it
| encode |
encode := [:text | | dictionary next phrase joined output |
 dictionary := Dictionary new.
 dictionary at: 'A' put: 1; at: 'B' put: 2.
 next := 3. phrase := ''. output := OrderedCollection new.
 text do: [:character |
  ('AB' includes: character) ifFalse: [Error signal: 'Use only A and B'].
  joined := phrase, character asString.
  (dictionary includesKey: joined)
   ifTrue: [phrase := joined]
   ifFalse: [
    output add: (dictionary at: phrase).
    next > 256 ifTrue: [Error signal: 'Dictionary capacity reached'].
    dictionary at: joined put: next. next := next + 1.
    phrase := character asString]].
 phrase isEmpty ifFalse: [output add: (dictionary at: phrase)].
 output asArray].
{encode value: ''. encode value: 'A'. encode value: 'AAA'}

Expected: #(#() #(1) #(1 3))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Handle empty input and repeated letters
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try AA: the result is #(1 1), because the new AA entry is learned only after emitting the first A.

Download this checkpoint

06 - Resolve the decoder’s one legal unknown code

Normally a code already exists. But when the code equals the next dictionary index, the encoder has just reused previous + its own first character. The decoder can reconstruct that phrase before inserting it. No other unknown code is valid.

Independent Workspace expression - select all, then Print it
| previous next number entry |
previous := 'AB'. next := 5. number := 5.
entry := number = next
 ifTrue: [previous, previous first asString]
 ifFalse: [Error signal: 'Unknown code'].
entry

Expected: 'ABA'

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Resolve the decoder’s one legal unknown code
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: In #(1 2 3 5), the decoder has entries A, B, AB and BA when code 5 arrives. Previous is AB, so the missing entry must be ABA.

Download this checkpoint

07 - Decode and verify round trips

For each decoded phrase after the first, learn previous + first character of current. This is exactly the encoder’s dictionary, reconstructed one step later. The special next-index case closes that gap. The tests compare complete strings, not just their lengths.

Independent Workspace expression - select all, then Print it
| encode decode |
encode := [:text | | dictionary next phrase joined output |
 dictionary := Dictionary new.
 dictionary at: 'A' put: 1; at: 'B' put: 2.
 next := 3. phrase := ''. output := OrderedCollection new.
 text do: [:character |
  ('AB' includes: character) ifFalse: [Error signal: 'Use only A and B'].
  joined := phrase, character asString.
  (dictionary includesKey: joined)
   ifTrue: [phrase := joined]
   ifFalse: [
    output add: (dictionary at: phrase).
    next > 256 ifTrue: [Error signal: 'Dictionary capacity reached'].
    dictionary at: joined put: next. next := next + 1.
    phrase := character asString]].
 phrase isEmpty ifFalse: [output add: (dictionary at: phrase)].
 output asArray].
decode := [:codes | | dictionary next previous entry output |
 dictionary := Dictionary new.
 dictionary at: 1 put: 'A'; at: 2 put: 'B'.
 next := 3. previous := nil. output := WriteStream on: String new.
 codes do: [:number |
  (number isInteger and: [number > 0])
   ifFalse: [Error signal: 'Use positive integer codes'].
  entry := dictionary at: number ifAbsent: [
   (previous notNil and: [number = next])
    ifTrue: [previous, previous first asString]
    ifFalse: [Error signal: 'Unknown code']].
  output nextPutAll: entry.
  previous notNil ifTrue: [
   next > 256 ifTrue: [Error signal: 'Dictionary capacity reached'].
   dictionary at: next put: previous, entry first asString.
   next := next + 1].
  previous := entry].
 output contents].
{decode value: #(1 2 3 5).
 #('' 'A' 'B' 'AAA' 'ABABABA' 'BAABAAB')
  collect: [:text | (decode value: (encode value: text)) = text]}

Expected: {'ABABABA'. #(true true true true true true)}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Decode and verify round trips
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try a longer mixture of A and B. The dictionaries reset for every call, so each returned array is a separate message.

Download this checkpoint

08 - Reject unsupported symbols and impossible codes

The first code must already be in the initial dictionary: no previous phrase exists yet. Later, a missing code is allowed only if it is exactly next. Positive-integer checks exclude fractions and zero. Capacity errors stop this bounded teaching codec rather than silently wrapping codes.

Independent Workspace expression - select all, then Print it
| encode decode badText badFirst badLater badType |
encode := [:text | | dictionary next phrase joined output |
 dictionary := Dictionary new.
 dictionary at: 'A' put: 1; at: 'B' put: 2.
 next := 3. phrase := ''. output := OrderedCollection new.
 text do: [:character |
  ('AB' includes: character) ifFalse: [Error signal: 'Use only A and B'].
  joined := phrase, character asString.
  (dictionary includesKey: joined)
   ifTrue: [phrase := joined]
   ifFalse: [
    output add: (dictionary at: phrase).
    next > 256 ifTrue: [Error signal: 'Dictionary capacity reached'].
    dictionary at: joined put: next. next := next + 1.
    phrase := character asString]].
 phrase isEmpty ifFalse: [output add: (dictionary at: phrase)].
 output asArray].
decode := [:codes | | dictionary next previous entry output |
 dictionary := Dictionary new.
 dictionary at: 1 put: 'A'; at: 2 put: 'B'.
 next := 3. previous := nil. output := WriteStream on: String new.
 codes do: [:number |
  (number isInteger and: [number > 0])
   ifFalse: [Error signal: 'Use positive integer codes'].
  entry := dictionary at: number ifAbsent: [
   (previous notNil and: [number = next])
    ifTrue: [previous, previous first asString]
    ifFalse: [Error signal: 'Unknown code']].
  output nextPutAll: entry.
  previous notNil ifTrue: [
   next > 256 ifTrue: [Error signal: 'Dictionary capacity reached'].
   dictionary at: next put: previous, entry first asString.
   next := next + 1].
  previous := entry].
 output contents].
badText := [encode value: 'AC'. false]
 on: Error do: [:e | e messageText = 'Use only A and B'].
badFirst := [decode value: #(3). false]
 on: Error do: [:e | e messageText = 'Unknown code'].
badLater := [decode value: #(1 4). false]
 on: Error do: [:e | e messageText = 'Unknown code'].
badType := [decode value: #(1 1.5). false]
 on: Error do: [:e | e messageText = 'Use positive integer codes'].
{badText. badFirst. badLater. badType. decode value: #()}

Expected: {true. true. true. true. ''}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Reject unsupported symbols and impossible codes
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: A dictionary lookup failure is not permission to invent any phrase. The next-index exception is narrow and requires a previous phrase.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
LZW: build a dictionary while compressing text native visual trace
Replay of actual Morphic window captures at successive computed stages; not mouse footage.

Download the visual experiment. Select the entire expression and Do it. Change stage := 0. to another supported stage, close the previous window, and run again. The GIF replays those native states. This example needs native Squeak; no new browser playground compatibility is claimed.

Reason about correctness and limits

This is a pedagogical LZW variant with a two-character alphabet, one-based codes and no reset or end markers. It is not a GIF/TIFF-compatible stream. Both sides must use the same alphabet, numbering, capacity and reset convention.

Four codes instead of seven characters does not prove byte compression. Real formats pack codes into bits and carry framing. For this binary alphabet, seven original symbols can be represented in seven bits; storing four Smalltalk Integers can cost far more memory.

The code intentionally rejects growth past 256 dictionary entries. Production variants can clear, freeze or reset dictionaries, but that policy must be identical in both encoder and decoder. These blocks abort and return no partial result on an error.

String concatenation copies characters, and dictionary keys retain complete phrases. This transparent implementation is not a linear-time or compact-memory codec. Streaming output does not eliminate dictionary storage. Untrusted compressed input also needs input/output length limits, which this lesson does not supply.

Unlike run-length encoding, repeated phrases need not be runs of identical symbols. Unlike Huffman coding, this example learns a phrase dictionary online instead of building a frequency tree. It performs no encryption and carries no integrity checksum.

Three practice challenges

Challenge 1: trace ABA

Predict the codes and the first two learned phrases for ABA.

Show solution

The encoder emits #(1 2 1). It learns AB = 3 and BA = 4. The final A is flushed; it does not add another dictionary entry.

Challenge 2: decode self-reference twice

Decode #(1 3 4). Why are both later codes legal?

Show solution

Code 1 gives A. Code 3 equals next and gives AA; add AA = 3. Code 4 again equals next and gives AAA; add AAA = 4. The output is AAAAAA. Each new phrase is previous plus its first character.

Challenge 3: expand the alphabet

What must change to admit C while keeping both sides synchronized?

Show solution

Initialize the encoder with C = 3 and decoder with 3 = C, start next at 4 on both sides, and change the encoder alphabet check to ABC. Recompute all old expected codes: initial numbering changes learned phrase codes. Capacity 256 still counts initial and learned entries together.

Continue learning

Run Length | Huffman Coding | Prefix Trie

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