[Haskell-cafe] A question about monad laws
tobias.schoofs at gmx.net
Mon Jan 17 21:49:50 CET 2011
Perhaps this might help:
I wrote a kind of logger monad that inserted messages with a context.
Behind was an algebraic data type, let's say "LoggerState".
The API provided methods to add a message like this:
addError :: String -> Logger ()
addError "Fatal error occurred"
addWarning "Some warning"
There were methods to enter and exit the context:
enterContext :: String -> Logger ()
exitContext :: Logger ()
enterContext "System x"
enterContext "SubSystem x.y"
enterContext "Module x.y.z"
Well, the context was stored in an attribute of LoggerState, let's call
The add function would pick the current ctx and add it to the message.
A message was defined as: ([Context], (State, String)) where State was
Ok, Warning, Error.
This, however, violates the associativity. In consequence, the context
of messages would depend on parentheses, e.g.:
someFunction :: Logger ()
someFunction = do
addError "Some Error"
produces a different result than:
enterContext "A" >>
addError "Some Error" >>
enterContext "B" >>
enterContext A >>
(addError "Some Error" >>
Here, addError and callSomeOtherFunction would operate on a LoggerState
without any Context,
whereas in the previous example, there is context "A".
Without the associativity law, it would be very hard to determine the
current state of the monad.
Since the compiler, on "desugaring" do-blocks, will insert brackets,
there is no guarantee that the results are the same as for the
brace-less and sugar-free version of the code.
Hope this helps!
On 01/17/2011 04:21 AM, C K Kashyap wrote:
> I am trying to get a better understanding of the "monad laws" - right
> now, it seems too obvious
> and pointless. I had similar feelings about identity function when I
> first saw it but understood its use
> when I saw it in action.
> Could someone please help me get a better understanding of the
> necessity of monads complying with these laws?
> I think, examples of somethings stop working if the monad does not
> obey these laws will help me understand it better.
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe