summaryrefslogtreecommitdiff
path: root/solveRPN.hs
diff options
context:
space:
mode:
authorJoe Zhao <ztuowen@gmail.com>2014-08-08 14:37:06 +0800
committerJoe Zhao <ztuowen@gmail.com>2014-08-08 14:37:06 +0800
commite285e81c2519dfe9b000d0f297b72c6c9909662d (patch)
tree352ee7f112be704111da437df4f62f15a37b3be9 /solveRPN.hs
parent423693811904a6038a1a7532700726799e05fade (diff)
downloadhaskbox-old-e285e81c2519dfe9b000d0f297b72c6c9909662d.tar.gz
haskbox-old-e285e81c2519dfe9b000d0f297b72c6c9909662d.tar.bz2
haskbox-old-e285e81c2519dfe9b000d0f297b72c6c9909662d.zip
Last few chapters in LYHGG
Diffstat (limited to 'solveRPN.hs')
-rw-r--r--solveRPN.hs15
1 files changed, 15 insertions, 0 deletions
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