[Haskell-cafe] evaluation semantics of bind

Jeremy Shaw jeremy at n-heptane.com
Thu Feb 5 11:20:36 EST 2009


The type IO (in many Haskell implemenations) is essentially:

> type IO a  =  RealWorld -> (a, RealWorld)

And >> would be implemented like:

> (>>) :: IO a -> IO b -> IO b
> action1 >>= action2 = \world0 ->
>   let (a, world1) = action1 world0
>       (b, world2) = action2 world1
>   in (b, world2)

So, even though action2 does not depend on the 'a' value returned by
action1, it does depend on the world value. Hence, the compiler will
not optimize away the call to action1, because then it would not have
a 'world1' value to pass to action2.

It is the passing around of these 'world*' values that causes the IO
operations to happen in the right order.

Of course, this only works if the programmer is careful to ensure that
each world variable is used exactly once, and that no functions are
accidently skipped, etc. For example, lets say that (>>) was
accidently defined like:

> (>>) :: IO a -> IO b -> IO b
> action1 >>= action2 = \world0 ->
>   let (a, world1) = action1 world0
>       (b, world2) = action2 world0 -- oops, should be world1
>   in (b, world2)

now action1 would not be run. Since it is so easy to accidently screw
up the passing around of world variables, we don't do it 'by hand'. We
get it right once in the Monad instance, and then we don't have to
worry about it anymore.

- jeremy

At Thu, 5 Feb 2009 09:20:06 -0600,
Gregg Reynolds wrote:
> [1  <multipart/alternative (7bit)>]
> [1.1  <text/plain; UTF-8 (7bit)>]
> 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.
> I can see that the monad laws ensure this But I haven't found anything that
> states this.  Am I missing something?
> Thanks,
> gregg
> [1.2  <text/html; UTF-8 (quoted-printable)>]
> [2  <text/plain; us-ascii (7bit)>]
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe

More information about the Haskell-Cafe mailing list