Mathematics

In
category theory a functor is a mapping from one category to another which maps objects to objects and morphisms to morphisms in such a manner that the composition of morphisms and the identities are preserved. For the precise definition and examples, see the article on category theory.

Functors were first considered in algebraic topology, where algebraic objects are associated to topological spaces, and algebraic homomorphisms are associated to continuous maps. Nowadays, functors are used throughout modern mathematics to relate various categories.

Software

In functional programming languages such as ML, a functor represents a mapping that maps modules to modules, representing a tool for the reuse of code, and is used in a manner analogous to the original mathematical meaning of the term.

Recently, in C++ and Java, the term functor was coined, probably independently, with a meaning largely unrelated to category theory. In object-oriented software design a class can contain both data and function. The term functor was chosen to describe object instances of a class that primarily contains functions.

This sort of functor has some of the characteristics that a function pointer would have in procedural languages such as C. For example, in object-oriented programming, a sort method might accept a functor argument where the functor class contains a method defining the ordering relation between items to be sorted. The sort method signature would typically define the functor parameter in terms of a base class (probably an interface in Java).

An invocation of the method would supply a functor object of a class derived from this base class (implementing the interface in Java). This allows the sort method to work with different implementations of an ordering relation. The analogue in non-object-oriented procedural programming would be a sort function accepting a function pointer argument where the function pointed-at defines the ordering relation between items to be sorted.

Functors are more powerful than function pointers in that they may contain state (data) that can be used by the function(s) represented.

A functor often contains a single (public) method (apart from the constructor), although this is not a strict limitation.