Ah... so the secret is in the hidden variables.  On some level I am
beginning to fear that Monads resurrect some of the scariest aspects of
method overriding from my OO programming days.  Do you (all) ever find that
the ever changing nature of >>= makes code hard to read?


On 4/15/07, jeff p <[EMAIL PROTECTED]> wrote:

Hello,

On 4/15/07, David Powers <[EMAIL PROTECTED]> 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.

-Jeff

_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to