A Neighborhood of Infinity: Haskell Monoids and their Uses - 0 views
-
The Writer MonadYou can think of monoids as being accumulators. Given a running total, n, we can add in a new value a to get a new running total n' = n `mappend` a. Accumulating totals is a very common design pattern in real code so it's useful to abstract this idea. This is exactly what the Writer monad allows. We can write monadic code that accumulates values as a "side effect". The function to perform the accumulation is (somewhat confusingly) called tell. Here's an example where we're logging a trace of what we're doing.
-
This is an implementation of the factorial function that tells us what it did.
-
We use runWriter to extract the results back out. If we run> ex1 = runWriter (fact1 10)we get back both 10! and a list of what it took to compute this.
- ...6 more annotations...