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 #-}
import Data.List
import Text.Read
import Control.Monad
main :: IO ()
main = io (show . rpn)
@ -8,12 +10,16 @@ main = io (show . rpn)
io :: (String -> String) -> IO ()
io f = interact (unlines . map f . lines)
rpn :: String -> Double
rpn = head . foldl parse [] . words where
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 xs (flip lookup nilad -> Just k) = k : xs
parse xs x = read x : xs
rpn :: String -> Either String Double
rpn = return . head <=< foldM parse [] . words
parse :: [Double] -> String -> Either String [Double]
parse (y:x:xs) (flip lookup dyad -> Just f) = Right (f x y : 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
dyad = [ ("+", (+))