Skip to content

Instantly share code, notes, and snippets.

@jorendorff
Created July 17, 2020 16:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorendorff/c622f69af2456f4717521869ece2093a to your computer and use it in GitHub Desktop.
Save jorendorff/c622f69af2456f4717521869ece2093a to your computer and use it in GitHub Desktop.
data Value = Num Integer | Nil | Cons Value Value
deriving Show
negateVal (Num x) = Num (-x)
negateVal other = other
decodeUnary ('0' : s) = (0, s)
decodeUnary ('1' : s) =
let (n, s') = decodeUnary s in
(n + 1, s')
decodeIntBits acc 0 s = (acc, s)
decodeIntBits acc n ('0' : s) = decodeIntBits (2 * acc) (n - 1) s
decodeIntBits acc n ('1' : s) = decodeIntBits (2 * acc + 1) (n - 1) s
decodeInt :: String -> (Integer, String)
decodeInt s =
let (len, s') = decodeUnary s in
decodeIntBits 0 (4 * len) s'
decode ('0' : '0' : tail) = (Nil, tail)
decode ('0' : '1' : tail) =
let (v, xs) = decodeInt tail in (Num v, xs)
decode ('1' : '0' : tail) =
let (v, xs) = decodeInt tail in (Num (-v), xs)
decode ('1' : '1' : tail) =
let (x, tail') = decode tail in
let (y, tail'') = decode tail' in
(Cons x y, tail'')
main = do
line <- getLine
putStrLn $ show $ decode line
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment