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 other functions, and assigning them to variables or storing them in data structures.[1] Some programming language theorists require support for anonymous functions (function literals) as well.[2] In languages with first-class functions, the names of functions do not have any special status; they are treated like ordinary variables with a function type.[3] The term was coined by Christopher Strachey in the context of "functions as first-class citizens" in the mid-1960s.[4]
First-class functions are a necessity for the functional programming style, in which the use of higher-order functions is a standard practice. A simple example of a higher-ordered function is the map function, which takes, as its arguments, a function and a list, and returns the list formed by applying the function to each member of the list. For a language to support map, it must support passing a function as an argument.
There are certain implementation difficulties in passing functions as arguments or returning them as results, especially in the presence of non-local variables introduced in nested and anonymous functions. Historically, these were termed the funarg problems, the name coming from "function argument".[5] In early imperative languages these problems were avoided by either not supporting functions as result types (e.g. ALGOL 60, Pascal) or omitting nested functions and thus non-local variables (e.g. C). The early functional language Lisp took the approach of dynamic scoping, where non-local variables refer to the closest definition of that variable at the point where the function is executed, instead of where it was defined. Proper support for lexically scoped first-class functions was introduced in Scheme and requires handling references to functions as closures instead of bare function pointers,[4] which in turn makes garbage collection a necessity.
In this section, we compare how particular programming idioms are handled in a functional language with first-class functions (Haskell) compared to an imperative language where functions are second-class citizens (C).
In languages where functions are first-class citizens, functions can be passed as arguments to other functions in the same way as other values (a function taking another function as argument is called a higher-order function). In the language Haskell:
Languages where functions are not first-class often still allow one to write higher-order functions through the use of features such as function pointers or delegates. In the language C:
There are a number of differences between the two approaches that are not directly related to the support of first-class functions. The Haskell sample operates on lists, while the C sample operates on arrays. Both are the most natural compound data structures in the respective languages and making the C sample operate on linked lists would have made it unnecessarily complex. This also accounts for the fact that the C function needs an additional parameter (giving the size of the array.) The C function updates the array in-place, returning no value, whereas in Haskell data structures are persistent (a new list is returned while the old is left intact.) The Haskell sample uses recursion to traverse the list, while the C sample uses iteration. Again, this is the most natural way to express this function in both languages, but the Haskell sample could easily have been expressed in terms of a fold and the C sample in terms of recursion. Finally, the Haskell function has a polymorphic type, as this is not supported by C we have fixed all type variables to the type constant int
.
In languages supporting anonymous functions, we can pass such a function as an argument to a higher-order function:
In a language which does not support anonymous functions, we have to bind it to a name instead:
int main
Once we have anonymous or nested functions, it becomes natural for them to refer to variables outside of their body (called non-local variables):
If functions are represented with bare function pointers, we can not know anymore how the value that is outside of the function's body should be passed to it, and because of that a closure needs to be built manually. Therefore we can not speak of "first-class" functions here.
void map(closure_t *closure, int x[], size_t n)
int f(int a, int b, int x)
void main
Also note that the map
is now specialized to functions referring to two int
s outside of their environment. This can be set up more generally, but requires more boilerplate code. If f
would have been a nested function we would still have run into the same problem and this is the reason they are not supported in C.[6]
When returning a function, we are in fact returning its closure. In the C example any local variables captured by the closure will go out of scope once we return from the function that builds the closure. Forcing the closure at a later point will result in undefined behaviour, possibly corrupting the stack. This is known as the upwards funarg problem.
Assigning functions to variables and storing them inside (global) datastructures potentially suffers from the same difficulties as returning functions.
As one can test most literals and values for equality, it is natural to ask whether a programming language can support testing functions for equality. On further inspection, this question appears more difficult and one has to distinguish between several types of function equality:[7]
See main article: Function type. In type theory, the type of functions accepting values of type A and returning values of type B may be written as A → B or BA. In the Curry–Howard correspondence, function types are related to logical implication; lambda abstraction corresponds to discharging hypothetical assumptions and function application corresponds to the modus ponens inference rule. Besides the usual case of programming functions, type theory also uses first-class functions to model associative arrays and similar data structures.
In category-theoretical accounts of programming, the availability of first-class functions corresponds to the closed category assumption. For instance, the simply typed lambda calculus corresponds to the internal language of Cartesian closed categories.
Functional programming languages, such as Erlang, Scheme, ML, Haskell, F#, and Scala, all have first-class functions. When Lisp, one of the earliest functional languages, was designed, not all aspects of first-class functions were then properly understood, resulting in functions being dynamically scoped. The later Scheme and Common Lisp dialects do have lexically scoped first-class functions.
Many scripting languages, including Perl, Python, PHP, Lua, Tcl/Tk, JavaScript and Io, have first-class functions.
For imperative languages, a distinction has to be made between Algol and its descendants such as Pascal, the traditional C family, and the modern garbage-collected variants. The Algol family has allowed nested functions and higher-order taking function as arguments, but not higher-order functions that return functions as results (except Algol 68, which allows this). The reason for this was that it was not known how to deal with non-local variables if a nested-function was returned as a result (and Algol 68 produces runtime errors in such cases).
The C family allowed both passing functions as arguments and returning them as results, but avoided any problems by not supporting nested functions. (The gcc compiler allows them as an extension.) As the usefulness of returning functions primarily lies in the ability to return nested functions that have captured non-local variables, instead of top-level functions, these languages are generally not considered to have first-class functions.
Modern imperative languages often support garbage-collection making the implementation of first-class functions feasible. First-class functions have often only been supported in later revisions of the language, including C# 2.0 and Apple's Blocks extension to C, C++, and Objective-C. C++11 has added support for anonymous functions and closures to the language, but because of the non-garbage collected nature of the language, special care has to be taken for non-local variables in functions to be returned as results (see below).
Language | Higher-order functions | Nested functions | Non-local variables | Notes | ||||
---|---|---|---|---|---|---|---|---|
Arguments | Results | Named | Partial application | |||||
Algol family | Have function types. | |||||||
[8] | [9] | |||||||
C family | Has function pointers. | |||||||
[10] | Has function pointers, function objects. (Also, see below.)Explicit partial application possible with std::bind . | |||||||
Has delegates (2.0) and lambda expressions (3.0). | ||||||||
Has function pointers. | ||||||||
Has anonymous inner classes. | ||||||||
[11] | ||||||||
[12] | ||||||||
Functional languages | (see below) | |||||||
[13] | ||||||||
Scripting languages | ||||||||
Partial application possible with user-land code on ES3 [14] | ||||||||
[15] | ||||||||
Partial application possible with user-land code. | ||||||||
[16] | ||||||||
[17] | (see below) | |||||||
(see below) | ||||||||
Other languages | ||||||||
[18] | Partial application possible by automatic generation of new functions.[19] | |||||||
Partial application possible through library. | ||||||||
function
must be used to retrieve the function as a value: (function foo)
evaluates to a function object. #'foo
exists as a shorthand notation. To apply such a function object, one must use the funcall
function: (funcall #'foo bar baz)
.[https://docs.python.org/library/functools.html#functools.partial functools.partial]
since version 2.5, and [https://docs.python.org/library/operator.html#operator.methodcaller operator.methodcaller]
since version 2.6.Method
or Proc
object to be used as first-class data. The syntax for calling such a function object differs from calling regular methods.
[http://www.ruby-doc.org/core-1.9.3/Proc.html#method-i-curry]
.