HOME

TheInfoList



OR:

In
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as ana ...
, a function object is a construct allowing an
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
to be invoked or called as if it were an ordinary
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
, usually with the same syntax (a function parameter that can also be a function). Function objects are often called functors.


Description

A typical use of a function object is in writing
callback Callback may refer to: * Callback (comedy), a joke which refers to one previously told * Callback (computer programming), executable code that is passed as a parameter to other code * Callback (telecommunications), the telecommunications event th ...
functions. A callback in procedural languages, such as C, may be performed by using
function pointer A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function poin ...
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 A façade () (also written facade) is generally the front part or exterior of a building. It is a Loanword, loan word from the French language, French (), which means 'frontage' or 'face'. In architecture, the façade of a building is often t ...
for a full object, carrying its own state. Many modern (and some older) languages, e.g.
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
,
Eiffel Eiffel may refer to: Places * Eiffel Peak, a summit in Alberta, Canada * Champ de Mars – Tour Eiffel station, Paris, France; a transit station Structures * Eiffel Tower, in Paris, France, designed by Gustave Eiffel * Eiffel Bridge, Ungheni, M ...
,
Groovy ''Groovy'' (or, less commonly, ''groovie'' or ''groovey'') is a slang colloquialism popular during the 1950s, '60s and '70s. It is roughly synonymous with words such as "excellent", "fashionable", or "amazing", depending on context. History The ...
,
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
,
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
,
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
,
PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group. ...
,
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
,
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
, Scala, and many others, support
first-class function In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning them as the values from ...
objects and may even make significant use of them.
Functional programming In computer science, functional programming is a programming paradigm where programs are constructed by Function application, applying and Function composition (computer science), composing Function (computer science), functions. It is a declar ...
languages additionally support closures, i.e. first-class functions that can 'close over' variables in their surrounding environment at creation time. During compilation, a transformation known as
lambda lifting Lambda lifting is a meta-process that restructures a computer program so that functions are defined independently of each other in a global scope. An individual "lift" transforms a local function into a global function. It is a two step process ...
converts the closures into function objects.


In C and C++

Consider the example of a sorting routine that uses a callback function to define an ordering relation between a pair of items. The following C program uses function pointers: #include /* qsort() callback function, returns < 0 if a < b, > 0 if a > b, 0 if a

b */ int compareInts(const void* a, const void* b) ... // prototype of qsort is // void qsort(void *base, size_t nel, size_t width, int (*compar)(const void *, const void *)); ... int main(void)
In C++, a function object may be used instead of an ordinary function by defining a class that overloads the
function call operator This is a list of operators in the C and C++ programming languages. All the operators listed exist in C++; the column "Included in C", states whether an operator is also present in C. Note that C does not support operator overloading. When not ...
by defining an operator() member function. In C++, this may appear as follows: // comparator predicate: returns true if a < b, false otherwise struct IntComparator ; int main() Notice that the syntax for providing the callback to the std::sort() 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. Of course, this is just a trivial example. To understand what power a functor provides more than a regular function, consider the common use case of sorting objects by a particular field. In the following example, a functor is used to sort a simple employee database by each employee's ID number. struct CompareBy ; int main() In
C++11 C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by ...
, the lambda expression provides a more succinct way to do the same thing. int main() It is possible to use function objects in situations other than as callback functions. In this case, the shortened term ''functor'' is normally ''not'' used about the function object. Continuing the example, IntComparator cpm; bool result = cpm(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 Template may refer to: Tools * Die (manufacturing), used to cut or shape material * Mold, in a molding process * Stencil, a pattern or overlay used in graphic arts (drawing, painting, etc.) and sewing to replicate letters, shapes or designs ...
facilities. The expressiveness of templates allows some
functional programming In computer science, functional programming is a programming paradigm where programs are constructed by Function application, applying and Function composition (computer science), composing Function (computer science), functions. It is a declar ...
techniques to be used, such as defining function objects in terms of other function objects (like
function composition In mathematics, function composition is an operation that takes two functions and , and produces a function such that . In this operation, the function is applied to the result of applying the function to . That is, the functions and ...
). Much of the C++
Standard Template Library The Standard Template Library (STL) is a Library (computer science), software library originally designed by Alexander Stepanov for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components ...
(STL) makes heavy use of template-based function objects.


Maintaining state

Another advantage of function objects is their ability to maintain a state that affects operator() between calls. For example, the following code defines a
generator Generator may refer to: * Signal generator, electronic devices that generate repeating or non-repeating electronic signals * Electric generator, a device that converts mechanical energy to electrical energy. * Generator (circuit theory), an eleme ...
counting from 10 upwards and is invoked 11 times. #include #include #include class CountFrom ; int main() In C++14 or later, the example above could be rewritten as: #include #include #include int main()


In C#

In C#, function objects are declared via
delegate Delegate or delegates may refer to: * Delegate, New South Wales, a town in Australia * Delegate (CLI), a computer programming technique * Delegate (American politics), a representative in any of various political organizations * Delegate (Unit ...
s. A delegate can be declared using a named method or a lambda expression. Here is an example using a named method. using System; using System.Collections.Generic; public class ComparisonClass1 Here is an example using a lambda expression. using System; using System.Collections.Generic; public class ComparisonClass2


In D

D provides several ways to declare function objects: Lisp/Python-style via closures or C#-style via
delegate Delegate or delegates may refer to: * Delegate, New South Wales, a town in Australia * Delegate (CLI), a computer programming technique * Delegate (American politics), a representative in any of various political organizations * Delegate (Unit ...
s, respectively: bool find(T)(T[] haystack, bool delegate(T) needle_test) void main() The difference between a
delegate Delegate or delegates may refer to: * Delegate, New South Wales, a town in Australia * Delegate (CLI), a computer programming technique * Delegate (American politics), a representative in any of various political organizations * Delegate (Unit ...
and a closure in D is automatically and conservatively determined by the compiler. D also supports function literals, that allow a lambda-style definition: void main() To allow the compiler to inline the code (see above), function objects can also be specified C++-style via
operator overloading In computer programming, operator overloading, sometimes termed ''operator ad hoc polymorphism'', is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is ...
: bool find(T, F)(T[] haystack, F needle_test) void main()


In Eiffel

In the
Eiffel Eiffel may refer to: Places * Eiffel Peak, a summit in Alberta, Canada * Champ de Mars – Tour Eiffel station, Paris, France; a transit station Structures * Eiffel Tower, in Paris, France, designed by Gustave Eiffel * Eiffel Bridge, Ungheni, M ...
software development method and language, operations and objects are seen always as separate concepts. However, the
agent Agent may refer to: Espionage, investigation, and law *, spies or intelligence officers * Law of agency, laws involving a person authorized to act on behalf of another ** Agent of record, a person with a contractual agreement with an insuranc ...
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 that 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 In computer programming, event-driven programming is a programming paradigm in which the flow of the program is determined by events such as user actions ( mouse clicks, key presses), sensor outputs, or message passing from other programs or t ...
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 In mathematical logic, a universal quantification is a type of quantifier, a logical constant which is interpreted as "given any" or "for all". It expresses that a predicate can be satisfied by every member of a domain of discourse. In other w ...
with a function for_all of type BOOLEAN that 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
TRING Tring is a market town and civil parish in the Borough of Dacorum, Hertfordshire, England. It is situated in a gap passing through the Chiltern Hills, classed as an Area of Outstanding Natural Beauty, from Central London. Tring is linked to ...
... if my_list.for_all (agent .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 that 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 .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
TRING Tring is a market town and civil parish in the Borough of Dacorum, Hertfordshire, England. It is situated in a gap passing through the Chiltern Hills, classed as an Area of Outstanding Natural Beauty, from Central London. Tring is linked to ...
... my_list.do_all (agent print_on_new_line (?)) my_list.do_all (agent .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 that 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 th
Eiffel ISO/ECMA standard document


In Java

Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
has no
first-class function In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning them as the values from ...
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 In object-oriented programming (OOP), 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 An instance of a normal or top-level class can exist on ...
, or, starting in Java 8, a
lambda Lambda (}, ''lám(b)da'') is the 11th letter of the Greek alphabet, representing the voiced alveolar lateral approximant . In the system of Greek numerals, lambda has a value of 30. Lambda is derived from the Phoenician Lamed . Lambda gave rise ...
. 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. Without 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() ; Collections.sort(list, numStringComparator); In Java 8+, this can be written as: List list = Arrays.asList("10", "1", "20", "11", "21", "12"); Comparator numStringComparator = (str1, str2) -> Integer.valueOf(str1).compareTo(Integer.valueOf(str2)); Collections.sort(list, numStringComparator);


In JavaScript

In
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
, functions are first class objects. JavaScript also supports closures. Compare the following with the subsequent Python example. function Accumulator(start) 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 = 49 in closure b) x = a(7); // x has value 18 (current = 18 in closure a)


In Julia

In
Julia Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio and Julius. (For further details on etymology, see the Wiktionary entry "Julius".) The given name ''Julia'' had been in use throughout Late Antiquity (e.g ...
, methods are associated with types, so it is possible to make any arbitrary Julia object "callable" by adding methods to its type. (Such "callable" objects are sometimes called "functors.") An example is this accumulator mutable struct (based on Paul Graham's study on programming language syntax and clarity): julia> mutable struct Accumulator n::Int end julia> function (acc::Accumulator)(n2) acc.n += n2 end julia> a = Accumulator(4) Accumulator(4) julia> a(5) 9 julia> a(2) 11 julia> b = Accumulator(42) Accumulator(42) julia> b(7) 49 Such an accumulator can also be implemented using closure: julia> function Accumulator(n0) n = n0 function(n2) n += n2 end end Accumulator (generic function with 1 method) julia> a = Accumulator(4) (::#1) (generic function with 1 method) julia> a(5) 9 julia> a(2) 11 julia> b = Accumulator(42) (::#1) (generic function with 1 method) julia> b(7) 49


In Lisp and Scheme

In Lisp family languages such as
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
,
Scheme A scheme is a systematic plan for the implementation of a certain idea. Scheme or schemer may refer to: Arts and entertainment * ''The Scheme'' (TV series), a BBC Scotland documentary series * The Scheme (band), an English pop band * ''The Schem ...
, and others, functions are objects, just like strings, vectors, lists, and numbers. A closure-constructing operator creates a ''function object'' from a part of the program: the part 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. 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, they must define a class that 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 that 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 counter (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 counter (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 In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented ...
object-oriented programming can be done fully 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 In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented ...
type OOP.


In Objective-C

In
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
, 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 = SInvocation 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. Se
here


In Perl

In
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
, 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 1; or by overloading the & operator so that the object can be used as a function: package Acc2; use overload '&' => sub ; sub new 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); print $a->(10), "\n"; # prints 52 print $a->(8), "\n"; # prints 60 or using the coderef dereferencing syntax ''&$ref(@arguments)'': use Acc2; my $a = Acc2->new(12); print &$a(10), "\n"; # prints 22 print &$a(8), "\n"; # prints 30


In PHP

PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group. ...
5.3+ has
first-class function In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning them as the values from ...
s that can be used e.g. as parameter to the usort() function: $a = array(3, 1, 4); usort($a, function ($x, $y) );
PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group. ...
5.3+, supports also lambda functions and closures. function Accumulator($start) An example of this in use: $a = Accumulator(4); $x = $a(5); echo "x = $x
"; // x = 9 $x = $a(2); echo "x = $x
"; // x = 11
It is also possible in PHP 5.3+ to make objects invokable by adding a magic __invoke() method to their class:PHP Documentation on Magic Methods
/ref> class Minus $a = array(3, 1, 4); usort($a, new Minus());


In PowerShell

In the
Windows PowerShell PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell and the associated scripting language. Initially a Windows component only, known as Windows PowerShell, it was made open-so ...
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 The .NET Framework (pronounced as "''dot net"'') is a proprietary software framework developed by Microsoft that runs primarily on Microsoft Windows. It was the predominant implementation of the Common Language Infrastructure (CLI) until bein ...
type System.Management.Automation.ScriptBlock. Function Get-Accumulator($x) 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 may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
, 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: def __init__(self, n) -> None: 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 Since functions are objects, they can also be defined locally, given attributes, and returned by other functions, Python reference manual - Function definitions
/ref> as demonstrated in the following example: def Accumulator(n): def inc(x): nonlocal n n += x return n return inc


In Ruby

In
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
, 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—the Ruby Extensions Projectbr>created a simple hack.
class Symbol def to_proc proc 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 RubyKaigi2006

Because of the variety of forms, the term Functor is not generally used in Ruby to mean a Function object. Just a type of dispatch delegation introduced by th
Ruby Facets
project is named as Functor. 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 (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
in which functions are
first-class object In programming language design, a first-class citizen (also type, object, entity, or value) in a given programming language is an entity which supports all the operations generally available to other entities. These operations typically include ...
s. The ML family of
functional programming In computer science, functional programming is a programming paradigm where programs are constructed by Function application, applying and Function composition (computer science), composing Function (computer science), functions. It is a declar ...
languages uses the term ''functor'' to represent a mapping 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 In mathematics, specifically category theory, a functor is a Map (mathematics), mapping between Category (mathematics), categories. Functors were first considered in algebraic topology, where algebraic objects (such as the fundamental group) ar ...
in
category theory Category theory is a general theory of mathematical structures and their relations that was introduced by Samuel Eilenberg and Saunders Mac Lane in the middle of the 20th century in their foundational work on algebraic topology. Nowadays, cate ...
, or to the use of generic programming in C++, Java or
Ada Ada may refer to: Places Africa * Ada Foah, a town in Ghana * Ada (Ghana parliament constituency) * Ada, Osun, a town in Nigeria Asia * Ada, Urmia, a village in West Azerbaijan Province, Iran * Ada, Karaman, a village in Karaman Province, ...
. In
Haskell Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
, the term ''
functor In mathematics, specifically category theory, a functor is a Map (mathematics), mapping between Category (mathematics), categories. Functors were first considered in algebraic topology, where algebraic objects (such as the fundamental group) ar ...
'' is also used for a concept related to the meaning of ''functor'' in category theory. In
Prolog Prolog is a 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 intended primarily ...
and related languages, ''functor'' is a synonym for
function symbol In formal logic and related branches of mathematics, a functional predicate, or function symbol, is a logical symbol that may be applied to an object term to produce another object term. Functional predicates are also sometimes called mappings, but ...
.


See also

*
Callback (computer science) In computer programming, a callback or callback function is any reference to executable code that is passed as an argument to another piece of code; that code is expected to ''call back'' (execute) the callback function as part of its job. Thi ...
*
Closure (computer science) In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function toge ...
*
Function pointer A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function poin ...
* Higher-order function *
Command pattern In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name ...
*
Currying In mathematics and computer science, currying is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument. For example, currying a function f that ...


Notes


References


Further reading

* David Vandevoorde & Nicolai M Josuttis (2006). ''C++ Templates: The Complete Guide'', : Specifically, chapter 22 is devoted to function objects.


External links


Description from the Portland Pattern Repository

C++ Advanced Design Issues - Asynchronous C++
by
Kevlin Henney Kevlin Henney is an English author, presenter, and consultant on software development. He has written on the subject of computer programming and development practice for many magazines and sites, including ''Better Software'', ''The Register'', ' ...

The Function Pointer Tutorials
by Lars Haendel (2000/2001) * Article
Generalized Function Pointers
by
Herb Sutter Herb Sutter is a prominent C++ expert. He is also a book author and was a columnist for Dr. Dobb's Journal. He joined Microsoft in 2002 as a platform evangelist for Visual C++ .NET, rising to lead software architect for C++/CLI. Sutter has ser ...

Generic Algorithms for Java

PHP Functors - Function Objects in PHP


(C++ FAQ) {{DEFAULTSORT:Function Object Object (computer science) Subroutines Articles with example C code Articles with example C++ code Articles with example Java code Articles with example Julia code Articles with example Perl code Articles with example Python (programming language) code Articles with example Ruby code