From da8897b2385d12eefe31af6c11c1a0f98480126f Mon Sep 17 00:00:00 2001 From: Rnhmjoj Date: Thu, 26 Feb 2015 19:50:12 +0100 Subject: [PATCH] Initial commit --- RPN.hs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 RPN.hs diff --git a/RPN.hs b/RPN.hs new file mode 100644 index 0000000..c40f03b --- /dev/null +++ b/RPN.hs @@ -0,0 +1,42 @@ +{-# LANGUAGE ViewPatterns #-} + +import Data.List + +main :: IO () +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 + +-- dyadic functions +dyad = [ ("+", (+)) + , ("-", (-)) + , ("*", (*)) + , ("/", (/)) + , ("^", (**)) ] + +-- monadic functions +monad = [ ("sin" , sin ) + , ("asin" , asin) + , ("cos" , cos ) + , ("acos" , acos) + , ("tan" , tan ) + , ("atan" , atan) + , ("ln" , log ) + , ("sqrt" , sqrt) + , ("sgn" , signum) + , ("abs" , abs) + , ("floor", fromIntegral . floor) + , ("ceil" , fromIntegral . ceiling) ] + +-- niladic functions +nilad = [ ("pi" , pi) + , ("e" , exp 1) + , ("phi", (1 + sqrt 5)/2) ] \ No newline at end of file