Skip to content

Instantly share code, notes, and snippets.

@o-sam-o
Created August 1, 2011 11:20
Show Gist options
  • Save o-sam-o/1117966 to your computer and use it in GitHub Desktop.
Save o-sam-o/1117966 to your computer and use it in GitHub Desktop.
Hacky Attempt At Haskell Reverse Polish Notation
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
@md2perpe
Copy link

md2perpe commented Aug 2, 2011

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

@o-sam-o
Copy link
Author

o-sam-o commented Aug 3, 2011

Great, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment