It is often written that all monads are functors, but it is quite hard to find an actual mathematical proof of it.
A functor is defined as a higher level type defining the fmap function:
class Functor f where
fmap :: (a -> b) -> f a -> f b
It must also preserve composition:
fmap (f . g) == fmap f . fmap g
And follow the identity law:
fmap id == id
A monad is defined as:
class Monad m where
(>>=) :: m a -> ( a -> m b) -> m b
return :: a -> m a
And the bind function must follow the three laws: left identity, right identity and associativity.
fmap for a monad can be defined as:
fmap f xs = xs >>= return . f
In order to prove that all monads are functors, we must prove that such a fmap function follow the composition and identity laws of functors. It's easy enough to prove identity using the left identity law of monads, but I am struggling to show that such definition of fmap conserves composition.
Does someone know the proof for this?
An alternate to the usual definition of a monad (as a functor plus some structure) that's similar to your Haskell definition has three pieces of structure and three equations.
Let $\mathcal C$ be a category. A monad on $\mathcal C$ consists of a map on objects $T : Ob(\mathcal C) \to Ob(\mathcal C)$, for each object $x \in Ob(\mathcal C)$ a morphism $\eta_x : x \to T(x)$ and for each morphism $f : x \to T(y)$, a morphism $f^T : T(x) \to T(y)$.
This structure should satisfy the equations $(\eta_x)^T = id_{T(x)}$, $f^T \circ \eta_x = f$ and $(f^T \circ g)^T = f^T \circ g^T$.
$T$ corresponds to your type function
m. $\eta_x$ is the same asreturnand $f^T$ corresponds to the function that takesxtox >>= f.$T$ can then be extended to morphisms via $T(f) = (\eta_y \circ f)^T$ (where $f : x \to y$).
Then $T(id_x) = (\eta_x \circ id_x)^T = (\eta_x)^T = id_{T(x)}$. Moreover, for $f : y \to z$ and $g : x \to y$,
$$ \begin{align} T(f) \circ T(g) &= (\eta_z \circ f)^T \circ (\eta_y \circ g)^T\\ &= ((\eta_z \circ f)^T \circ \eta_y \circ g)^T\\ &= (\eta_z \circ f \circ g)^T\\ &= T(f \circ g). \end{align} $$
So $T$ is a functor.