Last active
August 29, 2015 14:17
-
-
Save cronin101/e6680e747e7cc8a19651 to your computer and use it in GitHub Desktop.
Reverse Polish Notation calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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