[Haskell-cafe] Intuition to understand poor man's concurrency

Mikael Brockman mbrock at goula.sh
Wed Jul 30 12:56:01 UTC 2014


Benjamin Franksen <benjamin.franksen at helmholtz-berlin.de> writes:

> martin wrote:
>> I am trying to understand the ideas of Koen Klaessen, published in
>> Functional Pearls: "A poor man's concurrency" (1993).
>
> [...]
>
>   m >>= k = \f -> m (\x -> k x f)
>
> If you re-add the newtype wrapping and unwrapping, this is exactly the
> same as your definition above.
>
> This is one answer to the question of how one can arrive at a suitable
> definition of >>= for the continuation monad. But it does not tell us
> anything about how to arrive at an intuition about what this
> implementation really does. Maybe someone else can explain this...

Values of `Cont a` are functions in continuation-passing style.  That
is, they are functions that hand their results to a continuation passing
function, instead of returning.  I think the trickiness of this stuff
has more to do with continuation-passing style in general and less to do
with any inherent abstruseness of monadic bind.

With some CPS familiarity, you can see that `m` is just a function that
accepts a continuation, and `k` is a function that accepts the
intermediate result and the next continuation.

We know that our new CPS function is going to accept a continuation
argument.  We also know -- by the semantics of CPS -- that this
continuation will be handed to `k`.

So this CPS function

  \f -> m (\x -> k x f)

says: given a continuation `f`, invoke `m` with a continuation that
hands the intermediate result to `k` with the continuation `f`.

You can see how a chain like (given the actual Monad instance)

  do x <- m1
     y <- m2 x
     m3 y

will expand into a CPS function that passes along the continuation such
that `m3` is finally invoked with the continuation of the entire block.

And then, the presence of the Monad constraint just makes it obvious
that this can be used as a monad transformer.

--
Mikael Brockman
mikael at silk.co



More information about the Haskell-Cafe mailing list