How are functors in Haskell related to functors in category theory?

一个人想着一个人 提交于 2019-12-03 04:53:39

问题


For as far as I understand, a functor is a mapping between two categories, for example from objects in to objects in where and are categories.

In Haskell there is Hask in which the objects are Haskell types and the morphisms are Haskell functions. However, the Functor type class has a function fmap which maps between these types (which are thus objects and not categories themselves):

fmap :: (a -> b) -> f a -> f b

f a and f b are both objects in Hask. Does this mean every instance of Functor in Haskell is an endofunctor, and if not does Functor really represent a functor?

What am I missing here? Are types also categories in Haskell?


回答1:


An instance of Functor specifies two things: a type constructor F of kind * -> *, that is, a mapping from objects of Hask to objects of Hask, and a function of type (a -> b) -> (F a -> F b), that is, a mapping from arrows of Hask to arrows of Hask compatible with the object-mapping F. So, yes, all instances of Functor are endofunctors. There are several generalizations available on Hackage, e.g. Control.Categorical.Functor.




回答2:


Yes, all Functor instances are endofunctors on Hask--in fact, endofunctors from all of Hask to a proper subcategory whose objects are the types obtained by applying a particular type constructor. That type constructor is what the Functor instance is associated with, and gives the mapping for objects; the mapping for morphisms is fmap, which (because we're only concerned with endofunctors on a cartesian closed category) is itself a family of morphisms in Hask.

It does make sense to consider other functors besides those which can have Functor instances, such as contravariant functors (from Hask to its opposite category). The arr function in the Arrow class also corresponds to a functor, from all of Hask to the category whose objects are the same as those of Hask and whose morphisms are described by the type constructor the Arrow instance is associated with.

Further generalizations are also possible (as Daniel Wagner notes), but tend to become increasingly awkward to use.




回答3:


One important point about this is that what you really want is functors enriched in Hask, not just plain old functors. Hask is cartesian closed (not really, but it tries hard to be onesuch), and so it is naturally enriched in itself.

Now, enriched endofunctors give you a way of restricting to those implementable within the language: an enriched functor Hask -> Hask is a function at the level of objects (types) f a and for each pair of objects a, b a morphism in Hask going f : Hask(a,b) -> Hask(fa,fb). Of course, this is just fmap :: (a -> b) -> f a -> f b



来源:https://stackoverflow.com/questions/14820139/how-are-functors-in-haskell-related-to-functors-in-category-theory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!