Skip to content

Instantly share code, notes, and snippets.

@mrwonko
Last active November 30, 2015 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrwonko/46e094d308d691bb7f39 to your computer and use it in GitHub Desktop.
Save mrwonko/46e094d308d691bb7f39 to your computer and use it in GitHub Desktop.
module Main where
main :: IO ()
main = interact $ \ input ->
let (serializedTree:encodedMessages) = lines input
tree = deserialize serializedTree
messages = map (decode tree) encodedMessages in
unlines messages
data PrefixTree = Leaf Char | Node PrefixTree PrefixTree
deserialize :: String -> PrefixTree
deserialize string = deserialize' (reverse string) []
where
deserialize' [] (root:_) = root
deserialize' ('*':string) (l:r:stack) = deserialize' string ((Node l r):stack)
deserialize' (char:string) stack = deserialize' string ((Leaf char):stack)
decode :: PrefixTree -> String -> String
decode tree string = decode' tree string
where
decode' (Leaf char) string = char:(decode' tree string)
decode' (Node l r) (char:string) = decode' (if char == '0' then l else r) string
decode' _ [] = []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment