[Haskell-cafe] A question about monad laws

Tobias Schoofs 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"
etc.

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"
exitContext
exitContext
exitContext

Well, the context was stored in an attribute of LoggerState, let's call 
it ctx.
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
   enterContext "A"
   addError "Some Error"
   callSomeOtherFunction
   exitContext
   enterContext "B"
   ...

produces a different result than:

someFunction =
   enterContext "A" >>
   addError "Some Error" >>
   callSomeOtherFunction >>
   exitContext >>
   enterContext "B" >>
   ...

Imagine:

someFunction =
   enterContext A >>
   (addError "Some Error" >>
    callSomeOtherFunction >>
    exitContext)
   enterContext "B"
   ...

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!

Tobias

On 01/17/2011 04:21 AM, C K Kashyap wrote:
> Hi,
> 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.
> Regards,
> Kashyap
>
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20110117/9815a546/attachment.htm>


More information about the Haskell-Cafe mailing list