Skip to content

Instantly share code, notes, and snippets.

@cronin101
Last active August 29, 2015 14:17
Show Gist options
  • Save cronin101/e6680e747e7cc8a19651 to your computer and use it in GitHub Desktop.
Save cronin101/e6680e747e7cc8a19651 to your computer and use it in GitHub Desktop.
Reverse Polish Notation calculator
module RPN where
import Data.List
calc :: (Read a, Fractional a) => String -> a
calc = head . foldl processToken [] . words
where
processToken stack@(x:x':xs) token = case token of "/" -> (x' / x):xs
"*" -> (x' * x):xs
"+" -> (x' + x):xs
"-" -> (x' - x):xs
_ -> read token : stack
processToken stack token = read token : stack
main :: IO ()
main = print $ calc "10 4 3 + 2 * -"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment