# Talk:Toy compression implementations

### From HaskellWiki

Revision as of 13:34, 9 March 2007 by MathematicalOrchid (Talk | contribs)

Much kudos for fixing the underflow error. The new LZW implementation is much smaller, but... how in the name of God does it actually work? o_O MathematicalOrchid 11:36, 9 March 2007 (UTC)

To understand it I rewrote it a bit:

encode_LZW :: (Eq t) => [t] -> [t] -> [Int] encode_LZW alphabet = work (map (:[]) alphabet) where work table [] = [] work table lst = index : work table' rest where (tok, rest) = last . takeWhile ((`elem` table) . fst) . tail $ zip (inits lst) (tails lst) index = fromJust (elemIndex tok table) table' = table ++ [tok'] tok' = tok ++ [head rest]

The idea of the the table, which is the 1st argument to 'work', is that some prefix of the input is already in the table.

(encode_LZW chars) uses 'chars' to make the initial table for the 'work' function by turning the list of characters into a list of length 1 strings.

Thewhere (tok,rst)

- The computes every possible way to splitzip (inits lst) (tails lst)input into a prefix and suffix, in increasing length of prefix.lst
- The function just drops the head because it doesn't want to consider the length 0 prefixtail
- applies the predicatetakeWhileto the prefix. This will always succeed on the length 1 prefix, and may find longer prefixes in the table.(`elem` table)
- The function take the last prefix in the table, which will always be the longest such prefixlast
- is this prefix, andtokis the remaining suffix to process.rest

Wow... a most ingenious (and inefficient) approach! Well, now it makes sense anyway. MathematicalOrchid 13:34, 9 March 2007 (UTC)