diff --git a/RPN.hs b/RPN.hs index c40f03b..71536af 100644 --- a/RPN.hs +++ b/RPN.hs @@ -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 = [ ("+", (+))