Created
September 3, 2012 13:35
-
-
Save astanin/3609377 to your computer and use it in GitHub Desktop.
A mini-tutorial on using WriterT monad transformer.
This file contains 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
{- 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