リハビリ

「Web+DB vol.66 きっちりわかるアルゴリズム」の「埋め込み性的辞書による圧縮アルゴリズム」をHaskell

module Main where

type Dict = [(String, String)]

dict :: Dict
dict = [ ("http", "'")
       , (".jp", "|")
       , ("www", ">")
       , (".co", "<")
       , ("html", "^")
       ]

replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace [] _ _ = []
replace s find repl =
    if take (length find) s == find
        then repl ++ (replace (drop (length find) s) find repl)
        else [head s] ++ (replace (tail s) find repl)

compressWithDict :: Dict -> String -> String
compressWithDict [] s = s
compressWithDict ((find, repl):rest) s = compressWithDict rest $ replace s find repl

decompressWithDict :: Dict -> String -> String
decompressWithDict d = compressWithDict dict'
    where dict' = [ (y,x) | (x,y) <- d ]

compress :: String -> String
compress = compressWithDict dict

decompress :: String ->String
decompress = decompressWithDict dict