Created
August 1, 2011 11:20
-
-
Save o-sam-o/1117966 to your computer and use it in GitHub Desktop.
Hacky Attempt At Haskell Reverse Polish Notation
This file contains hidden or 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
solveRPN :: String -> Double | |
solveRPN [] = 0 | |
solveRPN s = head $ foldl solveRPN' [] $ words s | |
solveRPN' :: [Double] -> String -> [Double] | |
solveRPN' (x2:x1:stack) "+" = (x1 + x2):stack | |
solveRPN' (x2:x1:stack) "-" = (x1 - x2):stack | |
solveRPN' (x2:x1:stack) "*" = (x1 * x2):stack | |
solveRPN' stack num = (read num):stack |
Here's a solution using the State monad:
import Control.Monad.State
solveRPN :: String -> Double
solveRPN s = head $ execState (sequence $ map handle $ words s) []
handle :: String -> State [Double] ()
handle "+" = handleBinOp (+)
handle "-" = handleBinOp (-)
handle "*" = handleBinOp (*)
handle s = push (read s)
handleBinOp :: (Double -> Double -> Double) -> State [Double] ()
handleBinOp op = do
x1 <- pop
x2 <- pop
push (op x2 x1)
push :: Double -> State [Double] ()
push x = do
stack <- get
put (x : stack)
pop :: State [Double] Double
pop = do
(x : stack) <- get
put stack
return x
Great, thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I see that you've rewritten the code. Now it's much more legible.