Created
December 17, 2013 16:00
-
-
Save cohama/8007258 to your computer and use it in GitHub Desktop.
すごい Haskell 10 章の逆ポーランド電卓 Maybe を使ったエラー処理をしてる版
This file contains 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.String | |
import Control.Monad | |
import Data.Maybe | |
main :: IO () | |
main = interactEachLines $ (fromMaybe "Error!") . rpn | |
interactEachLines :: (String -> String) -> IO () | |
interactEachLines f = interact $ unlines . (map f) . lines | |
rpn :: String -> Maybe String | |
rpn s = do | |
[ss] <- (foldM rpnOneStep []) $ words s | |
return $ show ss | |
readMaybe :: (Read a) => String -> Maybe a | |
readMaybe s = case reads s of | |
[(x, "")] -> Just x | |
_ -> Nothing | |
rpnOneStep :: [Integer] -> String -> Maybe [Integer] | |
rpnOneStep (x:y:ys) "*" = return $ (y*x):ys | |
rpnOneStep (x:y:ys) "/" = return $ (y `div` x):ys | |
rpnOneStep (x:y:ys) "+" = return $ (y+x):ys | |
rpnOneStep (x:y:ys) "-" = return $ (y-x):ys | |
rpnOneStep (0:y:_:ys) "?" = return $ y:ys | |
rpnOneStep (_:_:z:ys) "?" = return $ z:ys | |
rpnOneStep stack num = liftM (:stack) (readMaybe num) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment