Function object
Encyclopedia
A function object, also called a functor, functional, or functionoid, is a computer programming
Computer programming
Computer programming is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs. This source code is written in one or more programming languages. The purpose of programming is to create a program that performs specific operations or exhibits a...

 construct allowing an object
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...

 to be invoked or called as though it were an ordinary function
Subroutine
In computer science, a subroutine is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code....

, usually with the same syntax.

Description

A typical use of a function object is in writing callback
Callback (computer science)
In computer programming, a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower-level software layer to call a subroutine defined in a higher-level layer....

 functions. A callback in procedural languages
Procedural programming
Procedural programming can sometimes be used as a synonym for imperative programming , but can also refer to a programming paradigm, derived from structured programming, based upon the concept of the procedure call...

, such as C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

, may be performed by using function pointer
Function pointer
A function pointer is a type of pointer in C, C++, D, and other C-like programming languages, and Fortran 2003. When dereferenced, a function pointer can be used to invoke a function and pass it arguments just like a normal function...

s. However it can be difficult or awkward to pass a state into or out of the callback function. This restriction also inhibits more dynamic behavior of the function. A function object solves those problems since the function is really a façade
Façade pattern
The facade pattern is a software engineering design pattern commonly used with Object-oriented programming. The name is by analogy to an architectural facade....

 for a full object, thus it carries its own state.

Many modern languages (and some older) e.g. C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

, Lisp, Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

, PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

, Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

, Ruby
Ruby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

, and many others, support first-class function
First-class function
In computer science, a programming language is said to have first-class functions if it treats functions as first-class objects. Specifically, this means that the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning...

 objects and may even make significant use of them. Functional programming
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...

 languages additionally support closures
Closure (computer science)
In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...

, i.e. first-class functions which can 'close over' variables in their surrounding environment at creation time. During compilation, a transformation known as lambda lifting
Lambda lifting
Lambda lifting or closure conversion is the process of eliminating free variables from local function definitions from a computer program. The elimination of free variables allows the compiler to hoist local definitions out of their surrounding contexts into a fixed set of top-level functions with...

 converts the closures into function objects.

In C and C++

Consider the example of a sorting routine which uses a callback function to define an ordering relation between a pair of items. A C program using function pointers may appear as:

  1. include


/* Callback function */
int compare_ints_function(void *A, void *B) {
return *((int *)(A)) < *((int *)(B));
}
...
/* Declaration of C sorting function */
void sort(void *first_item, size_t item_size, void *last_item, int (*cmpfunc)(void *, void *) );
...
int main(void) {
int items[] = {4, 3, 1, 2};
sort((void *)(items), sizeof(int), (void *)(items + 3), compare_ints_function);
return 0;
}


In C++ a function object may be used instead of an ordinary function by defining a class which overloads
Operator overloading
In object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments...

 the function call operator by defining an operator member function. In C++ this is called a class type functor, and may appear as follows:


struct compare_class {
bool operator(int A, int B) const {
return A < B;
}
};
...
// Declaration of C++ sorting function.
template
void sort_ints(int* begin_items, int num_items, ComparisonFunctor c);
...
int main {
int items[] = {4, 3, 1, 2};
sort_ints(items, sizeof(items)/sizeof(items[0]), compare_class);
}


Notice that the syntax for providing the callback to the sort_ints function is identical, but an object is passed instead of a function pointer. When invoked, the callback function is executed just as any other member function, and therefore has full access to the other members (data or functions) of the object.

It is possible to use function objects in situations other than as callback functions (although the shortened term functor is normally not used). Continuing the example,


functor_class Y;
int result = Y( a, b );


In addition to class type functors, other kinds of function objects are also possible in C++. They can take advantage of C++'s member-pointer or template
Generic programming
In a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...

 facilities. The expressiveness of templates allows some functional programming
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...

 techniques to be used, such as defining function objects in terms of other function objects (like function composition
Function composition (computer science)
In computer science, function composition is an act or mechanism to combine simple functions to build more complicated ones...

). Much of the C++ Standard Template Library
Standard Template Library
The Standard Template Library is a C++ software library which later evolved into the C++ Standard Library. It provides four components called algorithms, containers, functors, and iterators. More specifically, the C++ Standard Library is based on the STL published by SGI. Both include some...

 (STL) makes heavy use of template-based function objects.

C++11 allows one to define anonymous function
Anonymous function
In programming language theory, an anonymous function is a function defined, and possibly called, without being bound to an identifier. Anonymous functions are convenient to pass as an argument to a higher-order function and are ubiquitous in languages with first-class functions such as Haskell...

 objects. The line from the previous example could be written as follows:

sort_ints(items, sizeof(items)/sizeof(items[0]), [](int A, int B){ return A < B; });

Performance

An advantage of function objects in C++ is performance because, unlike a function pointer, a function object can be inlined
Inline function
In various versions of the C and C++ programming languages, an inline function is a function upon which the compiler has been requested to perform inline expansion...

. For example, consider a simple function which increments its argument implemented as a function object:


struct IncrementFunctor {
void operator(int &i) { ++i; }
};

and as a free function:

void increment_function(int &i) { ++i; }

Recall the standard library function std::for_each:

template
Function for_each(InputIterator first, InputIterator last, Function f) {
for ( ; first != last; ++first)
f(*first);
return f;
}

Suppose we apply std::for_each like so:

int A[] = {1, 4, 2, 8, 5, 7};
const int N = sizeof(A) / sizeof(A[0]);
for_each(A, A + N, IncrementFunctor);
for_each(A, A + N, increment_function);

Both calls to for_each will work as expected. The first call will be to this version:

IncrementFunctor for_each(int*, int*, IncrementFunctor)

the second will be to this version:

void (*for_each(int*, int*, void(*)(int&)))(int&)

Within for_each, the compiler will be able to inline the function object because the function is known at compile time whereas within for_each the function cannot be known at compile time because the pointer has not been assigned and so cannot be inlined.

Maintaining state

Another advantage of function objects is their ability to maintain a state which affects operator between calls. Inconveniently, copies of a function object must share a state to work correctly. STL algorithms are allowed to instantiate copies. For example, the following code defines a generator
Generator (computer science)
In computer science, a generator is a special routine that can be used to control the iteration behaviour of a loop. A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values...

 counting from 10 upwards and is invoked 11 times.
  1. include
  2. include
  3. include


class countfrom {
private:
int &count;
public:
countfrom(int &n) : count(n) {}
int operator { return count++; }
};

int main {
int state(10);
std::generate_n(std::ostream_iterator(std::cout, "\n"), 11, countfrom(state));
return 0;
}

In C#

In C#, function objects are declared via delegates
Delegate (.NET)
A delegate is a form of type-safe function pointer used by the .NET Framework. Delegates specify a method to call and optionally an object to call the method on. They are used, among other things, to implement callbacks and event listeners....

.

In D

D
D (programming language)
The D programming language is an object-oriented, imperative, multi-paradigm, system programming language created by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++...

 provides several ways to declare function objects: Lisp/Python-style via closures
Closure (computer science)
In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...

 or C#-style via delegates
Delegate (.NET)
A delegate is a form of type-safe function pointer used by the .NET Framework. Delegates specify a method to call and optionally an object to call the method on. They are used, among other things, to implement callbacks and event listeners....

, respectively:


bool find(T)(T[] haystack, bool delegate(T) needle_test) {
foreach ( straw; haystack ) {
if ( needle_test(straw) )
return true;
}
return false;
}

void main {
int[] haystack = [345,15,457,9,56,123,456];
int needle = 123;
bool needleTest(int n) {
return n needle;
}
assert(
find(haystack, &needleTest)
);
}


The difference between a delegate
Delegate (.NET)
A delegate is a form of type-safe function pointer used by the .NET Framework. Delegates specify a method to call and optionally an object to call the method on. They are used, among other things, to implement callbacks and event listeners....

 and a closure
Closure (computer science)
In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...

 in D is automatically and conservatively determined by the compiler.
D also supports function literals, that allow a lambda-style definition:


void main {
int[] haystack = [345,15,457,9,56,123,456];
int needle = 123;
assert(
find(haystack, (int n) { return n needle; })
);
}


To allow the compiler to inline the code (see above), function objects can also be specified C++-style via operator overloading
Operator overloading
In object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments...

:


bool find(T,F)(T[] haystack, F needle_test) {
foreach ( straw; haystack ) {
if ( needle_test(straw) )
return true;
}
return false;
}

void main {
int[] haystack = [345,15,457,9,56,123,456];
int needle = 123;
class NeedleTest {
int needle;
this(int n) { needle = n; }
bool opCall(int n) {
return n

needle;
}
}
assert(
find(haystack, new NeedleTest(needle))
);
}

In Eiffel
In the Eiffel
Eiffel (programming language)
Eiffel is an ISO-standardized, object-oriented programming language designed by Bertrand Meyer and Eiffel Software. The design of the language is closely connected with the Eiffel programming method...

 software development method and language, operations and objects are seen always as separate concepts. However, the agent mechanism facilitates the modeling of operations as runtime objects. Agents satisfy the range of application attributed to function objects, such as being passed as arguments in procedural calls or specified as callback routines. The design of the agent mechanism in Eiffel attempts to reflect the object-oriented nature of the method and language. An agent is an object which generally is a direct instance of one of the two library classes which model the two types of routines in Eiffel: PROCEDURE and FUNCTION. These two classes descend from the more abstract ROUTINE.

Within software text, the language keyword agent allows agents to be constructed in a compact form. In the following example, the goal is to add the action of stepping the gauge forward to the list of actions to be executed in the event that a button is clicked.


my_button.select_actions.extend (agent my_gauge.step_forward)


The routine extend referenced in the example above is a feature of a class in a graphical user interface (GUI) library to provide event-driven programming capabilities.

In other library classes, agents are seen to be used for different purposes. In a library supporting data structures, for example, a class modeling linear structures effects universal quantification
Universal quantification
In predicate logic, universal quantification formalizes the notion that something is true for everything, or every relevant thing....

 with a function for_all of type BOOLEAN which accepts an agent, an instance of FUNCTION, as an argument. So, in the following example, my_action is executed only if all members of my_list contain the character '!':


my_list: LINKED_LIST [STRING]
...
if my_list.for_all (agent {STRING}.has ('!')) then
my_action
end
...


When agents are created, the arguments to the routines they model and even the target object to which they are applied can be either closed or left open. Closed arguments and targets are given values at agent creation time. The assignment of values for open arguments and targets is deferred until some point after the agent is created. The routine for_all expects as an argument an agent representing a function with one open argument or target which conforms to actual generic parameter for the structure (STRING in this example.)

When the target of an agent is left open, the class name of the expected target, enclosed in braces, is substituted for an object reference as shown in the text agent {STRING}.has ('!') in the example above. When an argument is left open, the question mark character ('?') is coded as a placeholder for the open argument.

The ability to close or leave open targets and arguments is intended to improve the flexibility of the agent mechanism. Consider a class that contains the following procedure to print a string on standard output after a new line:


