Created
March 16, 2014 10:38
-
-
Save tuttlem/9581344 to your computer and use it in GitHub Desktop.
WriterMonad 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.Writer | |
-- | 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 -> Writer [String] Int | |
start x = do | |
tell (["Starting with " ++ show x]) | |
return x | |
-- | Halve a value | |
-- Any value passed into this function gets halved | |
-- | |
half :: Int -> Writer [String] Int | |
half x = do | |
tell (["Halving " ++ show x]) | |
return (x `div` 2) | |
-- | Squares a value | |
-- Any value passed into this function gets squared | |
-- | |
sqr :: Int -> Writer [String] Int | |
sqr x = do | |
tell (["Squaring " ++ show x]) | |
return (x * x) | |
main :: IO () | |
main = do | |
let work = runWriter $ start 10 >>= half >>= sqr >>= half | |
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