Skip to content

Instantly share code, notes, and snippets.

@mrwonko
Last active November 23, 2015 18:04
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/21cf82da822c6dc884ed to your computer and use it in GitHub Desktop.
Save mrwonko/21cf82da822c6dc884ed to your computer and use it in GitHub Desktop.
module Main( main ) where
data PolishElement = PolishPlus | PolishNumber Integer deriving (Show)
polish :: [PolishElement] -> (Integer, [PolishElement])
polish (PolishNumber x : tail) = (x, tail)
polish (PolishPlus : tail) = (x + y, tail'')
where
(x, tail') = polish tail
(y, tail'') = polish tail'
reversePolish :: [PolishElement] -> [Integer] -> [Integer]
reversePolish [] result = result -- when there's no more input, the result is the stack
reversePolish (PolishNumber x : tail) stack = reversePolish tail (x : stack)
reversePolish (PolishPlus : tail) (x: (y: stack)) = reversePolish tail (x + y : stack)
main :: IO ()
main = do
let instructions = [PolishPlus, PolishNumber 10, PolishPlus, PolishNumber 3, PolishNumber 4]
print $ polish instructions
print $ reversePolish (reverse instructions) []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment