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 |
Good question. I was keeping it in the same order as it is written. I peeked at the answer and its a lot easier doing it the other way. I plan to attempt it again the correct way.
It's easier and -- above all -- it's more efficient to use the head end.
Later today I could post a solution using the state monad.
I see that you've rewritten the code. Now it's much more legible.
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
Why are you using the tail end of the list as top of the stack instead of the head end?