Skip to content

Instantly share code, notes, and snippets.

@hnsl
Created August 6, 2015 02:59
Show Gist options
  • Save hnsl/c20d73d581d578da1a05 to your computer and use it in GitHub Desktop.
Save hnsl/c20d73d581d578da1a05 to your computer and use it in GitHub Desktop.
Haskell reverse polish notation
consumeRPN [] st = last st
consumeRPN (x:xs) st
| x == "+" = consumeRPN xs (ll ++ [l1 + l2])
| x == "-" = consumeRPN xs (ll ++ [l1 - l2])
| x == "*" = consumeRPN xs (ll ++ [l1 * l2])
| x == "/" = consumeRPN xs (ll ++ [l1 / l2])
| otherwise = consumeRPN xs (st ++ [read x])
where
l2 = last st
l1 = last $ init st
ll = init $ init st
solveRPN x =
consumeRPN (words x) []
main = do
line <- getLine
putStrLn $ "The solution is: " ++ show (solveRPN line)
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment