From 6c20bf7993ecacb253d7869f329d54d6a20f92cc Mon Sep 17 00:00:00 2001 From: Rnhmjoj Date: Fri, 27 Feb 2015 00:58:54 +0100 Subject: [PATCH] Clean a bit the code --- RPN.hs | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/RPN.hs b/RPN.hs index 98a8620..d241f0a 100644 --- a/RPN.hs +++ b/RPN.hs @@ -2,24 +2,35 @@ import Data.List import Text.Read +import Text.Printf import Control.Monad main :: IO () -main = io (show . rpn) +main = io (result . rpn) + +-- Interact line-by-line io :: (String -> String) -> IO () io f = interact (unlines . map f . filter (not . null) . lines) -rpn :: String -> Either String Double -rpn = foldM parse [] . words >=> return . head -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" +-- Pretty print RPN result/errors +result :: Either String Double -> String +result (Left err) = "Ꞥ∘ " ++ err +result (Right x) = printf ("ꟼ∘ " ++ format) x where + format = if ceiling n == floor n then "%.0f" else "%.10f" + + +-- Solve a RPN expression +rpn :: String -> Either String Double +rpn = foldM parse [] . words >=> return . head where + 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 = [ ("+", (+))