Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Created October 24, 2014 14:52
Show Gist options
  • Save davidallsopp/b7ecf8789efa584971c1 to your computer and use it in GitHub Desktop.
Save davidallsopp/b7ecf8789efa584971c1 to your computer and use it in GitHub Desktop.
Simple example of the Writer Monad (in Haskell), adapted from LYAH (http://learnyouahaskell.com)
module WriterMonad where
-- From http://learnyouahaskell.com/for-a-few-monads-more
-- This example no longer works without tweaking - see
-- http://stackoverflow.com/questions/11684321/how-to-play-with-control-monad-writer-in-haskell
-- just replace the data constructor "Writer" with the function "writer" in the line marked "here"
-- That changed with mtl going from major version 1.* to 2.*, shortly after LYAH and RWH were written
import Control.Monad.Writer
logNumber :: Int -> Writer [String] Int
logNumber x = writer (x, ["Got number: " ++ show x]) -- here
-- or can use a do-block to do the same thing, and clearly separate the logging from the value
logNumber2 :: Int -> Writer [String] Int
logNumber2 x = do
tell ["Got number: " ++ show x]
return x
multWithLog :: Writer [String] Int
multWithLog = do
a <- logNumber 3
b <- logNumber 5
tell ["multiplying " ++ show a ++ " and " ++ show b ]
return (a*b)
main :: IO ()
main = print $ runWriter multWithLog -- (15,["Got number: 3","Got number: 5","multiplying 3 and 5"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment