Add error handling

This commit is contained in:
Rnhmjoj 2015-02-26 23:12:56 +01:00
parent da8897b238
commit 516a0173f7

18
RPN.hs
View File

@ -1,6 +1,8 @@
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE ViewPatterns #-}
import Data.List import Data.List
import Text.Read
import Control.Monad
main :: IO () main :: IO ()
main = io (show . rpn) main = io (show . rpn)
@ -8,12 +10,16 @@ main = io (show . rpn)
io :: (String -> String) -> IO () io :: (String -> String) -> IO ()
io f = interact (unlines . map f . lines) io f = interact (unlines . map f . lines)
rpn :: String -> Double rpn :: String -> Either String Double
rpn = head . foldl parse [] . words where rpn = return . head <=< foldM parse [] . words
parse (y:x:xs) (flip lookup dyad -> Just f) = f x y : xs
parse (x:xs) (flip lookup monad -> Just f) = f x : xs parse :: [Double] -> String -> Either String [Double]
parse xs (flip lookup nilad -> Just k) = k : xs parse (y:x:xs) (flip lookup dyad -> Just f) = Right (f x y : xs)
parse xs x = read x : xs parse (x:xs) (flip lookup monad -> Just f) = Right (f x : xs)
parse xs (flip lookup nilad -> Just k) = Right (k : xs)
parse xs x = case readMaybe x of
Just x -> Right (x : xs)
Nothing -> Left "Syntax error"
-- dyadic functions -- dyadic functions
dyad = [ ("+", (+)) dyad = [ ("+", (+))