Skip to content

Instantly share code, notes, and snippets.

@astanin
Created September 3, 2012 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astanin/3609377 to your computer and use it in GitHub Desktop.
Save astanin/3609377 to your computer and use it in GitHub Desktop.
A mini-tutorial on using WriterT monad transformer.
{- A mini-tutorial on using WriterT monad transformer. -}
import Control.Monad.Writer.Lazy
{- A single-argument IO action: print and return. -}
pr :: (Show a) => a -> IO a
pr x = do
print x
return x
{- The same with WriterT; note the use of 'lift' and 'tell'.
ghci> r <- runWriterT $ prW 42
42
ghci> r
(42,["42"])
-}
prW :: (Show a) => a -> WriterT [String] IO a
prW x = do
lift (print x)
tell [show x]
return x
{- now let's create writing actions programmatically -}
{- do an action _and_ write the result
ghci> :{
*Main| r <- runWriterT $ let pr' = pr `withWriting` (\x -> [show x])
*Main| in do { pr' 123 ; pr' 456 ; }
*Main| :}
123
456
ghci> r
(456,["123","456"])
-}
withWriting :: (Monad m, Monoid w) =>
(a -> m b) -- ^ monadic action
-> (b -> w) -- ^ writing action
-> (a -> WriterT w m b)
withWriting act write x = do
r <- lift (act x)
tell (write r)
return r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment