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 --- addStuff.hs | 12 ++++++++++++ powerset.hs | 4 ++++ solveRPN.hs | 15 +++++++++++++++ stateful.hs | 15 +++++++++++++++ 4 files changed, 46 insertions(+) create mode 100644 addStuff.hs create mode 100644 powerset.hs create mode 100644 solveRPN.hs create mode 100644 stateful.hs diff --git a/addStuff.hs b/addStuff.hs new file mode 100644 index 0000000..d440f7e --- /dev/null +++ b/addStuff.hs @@ -0,0 +1,12 @@ +import Control.Monad.Instances + +addStuff :: Int -> Int +addStuff = do + a <- (*2) + b <- (+10) + return (a+b) + +complexOp = do + a <- sqrt + b <- log . (**2) + return (a+b) diff --git a/powerset.hs b/powerset.hs new file mode 100644 index 0000000..39d53ab --- /dev/null +++ b/powerset.hs @@ -0,0 +1,4 @@ +import Control.Monad + +powerset :: [a] -> [[a]] +powerset xs = filterM (\x -> [True,False]) xs 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 diff --git a/stateful.hs b/stateful.hs new file mode 100644 index 0000000..63548d3 --- /dev/null +++ b/stateful.hs @@ -0,0 +1,15 @@ +import Control.Monad.State + +type Stack = [Int] + +pop :: State Stack Int +pop = state $ \(x:xs) -> (x,xs) + +push :: Int -> State Stack () +push a = state $ \xs -> ((), a:xs) + +stackManip :: State Stack Int +stackManip = do + push 3 + pop + pop -- cgit v1.2.3-70-g09d2