Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Interesting, and disappointing in a way. I assumed that all Monadic compositions would be closed analogous to linear algebra operations and vector spaces. Out of curiosity, do you have a reference to read up on Monadic Composition not being closed? Particularly any lighter references (it's a Saturday after all).


Here's a simple counter-example.

The state monad is the following functor

    St s a = s -> (a, s)
if we compose it with itself (using `d` as the second state parameter)

    St s (St d a) = s -> (d -> (a, d), s)
is `F a = St s (St d a)` a monad? The return operation is clear enough

    return a = \s -> (\d -> (a, d), s)
but the join operation fails

    join :: F (F a) -> F a
         :: St s (St d (St s (St d a))) -> St s (St d a)
         :: s -> (d -> (s -> (d -> (a, d), s), d), s)
         -> s -> (d -> (a, d), s)

    join m0 = 
      \s0 -> let (m1 :: St d (F a), s1) = m0 s0
             in (\d0 -> let (m2 :: F a, d1) = m1 d0
                            (m3 :: St d a, s2) = m2 s1
                            (a, d2) = m3 d1
                        in (a, d2)
                , ??? )
The trouble is the ??? bit where we'd like to place the furthest advanced `s` state named `s2`, but it's not in scope to return at the top since we have to apply the d state to reach it.

This however only means that St does not compose with itself as a functor. It composes just fine in another method. If we install the inner monad "wrapped around" the tuple

    StT s m a = s -> m (a, s)      -- T for "transformer"
then the composition of states looks like

    StT s (St d) a = s -> St d (a, s)
                   = s -> d -> ((a, s), d)
                   = (s, d) -> (a, (s, d))
                   = St (s, d) a
which is obviously a monad.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: