It has been suggested that this article be merged into First-class object. (Discuss) Proposed since February 2007. |
In computer science, a programming language is said to support first-class functions if it treats functions as first-class objects. Specifically, this means that functions can be created during the execution of a program, stored in data structures, passed as arguments to other functions, and returned as the values of other functions.
These features are a necessity for the functional programming style, in which (for instance) the use of higher-order functions is a standard practice. A simple example of a higher-ordered function is the map or mapcar 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 and returning them as results. Historically, these were termed the funarg problems, the name coming from "function argument". A different set of difficulties arises when programs can create functions at runtime; if the program is compiled, this means that the runtime environment must itself include a compiler.
Availability
Languages which are strongly associated with functional programming, such as Lisp, Scheme, ML, and Haskell, all support first-class functions. Other languages which also support them include Io, Python, ECMAScript (JavaScript), Lua, Ruby and Scala. Also Perl supports first-class functions (passed using references to them).
The modern, natively compiled programming languages support functions defined statically at compile time. Most of them, e.g. C and Pascal, additionally support function pointers, which can be stored in data structures and passed as arguments to other functions. Nevertheless, they are not considered to support first class functions, since, in general, functions cannot be created dynamically during the execution of a program. The closest analog would be a dynamically compiled function created by a just-in-time compiler, which is compiled as an array of machine language instructions in memory and then cast to a function pointer. However, this technique is specific to the underlying hardware architecture and is, therefore, neither general nor portable.
See also