Jump to content

Function object

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Michael Hardy (talk | contribs) at 21:42, 20 March 2004. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In functional programming languages such as ML, a function object or 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.