Created
July 8, 2012 06:35
-
-
Save monzou/3069673 to your computer and use it in GitHub Desktop.
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
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