From e285e81c2519dfe9b000d0f297b72c6c9909662d Mon Sep 17 00:00:00 2001 From: Joe Zhao Date: Fri, 8 Aug 2014 14:37:06 +0800 Subject: Last few chapters in LYHGG --- solveRPN.hs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 solveRPN.hs (limited to 'solveRPN.hs') diff --git a/solveRPN.hs b/solveRPN.hs new file mode 100644 index 0000000..051999d --- /dev/null +++ b/solveRPN.hs @@ -0,0 +1,15 @@ +import Data.List +import Control.Monad +import Text.Read + +foldingFunction :: [Double] -> String -> Maybe [Double] +foldingFunction (x:y:ys) "*" = return ((y * x):ys) +foldingFunction (x:y:ys) "/" = return ((y / x):ys) +foldingFunction (x:y:ys) "+" = return ((y + x):ys) +foldingFunction (x:y:ys) "-" = return ((y - x):ys) +foldingFunction xs numberString = liftM (:xs) (readMaybe numberString) + +solveRPN :: String -> Maybe Double +solveRPN st = do + [result] <- foldM foldingFunction [] (words st) + return result -- cgit v1.2.3-70-g09d2