Skip to content

Instantly share code, notes, and snippets.

@monzou
Created July 8, 2012 06:35
Show Gist options
  • Save monzou/3069673 to your computer and use it in GitHub Desktop.
Save monzou/3069673 to your computer and use it in GitHub Desktop.
import Data.List
import Control.Monad
readMaybe :: (Read a) => String -> Maybe a
readMaybe st = case reads st of [(x, "")] -> Just x
_ -> Nothing
foldingFunction :: [Double] -> String -> Maybe [Double]
foldingFunction (x:y:ys) "*" = return ((y * x):ys)
foldingFunction (x:y:ys) "+" = return ((y + x):ys)
foldingFunction (x:y:ys) "-" = return ((y - x):ys)
foldingFunction xs numberString = liftM (:xs) (readMaybe numberString) -- liftM = fmap
solveRPN :: String -> Maybe Double
solveRPN st = do
[result] <- foldM foldingFunction [] (words st)
return result
main = do
print $ solveRPN "1 2 * 4 +" -- Just 6
print $ solveRPN "1 2 * 4" -- Nothing
print $ solveRPN "1 8 foo" -- Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment