Clean a bit the code
This commit is contained in:
parent
e2278ad892
commit
6c20bf7993
31
RPN.hs
31
RPN.hs
@ -2,24 +2,35 @@
|
|||||||
|
|
||||||
import Data.List
|
import Data.List
|
||||||
import Text.Read
|
import Text.Read
|
||||||
|
import Text.Printf
|
||||||
import Control.Monad
|
import Control.Monad
|
||||||
|
|
||||||
main :: IO ()
|
main :: IO ()
|
||||||
main = io (show . rpn)
|
main = io (result . rpn)
|
||||||
|
|
||||||
|
|
||||||
|
-- Interact line-by-line
|
||||||
io :: (String -> String) -> IO ()
|
io :: (String -> String) -> IO ()
|
||||||
io f = interact (unlines . map f . filter (not . null) . lines)
|
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]
|
-- Pretty print RPN result/errors
|
||||||
parse (y:x:xs) (flip lookup dyad -> Just f) = Right (f x y : xs)
|
result :: Either String Double -> String
|
||||||
parse (x:xs) (flip lookup monad -> Just f) = Right (f x : xs)
|
result (Left err) = "Ꞥ∘ " ++ err
|
||||||
parse xs (flip lookup nilad -> Just k) = Right (k : xs)
|
result (Right x) = printf ("ꟼ∘ " ++ format) x where
|
||||||
parse xs x = case readMaybe x of
|
format = if ceiling n == floor n then "%.0f" else "%.10f"
|
||||||
Just x -> Right (x : xs)
|
|
||||||
Nothing -> Left "Syntax error"
|
|
||||||
|
-- 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
|
-- dyadic functions
|
||||||
dyad = [ ("+", (+))
|
dyad = [ ("+", (+))
|
||||||
|
Loading…
Reference in New Issue
Block a user