Functor
Programmers are familiar with the concept of functor and can recognize generic types such as lists as functors in object-oriented languages because they usually have a map/fmap/select method that transforms a list of type List<int> in a list List<string> through a function .
The truth is that the concept of functor in mathematics and the one in programming represent the same concept from different perspectives, the correspondence is not intuitive and obvious and we will show why.
Definition: Functor
A functor from a category to another , denoted is a mapping that sends in an object and which sends to a morphism such that:
- preserves the composition: =
- preserves the identity: =
Basically, a functor is a homomorphism (mapping that preserves the structure) between two categories.
Connection with programming
Returning to the correspondence between programming and mathematics, we can highlight the connection by considering the following example. Let's assume that within a program we have three types of data, int, bool and string with the following functions between them: and . Let's assume that our basic types represent a category with types being objects and functions being morphisms. If we introduce a functor called as a generic type that has a function then the tuple represents the functor according to the definition given as the two mappings on objects and morphisms respectively.
This is just an example to conceptually illustrate the idea of a functor for a programmer, in reality the formalization of type systems in the form of categories is much more complex.
What we can see here is that the functor does not preserve an internal structure of a data type, this is irrelevant in a functional context, but it preserves the structure of relationships between data types. Also, for other generic types with different properties, several objects and morphisms must be included in the destination category for the functor. The destination category can include other objects and morphisms that are not mapped to from the source category.
Composition
Just as morphisms and functors can be composed, if we have functors and , then there will exist a functor that, when applied to and , maps to and , respectively.
Identity Functor
A special case of an (endo)functor is the identity functor (endofunctors are functors with the same source and destination category) which satisfies the properties:
Thus, this functor satisfies the relations for the composition of any functors ,