Skip to content

Instantly share code, notes, and snippets.

@tuttlem
Created March 16, 2014 10:38
Show Gist options
  • Save tuttlem/9581344 to your computer and use it in GitHub Desktop.
Save tuttlem/9581344 to your computer and use it in GitHub Desktop.
WriterMonad example
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