- Anonymous function
In
computing , an anonymous function is a function (or asubroutine ) defined, and possibly called, without being bound to a name. Inlambda calculus , all functions are anonymous. TheY combinator can be utilised in these circumstances to provideanonymous recursion . Certain programming languages also provide support for both named and anonymous functions. The lambda calculus without anonymous function definition forms acombinatory logic .Some
object-oriented programming languages haveanonymous class es, which are a similar concept. Java 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 closures and
currying .All of the code in the following sections is in python.
orting
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 (everything in python 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
&y
— and returns the comparison between them using the built-in functioncmp()
.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 variable s. 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).
Fold
The fold/reduce function reduces a list of elements repeatedly from left-to-right until only one element remains.
This performs:
:
The anonymous function here is simply the multiplication of the two arguments.
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 no support anonymous functions — C,
C++ , C# †, Java — all employ static typing. This does not, however, mean that static languages are incapable of support anonymous functions. Second, the languages that treat functions asfirst-class function s —JavaScript , Lisp, Scheme, ML, Haskell, Python,Ruby,Perl — generally have anonymous function support.† — C# support for anonymous functions currently employs the creation of a static function within the class. This means anonymous function support is a convenient facade presented by the compiler while the created anonymous function is really just a named static function (with a semi-random name) and thus not a real anonymous function. What this ultimately means is that anonymous functions are not dynamically created and executed like in, say, JavaScript.
Examples
Numerous languages support anonymous functions, or something similar.
C#
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. The term for it in C# is "lambda expressions". See the [http://msdn2.microsoft.com/en-us/vcsharp/aa336809.aspx C# 3.0 Language Specification] , section 5.3.3.29, for more information.
While the function is anonymous, the type is explicit. C# 3.0 does include implicitly typed variables, but because the lambda syntax may be used to denote an anonymous function or an expression tree, the type cannot automatically be inferred by the compiler, and therefore lambda expressions cannot be assigned to implicitly typed variables. Eg,this does not work:
As a further example, combining anonymous functions with the Map capability available with
System.Collections.Generic.List
(in theConvertAll()
method) looks like this: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 never exposed to application code.
In the case of the C# 3.0 version, the same mechanism applies.
Haskell
Haskell supports anonymous functions.
arg -> arg * argJavaScript
JavaScript supports anonymous functions.Unlike Python, anonymous functions in JavaScript are just like named functions and are declared just like named functions - in fact, all functions are implemented in the same way as anonymous functions, only sometimes with slightly different semantics (e.g.
function foo(x) { return x*x }
is the same asfoo
given above).Lisp
Lisp and Scheme supports anonymous functions using the "lambda" construct, which is a reference to
lambda calculus .Lua
In Lua all functions are anonymous. A "function name" in Lua is actually a variable that holds the respective function [cite web | title=Programming in Lua - More about Functions | url=http://www.lua.org/pil/6.html | accessdate=2008-04-25 ] .
Thus, in Luais just syntactical sugar for
An example of using anonymous functions for reverse-order sorting:
ML
The various dialects of ML support anonymous functions.
OCaml :Standard ML :fn arg => arg * argPerl
Perl 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.
PHP
PHP prior to 4.0.1 [http://php.net/create_function the top of the page indicates this with "(PHP 4 >= 4.0.1, PHP 5)"] PHP had no anonymous function support.4.0.1 to 5.3
PHP 4.0.1 introduced the
create_function
which was the initial anonymous function support. This function call created a new function but returned a string reference to the new function:The contents of
$foo
is a string of the form"
Wikimedia Foundation. 2010.