[Haskell-cafe] evaluation semantics of bind

Roman Cheplyaka roma at ro-che.info
Thu Feb 5 10:32:37 EST 2009

* Gregg Reynolds <dev at mobileink.com> [2009-02-05 09:20:06-0600]
> I think I've just about got monads figured out, but there's one detail that
> still escapes me.  As I understand it, a monad is a kind of programming
> trick the uses data dependency to force evaluation order.  x >>= f means
> apply f to x; since the value of f x depends on the value of x, the
> evaluator must evaluate x before f x. However, consider:
>     getChar >>= \x -> getChar
> An optimizer can see that the result of the first getChar is discarded and
> replace the entire expression with one getChar without changing the formal
> semantics.  But that would change the behavior, so to get the desired
> behavior, there must be some principle that prevents this from happening,
> ensuring that x >>= f always evaluates f x.

x >>= f doesn't mean apply f to x. It means, roughly, "construct (IO) action from
actions x and f(..), so that they are executed sequentially and f depends on
a resuls produced by x". Even if f does not depend on its argument,
there's no reason for compiler to think that the first action may be

If you think in terms of dependency, the second action depends on the
state of the "world" left after executing x. So all IO actions take an
implicit "world" argument and (>>=) operator implicitely passes modified
"world" to the next action.

> I can see that the monad laws ensure this But I haven't found anything that
> states this.  Am I missing something?

Roman I. Cheplyaka :: http://ro-che.info/
"Don't let school get in the way of your education." - Mark Twain

More information about the Haskell-Cafe mailing list