[Haskell-cafe] >> and sequencing [newbie]

jeff p mutjida at gmail.com
Sun Apr 15 20:32:49 EDT 2007


On 4/15/07, David Powers <david at grayskies.net> wrote:
> so... this is likely a question based on serious misunderstandings, but can
> anyone help me understand the exact mechanism by which monads enforce
> sequencing?
Monads do not enforce sequencing.

In general, data dependencies enforce sequencing (i.e. if expression x
depends upon expression y then expression y will have to be evaluated
first). Consider:

    let x = case y of Just y' -> f y'
                             Nothing -> g
         y = some code
    in more stuff

Here y must be evaluated before x because x needs to look at y in
order to compute.

> Specifically, I'm confused by the >> operator.  If I understand
> things properly f a >> g expands to something like:
> f >>= \_ -> g
> What I'm missing is how the expansion of f is ever forced under lazy
> evaluation.  Since the result is never used, doesn't it just stay as a
> completely unevaluated thunk?
(>>=) is an overloaded function. Some instances of it will cause f to
be evaluated, others won't. Consider the State monad:

    instance Monad (State s) where
        return a = State $ \s -> (a, s)
        m >>= k  = State $ \s -> case runState m s of
                                     (a, s') -> runState (k a) s'

Note that (>>=)  causes m to be evaluated (up to a pair) before
evaluating k because (>>=) needs to look at the result of m.

An example of a monad in which (>>=) doesn't force evaluation of the
first argument before the second is the Identity monad:

    instance Monad Identity where
        return a = Identity a
        m >>= k  = k (runIdentity m)

Note that (>>=) actually forces the evaluation of k before m.


More information about the Haskell-Cafe mailing list