Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monads from all angles - Mathematical, diagramatic and programmatical

I am trying to reconcile the Categorical definition of Monad with the other general representations/definitions that I have seen in some other tutorials/books.

Below, I am (perhaps forcefully) trying to bring the two definitions close, please point out the mistakes and provide corrections, where ever required

So Starting with the definition of Monads

Monads are just monoids in the category of endofunctors.

and with a little understanding of endofunctors, I assume a Monad can be written as

((a->b)->Ma->Mb)->((b->c)->Mb->Mc) 

The 'Type' of LHS (Left hand side) is Mb, and type of RHS is Mc, so I suppose I can write it as below

Mb-> (b->c)-> Mc, **which is how we define bind**

And here is how I see Monads in the category of endofuctors (which themselves are in Category C, with 'types' as objects)

Monad Visually.

Does any of this makes sense?

like image 792
Dev Maha Avatar asked Sep 21 '13 02:09

Dev Maha


1 Answers

Well um, I think you're a bit off. A monad is an endofunctor, which in Hask (The category of Haskell types) is something with the kind F :: * -> * with some function that knows how to inject morphisms (functions) into the subcategory of Hask with functions upon Fs as morphisms and Fs as objects, fmap. What you have there appears to be a natural transformation in Hask.

Examples: Maybe, Either a, (,) a, etc..

Now a monad also must have 2 natural transformations (Functor F, Functor g => F a -> G a in hask).

n : Identity -> M
u : M^2 -> M

Or in haskell code

n :: Identity a -> M a -- Identity a == a
u :: M (M a) -> M a

which correspond to return and join respectively.

Now we have to get to >>=. What you had as bind was actually just fmap, what we actually want is m a -> (a -> m b) -> m b. This is easily defined as

 m >>= f = join $ f `fmap` m

Tada! We have monads. Now for this monoid of endofunctors.

A monoid over endofunctors would have a functors as objects and natural transformations as morphisms. The interesting thing is that the product of two endofunctors is their composition. Here's the Haskell code for our new monoid

type (f <+> g) a = f (g a)
class Functor m => Monoid' m where
    midentity' :: Identity a -> m a
    mappend' :: (m <+> m) a -> m a

This desugars to

 midentity' :: a -> m a
 mappend' :: m (m a) -> m a

Look familiar?

like image 93
Daniel Gratzer Avatar answered Nov 06 '22 19:11

Daniel Gratzer