Created
March 16, 2014 11:16
-
-
Save tuttlem/9581716 to your computer and use it in GitHub Desktop.
State Monad example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Monad.State | |
-- | Starts a value off. | |
-- This function doesn't perform any calculation at all, it just prepares an | |
-- initial value to start in the calculation pipeline | |
-- | |
start :: Int -> State [String] Int | |
start x = do | |
put ["Starting with " ++ show x] | |
return x | |
-- | Halve a value | |
-- Any value passed into this function gets halved | |
-- | |
half :: Int -> State [String] Int | |
half x = do | |
s <- get | |
let ns = s ++ ["Halving " ++ show x] | |
put ns | |
return (x `div` 2) | |
-- | Squares a value | |
-- Any value passed into this function gets squared | |
-- | |
sqr :: Int -> State [String] Int | |
sqr x = do | |
s <- get | |
let ns = s ++ ["Squaring " ++ show x] | |
put ns | |
return (x * x) | |
main :: IO () | |
main = do | |
let c = runState $ start 10 >>= half >>= sqr >>= half | |
let work = c [""] | |
let ans = fst $ work | |
let log = snd $ work | |
putStrLn $ "Answer: " ++ show ans | |
putStrLn "" | |
putStrLn " ==== Log ==== " | |
mapM_ putStrLn log |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment