Newbie qustion about monads

Alastair Reid alastair at reid-consulting-uk.ltd.uk
Thu Oct 2 13:30:54 EDT 2003


> So, the question remains: when the monad
> laws say that
>
>   (return x) >>= f == f x
>
> what is intended in that "=="?

Observational equivalence.

For monads like list and maybe, this boils down to the normal equality because 
the standard equality on these types is exactly observational equality.

For monads like IO, you can't define an Eq instance so it comes down to what 
can the user of the program observe.  They can observe the order you create 
files or write to files.  They can even observe the order you open files.  
They can't observe 'internal' actions that don't have side effects and don't 
depend on the IO environment so 'return' should not be observable.  In 
particular, they can't see any of the returns in this sequence:

  do
    return 1
    return 2
    return 3
    print 42

Which is a good thing since the monad law you cite requires this to be equal 
to

  print 42


For monads like parser monads, there is usually a notion of encapsulation.  
That is, you're supposed to be able to observe the results of running the 
parser and you may also be able to observe how much input was examined but 
you probably can't directly observe the internal state of the parser.  In 
that case, we'd consider two states to be equivalent if they lead to the same 
results being returned and the same input being examined.  Since parsers are 
state transformers, we'd say that two parsers are equivalent if they preserve 
and reflect equivalence of states.

(There's a little circularity there and I'm ignoring the exception part of 
parser monads but, hopefully, you get the idea.)

--
Alastair Reid     www.haskell-consulting.com



More information about the Haskell-Cafe mailing list