print_on_new_line (s: STRING)
-- Print `s' preceded by a new line
do
print ("%N" + s)
end


The following snippet, assumed to be in the same class, uses print_on_new_line to demonstrate the mixing of open arguments and open targets in agents used as arguments to the same routine.


my_list: LINKED_LIST [STRING]
...
my_list.do_all (agent print_on_new_line (?))
my_list.do_all (agent {STRING}.to_lower)
my_list.do_all (agent print_on_new_line (?))
...


This example uses the procedure do_all for linear structures, which executes the routine modeled by an agent for each item in the structure.

The sequence of three instructions prints the strings in my_list, converts the strings to lowercase, and then prints them again.

Procedure do_all iterates across the structure executing the routine substituting the current item for either the open argument (in the case of the agents based on print_on_new_line), or the open target (in the case of the agent based on to_lower).

Open and closed arguments and targets also allow the use of routines which call for more arguments than are required by closing all but the necessary number of arguments:


my_list.do_all (agent my_multi_arg_procedure (closed_arg_1, ?, closed_arg_2, closed_arg_3)


The Eiffel agent mechanism is detailed in the Eiffel ISO/ECMA standard document.
In Java
Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 has no first-class function
First-class function
In computer science, a programming language is said to have first-class functions if it treats functions as first-class objects. Specifically, this means that the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning...

s, so function objects are usually expressed by an interface with a single method (most commonly the Callable interface), typically with the implementation being an anonymous inner class
Inner class
In object-oriented programming , an inner class or nested class is a class declared entirely within the body of another class or interface. It is distinguished from a subclass.-Overview:...

.

For an example from Java's standard library, java.util.Collections.sort takes a List and a functor whose role is to compare objects in the List. But because Java does not have first-class functions, the function is part of the Comparator interface. This could be used as follows.


List list = Arrays.asList("10", "1", "20", "11", "21", "12");

Comparator numStringComparator = new Comparator {
public int compare(String o1, String o2) {
return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
}
};

Collections.sort(list, numStringComparator);

In JavaScript
In JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

, functions are first class objects. JavaScript also supports closures.

Compare the following with the subsequent Python example.

function Accumulator(start) {
var current = start;
return function (x) {
current += x;
return current;
};
}


An example of this in use:


var a = Accumulator(4);
var x = a(5); //x has value 9
x = a(2); //x has value 11

var b = Accumulator(42);
x = b(7); //x has value 49 (current=42 in closure b)
x = a(7); //x has value 18 (current=11 in closure a)

In Lisp and Scheme
In Common Lisp
Common Lisp
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...

, Scheme and other languages in the Lisp family, functions are objects, just like strings, vectors, lists, and numbers. A closure-constructing operator creates a function object from a piece of the program itself: the piece of code given as an argument to the operator is part of the function, and so is the lexical environment: the bindings of the lexically visible variables are "captured" and stored in the function object, which is more commonly called a closure
Closure (computer science)
In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...

. The captured bindings play the role of "member variables", and the code part of the closure plays the role of the "anonymous member function", just like operator in C++.

The closure constructor has the syntax (lambda (parameters ...) code ...). The (parameters ...) part allows an interface to be declared, so that the function takes the declared parameters. The code ... part consists of expressions that are evaluated when the functor is called.

Many uses of functors in languages like C++ are simply emulations of the missing closure constructor. Since the programmer cannot directly construct a closure, he or she must define a class which has all of the necessary state variables, and also a member function. Then, construct an instance of that class instead, ensuring that all the member variables are initialized through its constructor. The values are derived precisely from those local variables that ought to be captured directly by a closure.

A function-object using the class system, no use of closures:

(defclass counter
((value :initarg :value :accessor value-of)))

(defmethod functor-call ((c counter))
(incf (value-of c)))

(defun make-counter (initial-value)
(make-instance 'counter :value initial-value))
; use the counter

(defvar *c* (make-counter 10))
(functor-call *c*) --> 11
(functor-call *c*) --> 12

Since there is no standard way to make funcallable objects in Lisp, we fake it by defining a generic function called FUNCTOR-CALL. This can be specialized for any class whatsoever. The standard FUNCALL function is not generic; it only takes function objects.

It is this FUNCTOR-CALL generic function which gives us function objects, which are a computer programming construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax. We have almost the same syntax: FUNCTOR-CALL instead of FUNCALL. Some Lisps provide "funcallable" objects as a simple extension. Making objects callable using the same syntax as functions is a fairly trivial business. Making a function call operator work with different kinds of "function things", whether they be class objects or closures is no more complicated than making a + operator that works with different kinds of numbers, such as integers, reals or complex numbers.

Now, a counter implemented using a closure. This is much more brief and direct. The INITIAL-VALUE argument of the MAKE-COUNTER factory function is captured and used directly. It does not have to be copied into some auxiliary class object through a constructor. It is the counter. An auxiliary object is created, but that happens "behind the scenes".


(defun make-counter (value)
(lambda (incf value)))
; use the counte

(defvar *c* (make-counter 10))
(funcall *c*) ; --> 11
(funcall *c*) ; --> 12


Scheme makes closures even simpler, and Scheme code tends to use such higher-order programming somewhat more idiomatically.


(define (make-counter value)
(lambda (set! value (+ value 1)) value))
; use the counte

(define c (make-counter 10))
(c) ; --> 11
(c) ; --> 12


More than one closure can be created in the same lexical environment. A vector of closures, each implementing a specific kind of operation, can quite faithfully emulate an object that has a set of virtual operations. That type of single dispatch object-oriented programming can be done entirely with closures.

Thus there exists a kind of tunnel being dug from both sides of the proverbial mountain. Programmers in OOP languages discover function objects by restricting objects to have one "main" function to "do" that object's functional purpose, and even eliminate its name so that it looks like the object is being called! While programmers who use closures are not surprised that an object is called like a function, they discover that multiple closures sharing the same environment can provide a complete set of abstract operations like a virtual table for single dispatch type OOP.
In Objective-C
In Objective-C
Objective-C
Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it...

 a function object can be created from the NSInvocation class. Construction of a function object requires a method signature, the target object, and the target selector. Here is an example for creating an invocation to the current object's myMethod:

// Construct a function object
SEL sel = @selector(myMethod);
NSInvocation* inv = [NSInvocation invocationWithMethodSignature:
[self methodSignatureForSelector:sel]];
[inv setTarget:self];
[inv setSelector:sel];

// Do the actual invocation
[inv invoke];


An advantage of NSInvocation is that the target object can be modified after creation. A single NSInvocation can be created and then called for each of any number of targets, for instance from an observable object. An NSInvocation can be created from only a protocol, but it is not straightforward. See here.
In Perl
In Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

, a function object can be created either from a class's constructor returning a function closed over the object's instance data, blessed into the class:

package Acc1;
sub new {
my $class = shift;
my $arg = shift;
my $obj = sub {
my $num = shift;
$arg += $num;
};
bless $obj, $class;
}
1;

or by overloading the &{} operator so that the object can be used as a function:

package Acc2;
use overload
'&{}' =>
sub {
my $self = shift;
sub {
$num = shift;
$self->{arg} += $num;
}
};

sub new {
my $class = shift;
my $arg = shift;
my $obj = { arg => $arg };
bless $obj, $class;
}
1;


In both cases the function object can be used either using the dereferencing arrow syntax $ref->(@arguments):

use Acc1;
my $a = Acc1->new(42);
  1. prints '52'

print $a->(10), "\n";
  1. prints '60'

print $a->(8), "\n";

or using the coderef dereferencing syntax &$ref(@arguments):

use Acc2;
my $a = Acc2->new(12);
  1. prints '22'

print &$a(10), "\n";
  1. prints '30'

print &$a(8), "\n";

In PowerShell
In the Windows PowerShell
Windows PowerShell
Windows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework...

 programming language, a script block is a collection of statements or expressions that can be used as a single unit. A script block can accept arguments and return values. A script block is an instance of a Microsoft .NET Framework
.NET Framework
The .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allows language interoperability...

 type System.Management.Automation.ScriptBlock.


Function Get-Accumulator($x) {
{
param($y)
return $script:x += $y
}.GetNewClosure
}



PS C:\> $a = Get-Accumulator 4

PS C:\> & $a 5

9

PS C:\> & $a 2

11

PS C:\> $b = Get-Accumulator 32

PS C:\> & $b 10

42

In Python
In Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

, functions are first-class objects, just like strings, numbers, lists etc. This feature eliminates the need to write a function object in many cases. Any object with a __call__ method can be called using function-call syntax.

An example is this Accumulator class (based on Paul Graham's study on programming language syntax and clarity):


class Accumulator(object):
def __init__(self, n):
self.n = n
def __call__(self, x):
self.n += x
return self.n


An example of this in use (using the interactive interpreter):


>>> a = Accumulator(4)
>>> a(5)
9
>>> a(2)
11
>>> b = Accumulator(42)
>>> b(7)
49


A function object using a closure in Python 3:


def accumulator(n):
def inc(x):
nonlocal n
n += x
return n
return inc

In Ruby
In Ruby
Ruby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

, several objects can be considered function objects, in particular Method and Proc objects. Ruby also has two kinds of objects that can be thought of as semi-function objects: UnboundMethod and block. UnboundMethods must first be bound to an object (thus becoming a Method) before they can be used as a function object. Blocks can be called like function objects, but to be used in any other capacity as an object (e.g. passed as an argument) they must first be converted to a Proc. More recently, symbols (accessed via the literal unary indicator :) can also be converted to Procs. Using Ruby's unary & operator—equivalent to calling to_proc on an object, and assuming that method exists
Duck typing
In computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface...

—the Ruby Extensions Project created a simple hack.


class Symbol
def to_proc
proc { |obj, *args| obj.send(self, *args) }
end
end


Now, method foo can be a function object, i.e. a Proc, via &:foo and used via takes_a_functor(&:foo). Symbol.to_proc was officially added to Ruby on June 11, 2006 during RubyKaiga2006. http://redhanded.hobix.com/cult/symbolTo_procExonerated.html

Because of the variety of forms, the term Functor is not generally used in Ruby to mean a Function object. Rather it has come to represent a type of dispatch delegation
Delegation (programming)
In object-oriented programming, there are two related notions of delegation.* Most commonly, it refers to a programming language feature making use of the method lookup rules for dispatching so-called self-calls as defined by Lieberman in his 1986 paper "Using Prototypical Objects to Implement...

 introduced by the Ruby Facets project. The most basic definition of which is:


class Functor
def initialize(&func)
@func = func
end
def method_missing(op, *args, &blk)
@func.call(op, *args, &blk)
end
end


This usage is more akin to that used by functional programming languages, like ML, and the original mathematical terminology.
Other meanings
In a more theoretical context a function object may be considered to be any instance of the class of functions, especially in languages such as Common Lisp
Common Lisp
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...

 in which functions are first-class object
First-class object
In programming language design, a first-class citizen , in the context of a particular programming language, is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable...

s.

In some functional programming languages, such as ML and Haskell
Haskell (programming language)
Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...

, the term functor has a different meaning; it represents a mapping
Function (mathematics)
In mathematics, a function associates one quantity, the argument of the function, also known as the input, with another quantity, the value of the function, also known as the output. A function assigns exactly one output to each input. The argument and the value may be real numbers, but they can...

 from modules to modules, or from types to types and is a technique for reusing code. Functors used in this manner are analogous to the original mathematical meaning of functor
Functor
In category theory, a branch of mathematics, a functor is a special type of mapping between categories. Functors can be thought of as homomorphisms between categories, or morphisms when in the category of small categories....

 in category theory
Category theory
Category theory is an area of study in mathematics that examines in an abstract way the properties of particular mathematical concepts, by formalising them as collections of objects and arrows , where these collections satisfy certain basic conditions...

, or to the use of generic programming in C++, Java or Ada
Ada (programming language)
Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...

.

In Prolog
Prolog
Prolog is a general purpose logic programming language associated with artificial intelligence and computational linguistics.Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is declarative: the program logic is expressed in terms of...

 and related languages, functor is a synonym for function symbol.
See also

  • Callback (computer science)
    Callback (computer science)
    In computer programming, a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower-level software layer to call a subroutine defined in a higher-level layer....

  • Closure (computer science)
    Closure (computer science)
    In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...

  • Function pointer
    Function pointer
    A function pointer is a type of pointer in C, C++, D, and other C-like programming languages, and Fortran 2003. When dereferenced, a function pointer can be used to invoke a function and pass it arguments just like a normal function...

  • Higher-order function
    Higher-order function
    In mathematics and computer science, higher-order functions, functional forms, or functionals are functions which do at least one of the following:*take one or more functions as an input*output a function...

  • Command pattern
    Command pattern
    In object-oriented programming, the command pattern is a design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time...

  • Currying
    Currying
    In mathematics and computer science, currying is the technique of transforming a function that takes multiple arguments in such a way that it can be called as a chain of functions each with a single argument...


Further reading

  • David Vandevoorde & Nicolai M Josuttis (2006). C++ Templates: The Complete Guide, ISBN 0-201-73484-2 : Specifically, chapter 22 is entirely devoted to function objects.

External links
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK