Just to make a couple of obvious observations:

Graeme Moss wrote:

> A question born out only of curiosity:
> 
> Can anyone provide a definition of `thread' equivalent to this:
> 
> > thread :: Monad m => [a -> m a] -> a -> m a
> > thread []     a = return a
> > thread (k:ks) a = k a >>= thread ks
> 
> not using pattern matching 

Ralf Hinze came up with:

> thread                =  foldr (\k sol a -> k a >>= sol) return

The lambda expression
        \k sol a -> k a >>= sol
is nothing else but the composition of the monad, in diagrammatical order.
If it's a mathematical monad (rather than just something that fits the types)
then this composition is associative and has 'return' as its neutral element.

Graeme's comparison between his original and his foldl version used this
associativity implicitly, e.g. [writing infix ** for this composition] the
thread version computes:
        thread [k1,k2,k3] = (return ** (k1 ** (k2 ** k3))) 
while the foldl version gives us
        (((return ** k1) ** k2) ** k3) 

As one would expect, one can give counterexamples to this equivalence in 
Haskell,
i.e. create instances of Monad which aren't mathematical monads and which thus 
can
distinguish these two versions of 'thread'; and it's not just a difference in 
laziness...

Cheers, Stefan Kahrs



Reply via email to