Skip to content

Instantly share code, notes, and snippets.

@AndrasKovacs
Created March 14, 2015 17:55
Show Gist options
  • Select an option

  • Save AndrasKovacs/fcf9bd63c1eb4b7b75aa to your computer and use it in GitHub Desktop.

Select an option

Save AndrasKovacs/fcf9bd63c1eb4b7b75aa to your computer and use it in GitHub Desktop.
LZW
import Data.Maybe
import Data.Char
import Data.List
dictionary :: [String]
dictionary = [[chr x] | x <- [0..127]]
encode :: String -> [Int]
encode [] = []
encode (x:xs) = go dictionary [x] xs where
elemIndex' w = fromJust . elemIndex w
go dict w [] = [elemIndex' w dict]
go dict w (i:inp) =
maybe
(elemIndex' w dict : go (dict ++ [w']) [i] inp)
(\_ -> go dict w' inp)
(elemIndex w' dict)
where w' = w ++ [i]
decode :: [Int] -> String
decode = go dictionary where
go dict [] = []
go dict [i] = dict !! i
go dict (i:j:js) = out ++ go (dict ++ [out ++ [nxt]]) (j:js)
where out = dict !! i
nxt = case drop j dict of
(c:_):_ -> c
[] -> head out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment