Anonymous function
Encyclopedia
In programming language theory
, an anonymous function (also function constant or function literal) is a function
(or a subroutine
) 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 function
s such as Haskell
. Anonymous functions are a form of nested function
, in that they allow access to the variable in the scope of the containing function (non-local variable
s). Unlike named nested functions, they cannot be recursive
without the assistance of a fixpoint operator (also known as an anonymous fixpoint or anonymous recursion).
Anonymous functions originate in the work of Alonzo Church
in his invention of the lambda calculus
in 1936 (prior to electronic computers), in which all functions are anonymous. The Y combinator
can be utilised in these circumstances to provide anonymous recursion, which Church used to show that some mathematical questions are unsolvable by computation. (Note: this result was disputed at the time, and later Alan Turing
- who became Church's student - provided a proof that was more generally accepted.)
Anonymous functions have been a feature of programming language
s since Lisp in 1958. An increasing number of modern programming languages support anonymous functions, and some notable mainstream languages have recently added support for them, the most widespread being JavaScript
. C# and PHP
also support anonymous functions. Anonymous functions were added to the C++ language as of C++11.
Some object-oriented programming
languages have anonymous classes, which are a similar concept, but do not support anonymous functions. Java
is such a language.
s and currying
.
All of the code in the following sections is written in Python
2.x (not 3.x).
Most languages provide a generic sort function that implements a sort algorithm that will sort arbitrary objects.
This function usually accepts an arbitrary comparison function that is supplied two items and the function indicates if they are equal or if one is "greater" or "less" than the other (typically indicated by returning a negative number, zero, or a positive number).
Consider sorting items in a list by the name of their class (in Python, everything has a class):
Note that
The anonymous function in this example is the lambda expression:
The anonymous function accepts two arguments,
Another example would be sorting a list of strings by length of the string:
which clearly has been sorted by length of the strings.
This can be used as a sort of generator of comparison functions:
It would be very impractical to create a function for every possible comparison function and may be too inconvenient to keep the threshold around for further use. Regardless of the reason why a closure is used, the anonymous function is the entity that contains the functionality that does the comparing.
While the use of anonymous functions is perhaps not common with currying it still can be used. In the above example, the function divisor generates functions with a specified divisor. The functions half and third curry the divide function with a fixed divisor.
(It just so happens that the divisor function forms a closure as well as curries by binding the "d" variable.)
The anonymous function accepts an argument and multiplies it by itself (squares it).
The anonymous function checks if the argument passed to it is even.
This performs:
The anonymous function here is simply the multiplication of the two arguments.
However, there is no reason why the result of a fold need be a single value - in fact, both map and filter can be created using fold. In map, the value that is accumulated is a new list, containing the results of applying a function to each element of the original list. In filter, the value that is accumulated is a new list containing only those elements that match the given condition.
List of languages
The following is a list of programming language
s that fully support unnamed anonymous functions; support some variant of anonymous functions; and have no support for anonymous functions.
This table shows some general trends. First, the languages that do not support anonymous functions—C
, Pascal
, Object Pascal
, Java
—are all conventional statically-typed languages. This does not, however, mean that statically-typed languages are incapable of supporting anonymous functions. For example, the ML languages are statically typed and fundamentally include anonymous functions, and Delphi, a dialect of Object Pascal, has been extended to support anonymous functions. Second, the languages that treat functions as first-class function
s—Dylan, JavaScript
, Lisp, Scheme, ML, Haskell
, Python
, Ruby
, Perl
—generally have anonymous function support so that functions can be defined and passed around as easily as other data types. However, the new C++11 standard adds them to C++, even though this is conventional, statically typed language.
. See the C# 4.0 Language Specification, section 5.3.3.29, for more information.
While the function is anonymous, it cannot be assigned to an implicitly typed variable, because the lambda syntax may be used to denote an anonymous function or an expression tree, and the choice cannot automatically be decided by the compiler. E.g., this does not work:
However, a lambda expression can take part in type inference and can be used as a method argument
, e.g. to use anonymous functions with the Map capability available with
Prior versions of C# had more limited support for anonymous functions.
C# v1.0, introduced in February 2002 with the .NET Framework v1.0, provided partial anonymous function support through the use of delegates
. This construct is somewhat similar to PHP delegates. In C# 1.0, Delegates are like function pointers that refer to an explicitly named method within a class. (But unlike PHP the name is not required at the time the delegate is used.) C# v2.0, released in November 2005 with the .NET Framework v2.0, introduced the concept of anonymous methods as a way to write unnamed inline statement blocks that can be executed in a delegate invocation. C# 3.0 continues to support these constructs, but also supports the lambda expression construct.
This example will compile in C# 3.0, and exhibits the three forms:
In the case of the C# 2.0 version, the C# compiler takes the code block of the anonymous function and creates a static private function. Internally, the function gets a generated name, of course; this generated name is based on the name of the method in which the Delegate is declared. But the name is not exposed to application code except by using reflection
.
In the case of the C# 3.0 version, the same mechanism applies.
The return type of this unnamed function is
The return type can be explicitly specified as follows:
In this example, a temporary variable,
A lambda function can refer to identifiers declared outside the lambda function. The set of these variables is commonly called a closure
. Closures are defined between square brackets
The following two examples demonstrate usage of a lambda expression:
This computes the total of all elements in the list. The variable
This will cause
The capture of
If
The specific internal implementation can vary, but the expectation is that a lambda function that captures everything by reference will store the actual stack pointer of the function it is created in, rather than individual references to stack variables. However, because most lambda functions are small and local in scope, they are likely candidates for inlining
, and thus will not need any additional storage for references.
If a closure object containing references to local variables is invoked after the innermost block scope of its creation, the behaviour is undefined
.
Lambda functions are function objects of an implementation-dependent type; this type's name is only available to the compiler. If the user wishes to take a lambda function as a parameter, the type must be a template type, or it must create a
A lambda function with an empty capture specification (
uses a concise syntax for anonymous functions (lambda expressions).
Lambda expressions are fully integrated with the type inference engine, and support all the syntax and features of "ordinary" functions (except for the use of multiple definitions for pattern-matching, since the argument list is only specified once).
The following are all equivalent:
supports anonymous functions.
This construct is often used in Bookmarklet
s. For example, to change the title of the current document (visible in its window's title bar
) to its URL, the following bookmarklet may seem to work.
However, as the assignment statement returns a value (the URL itself), many browsers actually create a new page to display this value.
Instead, an anonymous function can be used so that no value is returned:
The function statement in the first (outer) pair of parentheses declares an anonymous function, which is then executed when used with the last pair of parentheses. This is equivalent to the following.
. Clojure
supports anonymous functions with the "fn" special form and # reader syntax.
Interestingly, Scheme's "named functions" is simply syntactic sugar
for anonymous functions bound to names:
expands (and is equivalent) to
Clojure
supports anonymous functions through the "fn" special form:
There is also a reader syntax to define a lambda:
Like Scheme, Clojure's "named functions" are simply syntactic sugar for lambdas bound to names:
expands to:
uses the following syntax for anonymous predicates (lambda expressions):
A simple example with no free variables and using a list mapping predicate is:
Currying is also supported. The above example can be written as:
Thus, in Lua
is just syntactical sugar for
An example of using anonymous functions for reverse-order sorting:
Objective Caml
:
Standard ML
:
Other constructs take "bare blocks" as arguments, which serve a function similar to lambda functions of a single parameter, but don't have the same parameter-passing convention as functions -- @_ is not set.
, all blocks (even the ones associated with if, while, etc.) are anonymous functions. A block that is not used as an rvalue
is executed immediately.
It is important to note that the argument list and function body must be in single quotes or the dollar signs must be escaped.
Otherwise PHP will assume "
For functions with quotes or functions with lots of variables, it can get quite tedious to ensure the intended function body is what PHP interprets.
Lambda functions are a compiler "trick" that instantiates a new
In this example,
PHP 5.3 mimics anonymous functions but it does not support true anonymous functions because PHP functions are still not first-class objects.
PHP 5.3 does support closures but the variables must be explicitly indicated as such:
The variable
supports simple anonymous functions through the lambda form. The executable body of the lambda must be an expression and can't be a statement, which is a restriction that limits its utility. The value returned by the lambda is the value of the contained expression. Lambda forms can be used anywhere ordinary functions can, however these restrictions make it a very limited version of a normal function. Here is an example:
This example will print: 100.
In general, Python convention encourages the use of named functions defined in the same scope as one might typically use an anonymous functions in other languages. This is acceptable as locally defined functions implement the full power of closure
s and are almost as efficient as the use of a lambda in Python. In this example, the built-in power function can be said to have been curried
:
In certain contexts, such as when an anonymous function is passed as a parameter to another function, the compiler can infer the types of the parameters of the anonymous function and they can be omitted in the syntax. In such contexts, it is also possible to use a shorthand for anonymous functions using the underscore character to introduce unnamed parameters.
anonymous functions are called blocks
9, introduced in November 2007, supports anonymous functions through the lambda form. Combined with implicit typing, VB provides an economical syntax for anonymous functions. As with Python, in VB9, anonymous functions must be defined on a single line; they cannot be compound statements. Further, an anonymous function in VB must truly be a VB "
VB10, released April 12, 2010, adds support for multiline lambda expressions and anonymous functions without a return value. For example, a function for use in a Thread.
in version 7.2. Anonymous predicates can capture values from the context. If created in an object member it can also access the object state (by capturing
Additionally, Mathematica has an additional construct to for making recursive anonymous functions. The symbol '#0' refers to the entire function.
Programming language theory
Programming language theory is a branch of computer science that deals with the design, implementation, analysis, characterization, and classification of programming languages and their individual features. It falls within the discipline of computer science, both depending on and affecting...
, an anonymous function (also function constant or function literal) is a function
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...
(or a subroutine
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....
) defined, and possibly called, without being bound
Name binding
In programming languages, name binding is the association of objects with identifiers. An identifier bound to an object is said to reference that object. Machine languages have no built-in notion of identifiers, but name-object bindings as a service and notation for the programmer is implemented...
to an identifier
Identifier
An identifier is a name that identifies either a unique object or a unique class of objects, where the "object" or class may be an idea, physical [countable] object , or physical [noncountable] substance...
. Anonymous functions are convenient to pass as an argument to a 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...
and are ubiquitous in languages with 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 such as Haskell
Haskell
Haskell may refer to:*Haskell , a standardized pure functional programming language with non-strict semantics* Haskell Indian Nations University, a four year degree granting university in Lawrence, Kansas which offers free tuition to members of registered Native American tribes in the United...
. Anonymous functions are a form of nested function
Nested function
In computer programming, a nested function is a function which is lexically encapsulated within another function. It can only be called by the enclosing function or by functions directly or indirectly nested within the same enclosing function. In other words, the scope of the nested function is...
, in that they allow access to the variable in the scope of the containing function (non-local variable
Non-local variable
In programming language theory, a non-local variable is a variable that is not defined in the local scope. While the term can refer to global variables, it is primarily used in the context of nested and anonymous functions where some variables can be neither in the local nor the global scope.-...
s). Unlike named nested functions, they cannot be recursive
Recursion (computer science)
Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem. The approach can be applied to many types of problems, and is one of the central ideas of computer science....
without the assistance of a fixpoint operator (also known as an anonymous fixpoint or anonymous recursion).
Anonymous functions originate in the work of Alonzo Church
Alonzo Church
Alonzo Church was an American mathematician and logician who made major contributions to mathematical logic and the foundations of theoretical computer science. He is best known for the lambda calculus, Church–Turing thesis, Frege–Church ontology, and the Church–Rosser theorem.-Life:Alonzo Church...
in his invention of the lambda calculus
Lambda calculus
In mathematical logic and computer science, lambda calculus, also written as λ-calculus, is a formal system for function definition, function application and recursion. The portion of lambda calculus relevant to computation is now called the untyped lambda calculus...
in 1936 (prior to electronic computers), in which all functions are anonymous. The Y combinator
Y Combinator
Y Combinator is an American seed-stage startup funding firm, started in March 2005. Y Combinator provides seed money, advice, and connections at two 3-month programs per year...
can be utilised in these circumstances to provide anonymous recursion, which Church used to show that some mathematical questions are unsolvable by computation. (Note: this result was disputed at the time, and later Alan Turing
Alan Turing
Alan Mathison Turing, OBE, FRS , was an English mathematician, logician, cryptanalyst, and computer scientist. He was highly influential in the development of computer science, providing a formalisation of the concepts of "algorithm" and "computation" with the Turing machine, which played a...
- who became Church's student - provided a proof that was more generally accepted.)
Anonymous functions have been a feature of programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....
s since Lisp in 1958. An increasing number of modern programming languages support anonymous functions, and some notable mainstream languages have recently added support for them, the most widespread being 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....
. C# and 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...
also support anonymous functions. Anonymous functions were added to the C++ language as of C++11.
Some object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...
languages have anonymous classes, which are a similar concept, but do not support anonymous functions. 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...
is such a language.
Uses
Anonymous functions can be used to contain functionality that need not be named and possibly for short-term use. Some notable examples include closureClosure (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...
s and 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...
.
All of the code in the following sections is written 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...
2.x (not 3.x).
Sorting
When attempting to sort in a non-standard way it may be easier to contain the comparison logic as an anonymous function instead of creating a named function.Most languages provide a generic sort function that implements a sort algorithm that will sort arbitrary objects.
This function usually accepts an arbitrary comparison function that is supplied two items and the function indicates if they are equal or if one is "greater" or "less" than the other (typically indicated by returning a negative number, zero, or a positive number).
Consider sorting items in a list by the name of their class (in Python, everything has a class):
Note that
10.0
has class name "float
", 10
has class name "int
", and '10'
has class name "str
". The sorted order is "float
", "int
", then "str
".The anonymous function in this example is the lambda expression:
The anonymous function accepts two arguments,
x
and y
, and returns the comparison between them using the built-in function cmp
.Another example would be sorting a list of strings by length of the string:
which clearly has been sorted by length of the strings.
Closures
Closures are functions evaluated in an environment containing bound variables. The following example binds the variable "threshold" in an anonymous function that compares the input to the threshold.This can be used as a sort of generator of comparison functions:
It would be very impractical to create a function for every possible comparison function and may be too inconvenient to keep the threshold around for further use. Regardless of the reason why a closure is used, the anonymous function is the entity that contains the functionality that does the comparing.
Currying
Currying is transforming a function from multiple inputs to fewer inputs (in this case integer division).While the use of anonymous functions is perhaps not common with currying it still can be used. In the above example, the function divisor generates functions with a specified divisor. The functions half and third curry the divide function with a fixed divisor.
(It just so happens that the divisor function forms a closure as well as curries by binding the "d" variable.)
Map
The map function performs a function call on each element of an array. The following example squares every element in an array with an anonymous function.The anonymous function accepts an argument and multiplies it by itself (squares it).
Filter
The filter function returns all elements from a list that evaluate True when passed to a certain function.The anonymous function checks if the argument passed to it is even.
Fold
The fold/reduce function runs over all elements in a list (usually left-to-right), accumulating a value as it goes. A common usage of this is to combine all elements of a list into a single value, for example:This performs:
The anonymous function here is simply the multiplication of the two arguments.
However, there is no reason why the result of a fold need be a single value - in fact, both map and filter can be created using fold. In map, the value that is accumulated is a new list, containing the results of applying a function to each element of the original list. In filter, the value that is accumulated is a new list containing only those elements that match the given condition.
List of languages
The following is a list of programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....
s that fully support unnamed anonymous functions; support some variant of anonymous functions; and have no support for anonymous functions.
This table shows some general trends. First, the languages that do not support anonymous functions—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....
, Pascal
Pascal (programming language)
Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal...
, Object Pascal
Object Pascal
Object Pascal refers to a branch of object-oriented derivatives of Pascal, mostly known as the primary programming language of Embarcadero Delphi.-Early history at Apple:...
, 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...
—are all conventional statically-typed languages. This does not, however, mean that statically-typed languages are incapable of supporting anonymous functions. For example, the ML languages are statically typed and fundamentally include anonymous functions, and Delphi, a dialect of Object Pascal, has been extended to support anonymous functions. Second, the languages that treat functions as 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—Dylan, 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....
, Lisp, Scheme, ML, 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...
, 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...
, 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...
—generally have anonymous function support so that functions can be defined and passed around as easily as other data types. However, the new C++11 standard adds them to C++, even though this is conventional, statically typed language.
Language | Support | Notes |
---|---|---|
ActionScript ActionScript ActionScript is an object-oriented language originally developed by Macromedia Inc. . It is a dialect of ECMAScript , and is used primarily for the development of websites and software targeting the Adobe Flash Player platform, used on Web pages in the form of... |
||
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.... |
Support is provided in clang Clang Clang is a compiler front end for the C, C++, Objective-C, and Objective-C++ programming languages. It uses the Low Level Virtual Machine as its back end, and Clang has been part of LLVM releases since LLVM 2.6.... and along with the llvm compiler-rt lib. GCC support is given for a macro implementation which enables the possibility of usage. Details see below. |
|
C# | ||
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... |
As of the C++11 standard | |
Clojure Clojure Clojure |closure]]") is a recent dialect of the Lisp programming language created by Rich Hickey. It is a general-purpose language supporting interactive development that encourages a functional programming style, and simplifies multithreaded programming.... |
||
Curl | ||
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++... |
||
Delphi Object Pascal Object Pascal refers to a branch of object-oriented derivatives of Pascal, mostly known as the primary programming language of Embarcadero Delphi.-Early history at Apple:... |
Starting with Delphi 2009. | |
Dylan | ||
Erlang | ||
F# | ||
Frink Frink Frink, named after the fictional mad scientist Professor John Frink from The Simpsons, is a calculating tool and programming language designed by Alan Eliasen. It is built on the Java Virtual Machine and incorporates features similar to Java, Perl, Ruby, Smalltalk, and various BASIC implementations... |
||
Go Go (programming language) Go is a compiled, garbage-collected, concurrent programming language developed by Google Inc.The initial design of Go was started in September 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. Go was officially announced in November 2009. In May 2010, Rob Pike publicly stated that Go was being... |
||
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... |
||
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... |
Planned for Java 8 or later | |
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.... |
||
Lisp | ||
Logtalk Logtalk Logtalk is an object-oriented logic programming language that extends the Prolog language with a feature set suitable for programming in the large. It provides support for encapsulation and data hiding, separation of concerns and enhanced code reuse... |
||
Lua | ||
Mathematica Mathematica Mathematica is a computational software program used in scientific, engineering, and mathematical fields and other areas of technical computing... |
||
Matlab MATLAB MATLAB is a numerical computing environment and fourth-generation programming language. Developed by MathWorks, MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages,... |
||
Maxima | ||
ML languages (Objective Caml Objective Caml OCaml , originally known as Objective Caml, is the main implementation of the Caml programming language, created by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy and others in 1996... , Standard ML Standard ML Standard ML is a general-purpose, modular, functional programming language with compile-time type checking and type inference. It is popular among compiler writers and programming language researchers, as well as in the development of theorem provers.SML is a modern descendant of the ML... , etc.) |
||
Octave GNU Octave GNU Octave is a high-level language, primarily intended for numerical computations. It provides a convenient command-line interface for solving linear and nonlinear problems numerically, and for performing other numerical experiments using a language that is mostly compatible with MATLAB... |
||
Object Pascal Object Pascal Object Pascal refers to a branch of object-oriented derivatives of Pascal, mostly known as the primary programming language of Embarcadero Delphi.-Early history at Apple:... |
Delphi, a dialect of Object Pascal, implements support for anonymous functions (formally, anonymous methods) natively. The Oxygene Object Pascal dialect also supports them. | |
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... (Mac OS X 10.6+) |
called blocks Blocks (C language extension) Blocks are a nonstandard extension added by Apple Inc. to the C, C++, and Objective-C programming languages that uses a lambda expression-like syntax to create closures within these languages... ; in addition to Objective-C, blocks can also be used on C and C++ when programming on Apple's platform |
|
Pascal Pascal (programming language) Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal... |
||
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... |
As of PHP 5.3.0, true anonymous functions are supported; previously only partial anonymous functions were supported, which worked much like C#'s implementation. | |
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... |
Python supports anonymous functions through the lambda syntax, in which you can only use expressions (and not statements). | |
R R (programming language) R is a programming language and software environment for statistical computing and graphics. The R language is widely used among statisticians for developing statistical software, and R is widely used for statistical software development and data analysis.... |
||
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... |
Ruby's anonymous functions, inherited from Smalltalk Smalltalk Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist... , are called blocks. |
|
Scala | ||
Scheme | ||
Smalltalk Smalltalk Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist... |
Smalltalk's anonymous functions are called blocks. | |
Visual Basic .NET Visual Basic .NET Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework... v9 |
||
Visual Prolog Visual Prolog Visual Prolog, also formerly known as PDC Prolog and Turbo Prolog, is a strongly typed object-oriented extension of Prolog. As Turbo Prolog it was marketed by Borland, but it is now developed and marketed by the Danish firm Prolog Development Center that originally developed it... v 7.2 |
||
Vala Vala (programming language) Vala is a programming language created with the goal of bringing modern language features to C, with no added runtime needs and with little overhead, by targeting the GObject object system. It is being developed by Jürg Billeter and Raffaele Sandrini. The syntax borrows heavily from C#... |
C lambda expressions
The following example works only with GCC.C# lambda expressions
Support for anonymous functions in C# has deepened through the various versions of the language compiler. The C# language v3.0, released in November 2007 with the .NET Framework v3.5, has full support of anonymous functions. C# refers to them as "lambda expressions", following the original version of anonymous functions, the Lambda CalculusLambda calculus
In mathematical logic and computer science, lambda calculus, also written as λ-calculus, is a formal system for function definition, function application and recursion. The portion of lambda calculus relevant to computation is now called the untyped lambda calculus...
. See the C# 4.0 Language Specification, section 5.3.3.29, for more information.
While the function is anonymous, it cannot be assigned to an implicitly typed variable, because the lambda syntax may be used to denote an anonymous function or an expression tree, and the choice cannot automatically be decided by the compiler. E.g., this does not work:
However, a lambda expression can take part in type inference and can be used as a method argument
Parameter (computer science)
In computer programming, a parameter is a special kind of variable, used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are called arguments...
, e.g. to use anonymous functions with the Map capability available with
System.Collections.Generic.List
(in the ConvertAll
method):Prior versions of C# had more limited support for anonymous functions.
C# v1.0, introduced in February 2002 with the .NET Framework v1.0, provided partial anonymous function support through the use of 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....
. This construct is somewhat similar to PHP delegates. In C# 1.0, Delegates are like function pointers that refer to an explicitly named method within a class. (But unlike PHP the name is not required at the time the delegate is used.) C# v2.0, released in November 2005 with the .NET Framework v2.0, introduced the concept of anonymous methods as a way to write unnamed inline statement blocks that can be executed in a delegate invocation. C# 3.0 continues to support these constructs, but also supports the lambda expression construct.
This example will compile in C# 3.0, and exhibits the three forms:
In the case of the C# 2.0 version, the C# compiler takes the code block of the anonymous function and creates a static private function. Internally, the function gets a generated name, of course; this generated name is based on the name of the method in which the Delegate is declared. But the name is not exposed to application code except by using reflection
Reflection (computer science)
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior at runtime....
.
In the case of the C# 3.0 version, the same mechanism applies.
C++
C++11 provides support for anonymous functions, called lambda functions in the specification. An example lambda function is defined as follows:The return type of this unnamed function is
decltype(x+y)
. The return type can be omitted if the lambda function is of the form return expression
(or if the lambda returns nothing), or if all locations that return a value return the same type when the return expression is passed through decltype
.The return type can be explicitly specified as follows:
In this example, a temporary variable,
z
, is created to store an intermediate. As with normal functions, the value of this intermediate is not held between invocations. Lambdas that return nothing can omit the return type specification; they do not need to use -> void
.A lambda function can refer to identifiers declared outside the lambda function. The set of these variables is 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...
. Closures are defined between square brackets
[
and ]
in the declaration of lambda expression. The mechanism allows these variables to be captured by value or by reference. The following table demonstrates this:The following two examples demonstrate usage of a lambda expression:
This computes the total of all elements in the list. The variable
total
is stored as a part of the lambda function's closure. Since it is a reference to the stack variable total
, it can change its value.This will cause
total
to be stored as a reference, but value
will be stored as a copy.The capture of
this
is special. It can only be captured by value, not by reference. Therefore, when using the &
specifier, this
is not captured at all unless it is explicitly stated. this
can only be captured if the closest enclosing function is a non-static member function. The lambda will have the same access as the member that created it, in terms of protected/private members.If
this
is captured, either explicitly or implicitly, then the scope of the enclosed class members is also tested. Accessing members of this
does not require explicit use of this->
syntax.The specific internal implementation can vary, but the expectation is that a lambda function that captures everything by reference will store the actual stack pointer of the function it is created in, rather than individual references to stack variables. However, because most lambda functions are small and local in scope, they are likely candidates for inlining
Inline expansion
In computing, inline expansion, or inlining, is a manual or compiler optimization that replaces a function call site with the body of the callee. This optimization may improve time and space usage at runtime, at the possible cost of increasing the final size of the program In computing, inline...
, and thus will not need any additional storage for references.
If a closure object containing references to local variables is invoked after the innermost block scope of its creation, the behaviour is undefined
Undefined behaviour
In computer programming, undefined behavior is a feature of some programming languages—most famously C. In these languages, to simplify the specification and allow some flexibility in implementation, the specification leaves the results of certain operations specifically undefined.For...
.
Lambda functions are function objects of an implementation-dependent type; this type's name is only available to the compiler. If the user wishes to take a lambda function as a parameter, the type must be a template type, or it must create a
std::function
or a similar object to capture the lambda value. The use of the auto
keyword can help store the lambda function:A lambda function with an empty capture specification (
[]
) can be implicitly converted into a function pointer with the same type as the lambda was declared with. So this is legal:Delphi (since v. 2009)
Erlang
Erlang uses a syntax for anonymous functions similar to that of named functions.Haskell
HaskellHaskell (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...
uses a concise syntax for anonymous functions (lambda expressions).
Lambda expressions are fully integrated with the type inference engine, and support all the syntax and features of "ordinary" functions (except for the use of multiple definitions for pattern-matching, since the argument list is only specified once).
The following are all equivalent:
JavaScript
JavaScriptJavaScript
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....
supports anonymous functions.
This construct is often used in Bookmarklet
Bookmarklet
A bookmarklet is Unobtrusive JavaScript stored as the URL of a bookmark in a web browser or as a hyperlink on a web page. The term is a portmanteau of the terms bookmark and applet, however, an applet is not to be confused with a bookmarklet just as JavaScript is not to be confused with Java...
s. For example, to change the title of the current document (visible in its window's title bar
Title bar
In computing, the title bar consists of that part of a window where the title of the window appears. Most graphical operating systems and window managers position the title bar at the top of the application window as a horizontal bar....
) to its URL, the following bookmarklet may seem to work.
However, as the assignment statement returns a value (the URL itself), many browsers actually create a new page to display this value.
Instead, an anonymous function can be used so that no value is returned:
The function statement in the first (outer) pair of parentheses declares an anonymous function, which is then executed when used with the last pair of parentheses. This is equivalent to the following.
Lisp
Lisp and Scheme support anonymous functions using the "lambda" construct, which is a reference to lambda calculusLambda calculus
In mathematical logic and computer science, lambda calculus, also written as λ-calculus, is a formal system for function definition, function application and recursion. The portion of lambda calculus relevant to computation is now called the untyped lambda calculus...
. Clojure
Clojure
Clojure |closure]]") is a recent dialect of the Lisp programming language created by Rich Hickey. It is a general-purpose language supporting interactive development that encourages a functional programming style, and simplifies multithreaded programming....
supports anonymous functions with the "fn" special form and # reader syntax.
Interestingly, Scheme's "named functions" is simply syntactic sugar
Syntactic sugar
Syntactic sugar is a computer science term that refers to syntax within a programming language that is designed to make things easier to read or to express....
for anonymous functions bound to names:
expands (and is equivalent) to
Clojure
Clojure
Clojure |closure]]") is a recent dialect of the Lisp programming language created by Rich Hickey. It is a general-purpose language supporting interactive development that encourages a functional programming style, and simplifies multithreaded programming....
supports anonymous functions through the "fn" special form:
There is also a reader syntax to define a lambda:
Like Scheme, Clojure's "named functions" are simply syntactic sugar for lambdas bound to names:
expands to:
Logtalk
LogtalkLogtalk
Logtalk is an object-oriented logic programming language that extends the Prolog language with a feature set suitable for programming in the large. It provides support for encapsulation and data hiding, separation of concerns and enhanced code reuse...
uses the following syntax for anonymous predicates (lambda expressions):
{FreeVar1, FreeVar2, ...}/[LambdaParameter1, LambdaParameter2, ...]>>Goal
A simple example with no free variables and using a list mapping predicate is:
| ?- meta::map([X,Y]>>(Y is 2*X), [1,2,3], Ys).
Ys = [2,4,6]
yes
Currying is also supported. The above example can be written as:
| ?- meta::map([X]>>([Y]>>(Y is 2*X)), [1,2,3], Ys).
Ys = [2,4,6]
yes
Lua
In Lua (much as in Scheme) all functions are anonymous. A "named function" in Lua is simply a variable holding a reference to a function object.Thus, in Lua
is just syntactical sugar for
An example of using anonymous functions for reverse-order sorting:
Maxima
Maxima supports anonymous functions,ML
The various dialects of ML support anonymous functions.Objective Caml
Objective Caml
OCaml , originally known as Objective Caml, is the main implementation of the Caml programming language, created by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy and others in 1996...
:
Standard ML
Standard ML
Standard ML is a general-purpose, modular, functional programming language with compile-time type checking and type inference. It is popular among compiler writers and programming language researchers, as well as in the development of theorem provers.SML is a modern descendant of the ML...
:
fn arg => arg * arg
Perl 5
Perl 5 supports anonymous functions, as follows:Other constructs take "bare blocks" as arguments, which serve a function similar to lambda functions of a single parameter, but don't have the same parameter-passing convention as functions -- @_ is not set.
Perl 6
In Perl 6Perl 6
Perl 6 is a major revision to the Perl programming language. It is still in development, as a specification from which several interpreter and compiler implementations are being written. It is introducing elements of many modern and historical languages. Perl 6 is intended to have many...
, all blocks (even the ones associated with if, while, etc.) are anonymous functions. A block that is not used as an rvalue
Value (computer science)
In computer science, a value is an expression which cannot be evaluated any further . The members of a type are the values of that type. For example, the expression "1 + 2" is not a value as it can be reduced to the expression "3"...
is executed immediately.
4.0.1 to 5.3
PHP 4.0.1 introduced thecreate_function
which was the initial anonymous function support. This function call creates a new randomly named function and returns its name (as a string)It is important to note that the argument list and function body must be in single quotes or the dollar signs must be escaped.
Otherwise PHP will assume "
$x
" means the variable $x
and will substitute it into the string (despite possibly not existing) instead of leaving "$x
" in the string.For functions with quotes or functions with lots of variables, it can get quite tedious to ensure the intended function body is what PHP interprets.
5.3
PHP 5.3 added a new class calledClosure
and magic method __invoke
that makes a class instance invocable.Lambda functions are a compiler "trick" that instantiates a new
Closure
instance that can be invoked as if the function were invokable.In this example,
$func
is an instance of Closure
and echo $func
is equivalent to $func->__invoke($z)
.PHP 5.3 mimics anonymous functions but it does not support true anonymous functions because PHP functions are still not first-class objects.
PHP 5.3 does support closures but the variables must be explicitly indicated as such:
The variable
$x
is bound by reference so the invocation of $func
modifies it and the changes are visible outside of the function.Python
PythonPython (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...
supports simple anonymous functions through the lambda form. The executable body of the lambda must be an expression and can't be a statement, which is a restriction that limits its utility. The value returned by the lambda is the value of the contained expression. Lambda forms can be used anywhere ordinary functions can, however these restrictions make it a very limited version of a normal function. Here is an example:
This example will print: 100.
In general, Python convention encourages the use of named functions defined in the same scope as one might typically use an anonymous functions in other languages. This is acceptable as locally defined functions implement the full power of 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...
s and are almost as efficient as the use of a lambda in Python. In this example, the built-in power function can be said to have been curried
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...
:
Ruby
Ruby supports anonymous functions by using a syntactical structure called block. When passed to a method, a block is converted into an object of class Proc in some circumstances.Scala
In Scala, anonymous functions use the following syntax:In certain contexts, such as when an anonymous function is passed as a parameter to another function, the compiler can infer the types of the parameters of the anonymous function and they can be omitted in the syntax. In such contexts, it is also possible to use a shorthand for anonymous functions using the underscore character to introduce unnamed parameters.
Smalltalk
In SmalltalkSmalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...
anonymous functions are called blocks
Visual Basic
VBVisual Basic .NET
Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...
9, introduced in November 2007, supports anonymous functions through the lambda form. Combined with implicit typing, VB provides an economical syntax for anonymous functions. As with Python, in VB9, anonymous functions must be defined on a single line; they cannot be compound statements. Further, an anonymous function in VB must truly be a VB "
Function
" - it must return a value.VB10, released April 12, 2010, adds support for multiline lambda expressions and anonymous functions without a return value. For example, a function for use in a Thread.
Visual Prolog
Anonymous functions (in general anonymous predicates) were introduced in Visual PrologVisual Prolog
Visual Prolog, also formerly known as PDC Prolog and Turbo Prolog, is a strongly typed object-oriented extension of Prolog. As Turbo Prolog it was marketed by Borland, but it is now developed and marketed by the Danish firm Prolog Development Center that originally developed it...
in version 7.2. Anonymous predicates can capture values from the context. If created in an object member it can also access the object state (by capturing
This
).mkAdder
returns an anonymous function, which has captured the argument X
in the closure. The returned function is a function that adds X
to its argument:Mathematica
Anonymous Functions are important in programming Mathematica. There are several ways to create them. Below are a few anonymous function that increment a number. The first is the most common. '#1' refers to the first argument and '&' makes the end of the anonymous function.Additionally, Mathematica has an additional construct to for making recursive anonymous functions. The symbol '#0' refers to the entire function.
External links
- Anonymous Methods - When Should They Be Used? (blog about anonymous function in Delphi)