A Quick Lap with the Writer Monad
16 Mar 2014Introduction
The Writer monad allows functions to accumulate information as functions execute. According to the Hackage page:
A writer monad parameterized by the type w of output to accumulate.
Perhaps not the most verbose of descriptions, however this is rather simple to explain with a well known example. In previous programming disciplines you would have needed to log information out of your code as your program “did things”. The Writer monad allows you to write out information in a log form. This doesn’t necessarily have to be in textual log format; an example I have seen recently is to keep track of calculations used to come to a final result. The calculations put into that log sped up calculations on other figures.
The idea here is to not clutter your code having to support things like logging/tracing, etc. Employing this monad gives your code the ability to produce this output on the side without getting in the way.
Key Pieces
- Functions in the Writer monad are decorated with
Writer l r
.l
in this case is the type that you’ll be logging out wherer
is the result being returned from your function. - The function
tell
is what’s used to push another value into the log/trace/writer. - Operations in the Writer monad can be chained together using
>>=
runWriter
is what you’ll use to run something in the Writer monad to get your result back.