Add error handling
This commit is contained in:
parent
da8897b238
commit
516a0173f7
18
RPN.hs
18
RPN.hs
@ -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 = [ ("+", (+))
|
||||||
|
Loading…
Reference in New Issue
Block a user