Search code examples
mathhaskellmonadsfunctorcategory-theory

Why Functor class has no return function?


From categorical point of view, functor is pair of two maps (one between objects and another between arrows of categories), following some axioms.

I have assumed, what every Functor instance is similar to mathematical definition i.e. can map both objects and functions, but Haskell's Functor class has only function fmap which maps functions.

Why so?

UPD In other words:

Every Monad type M has an function return :: a -> M a.

And Functor type F has no function return :: a -> F a, but only F x constructor.


Solution

  • There are two levels: types and values. As objects of Hask are types, you can map them only with type constructors, which have the * -> * kind:

    • α -> F α (for Functor F),
    • β -> M β (for Monad M).

    Then for a functor you need a map on morphisms (i.e. functions, which are values):

    fmap :: (α -> β) -> (F α -> F β)
    

    The important thing is that return :: α -> M α of Monad is not a mapper of a type α to the M α as you might think. According to the mathematical definition of a monad, return corresponds to a natural transformation from Id functor to the M functor. And the Id functor is kind of implicit in Hask. The standard definition of a monad also requires another natural transformation M ◦ M -> M. So translating it to Haskell would look like

    class Functor m => Monad m where
        return :: Id α -> m α
        join :: m (m α) -> m α
    

    (As a side-note: these two natural transformations are actually the unit and multiplication, which make monad a monoid in the category of endofunctors)

    The actual definition differs, but is equivalent. See Haskell/wiki on that.

    If you take the composition-like operator derived from the standard bind >>= :: m α -> (α -> m β) -> m β:

    (>=>) :: Monad m => (α -> m β) -> (β -> m γ) -> (α -> m γ)
    f >=> g = \a => f a >>= g
    

    You can see, that it's all actually about the Kleisli category. See also the article on nLab about monads in computer science.