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 ie 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.
First of all, 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 (ie functions, which are values): it's just fmap :: (α -> β) -> (F α -> F β)
.
So far, I guess, I'm not saying anything new. But important thing is that return :: α -> M α
of Monad
is not a mapper of a type α
to the M α
as you may think. Regarding to the math definition of a monad, return
corresponds to a natural transformation from Id
functor to the M
functor. Just that this Id
functor is kind of implicit. The standard definition of monad requires also another natural transformation M ◦ M -> M
. So translating it to Haskell would be 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 (except maybe the lack of Functor
instance in the context). See Haskell/wiki on that.
If you take the composition-like operator derived form 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.
Objects of a category are not the same as objects in a OO programming language (we prefer to call those values in Haskell; what they mean in category theory was discussed here). Rather, the objects of Hask are types. Haskell Functor
s are endofunctors in Hask , ie associate types to types, by the following means:
Prelude> :k Maybe
Maybe :: * -> *
Prelude> :k Int
Int :: *
Prelude> :k Maybe Int
Maybe Int :: *
OTOH, the arrows of Hask are in fact values, of some function type a -> b
. These are associated in the following way:
fmap :: ( Functor (f :: t -> f t {- type-level -} ) )
=> (a->b) -> fmap(a->b) {- value-level -}
≡ (a->b) -> (f a->f b)
If you have
instance Functor F where
fmap = ...
Then the type constructor F
is the action on objects (which are types) taking a type T
to the type FT
, and fmap
is the action on morphisms (which are functions) taking a function f :: T -> U
to fmap f :: FT -> FU
.
下一篇: 为什么Functor类没有返回函数?