Monads/Writer monad: Difference between revisions

added haskell
(added haskell)
Line 197:
</lang>
 
=={{header|Haskell}}==
 
Haskell has the built-in <code>Monad</code> type class, and a built-in <code>Writer</code> monad (as well as the more general <code>WriterT</code> monad transformer that can make a writer monad with an underlying computation that is also a monad) already conforms to the <code>Monad</code> type class.
 
Making a logging version of functions (unfortunately, if we use the built-in writer monad we cannot get the values into the logs when binding):
<lang haskell>import Control.Monad.Trans.Writer
import Control.Monad ((>=>))
 
loggingVersion :: (a -> b) -> c -> a -> Writer c b
loggingVersion f log x = writer (f x, log)
 
logRoot = loggingVersion sqrt "obtained square root, "
logAddOne = loggingVersion (+1) "added 1, "
logHalf = loggingVersion (/2) "divided by 2, "
 
halfOfAddOneOfRoot = logRoot >=> logAddOne >=> logHalf
 
main = print $ runWriter (halfOfAddOneOfRoot 5)</lang>
 
{{Out}}
 
<pre>
(1.618033988749895,"obtained square root, added 1, divided by 2, ")
</pre>
 
=={{header|J}}==
Anonymous user