Computing is usually defined as the activity of using and developing computer technology, computer hardware and computer software. It is the computer-specific part of information technology.... , an anonymous function is a function
Function (mathematics)
The mathematical concept of a function expresses dependence between two quantities, one of which is known and the other which is produced. A function associates a single output to each input element drawn from a fixed Set , such as the real numbers , although different inputs may have the same output.... (or a subroutine
Subroutine
In computer science, a subroutine or subprogram is a portion of computer code within a larger computer program, which performs a specific task and is relatively independent of the remaining code.... ) defined, and possibly called, without being bound to a name. In lambda calculus
Lambda calculus
In mathematical logic and computer science, lambda calculus, also written as ?-calculus, is a formal system designed to investigate function definition, function application and recursion.... , all functions are anonymous. The Y combinator
Y Combinator
Y Combinator is a seed-stage startup venture capital firm, started in 2005 by Paul Graham, Robert Tappan Morris, Trevor Blackwell, and Jessica Livingston.... can be utilised in these circumstances to provide anonymous recursion
Anonymous recursion
In computer science, anonymous recursion is a recursion technique that uses anonymous functions.... . Certain programming languages also provide support for both named and anonymous functions. The lambda calculus without anonymous function definition forms a combinatory logic
Combinatory logic
Combinatory logic is a notation introduced by Moses Sch?nfinkel and Haskell Curry to eliminate the need for variables in mathematical logic. It has more recently been used in computer science as a theoretical model of computation and also as a basis for the design of functional programming languages.... .
Some object-oriented programming languages have anonymous classes, which are a similar concept.
Computing is usually defined as the activity of using and developing computer technology, computer hardware and computer software. It is the computer-specific part of information technology.... , an anonymous function is a function
Function (mathematics)
The mathematical concept of a function expresses dependence between two quantities, one of which is known and the other which is produced. A function associates a single output to each input element drawn from a fixed Set , such as the real numbers , although different inputs may have the same output.... (or a subroutine
Subroutine
In computer science, a subroutine or subprogram is a portion of computer code within a larger computer program, which performs a specific task and is relatively independent of the remaining code.... ) defined, and possibly called, without being bound to a name. In lambda calculus
Lambda calculus
In mathematical logic and computer science, lambda calculus, also written as ?-calculus, is a formal system designed to investigate function definition, function application and recursion.... , all functions are anonymous. The Y combinator
Y Combinator
Y Combinator is a seed-stage startup venture capital firm, started in 2005 by Paul Graham, Robert Tappan Morris, Trevor Blackwell, and Jessica Livingston.... can be utilised in these circumstances to provide anonymous recursion
Anonymous recursion
In computer science, anonymous recursion is a recursion technique that uses anonymous functions.... . Certain programming languages also provide support for both named and anonymous functions. The lambda calculus without anonymous function definition forms a combinatory logic
Combinatory logic
Combinatory logic is a notation introduced by Moses Sch?nfinkel and Haskell Curry to eliminate the need for variables in mathematical logic. It has more recently been used in computer science as a theoretical model of computation and also as a basis for the design of functional programming languages.... .
Some object-oriented programming languages have anonymous classes, which are a similar concept. 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 .... 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 closure
Closure (computer science)
In computer science, a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these variables.... s and currying
Currying
In computer science, currying, invented by Moses Sch?nfinkel and Gottlob Frege, and independently by Haskell Curry, is the technique of transforming a function that takes multiple parameter 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. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive.... .
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 (everything in python has a class):
a = [10, '10', 10.0]
a.sort(lambda x,y: cmp(x.__class__.__name__, y.__class__.__name__))
print a
[10.0, 10, '10']
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:
lambda x,y: cmp(...)
The anonymous function accepts two arguments — x & 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:
a = ['three', 'two', 'four']
a.sort(lambda x,y: cmp(len(x), len(y)))
print a
['two', 'four', 'three']
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.
def comp(threshold):
return lambda x: x < 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).
def divide(x,y):
return x/y
def divisor(d):
return lambda x: divide(x,d)
half = divisor(2)
third = divisor(3)
print half(32), third(32)
16 10
print half(40), third(40)
20 13
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 square
Square (algebra)
In algebra, the square of a number is that number multiplication by itself. To square a quantity is to multiply it by itself.Its notation is a superscripted "2"; a number x squared is written as x?.... s every element in an array with an anonymous function.
a = [1, 2, 3, 4, 5, 6]
print map(lambda x: x*x, a)
[1, 4, 9, 16, 25, 36]
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.
a = [1, 2, 3, 4, 5]
print reduce(lambda x,y: x*y, a)
120
This performs:
The anonymous function here is simply the multiplication of the two arguments.
A programming language is a machine-readable artificial language designed to express computations that can be performed by a machine, particularly a computer.... 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 originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system.... , C++
C++
C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features.... , C# †, Pascal, Object Pascal
Object Pascal
Object Pascal refers to a branch of Object-oriented programming derivatives of Pascal , mostly known as the primary programming language of CodeGear Delphi.... , 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 .... — all employ static typing. This does not, however, mean that static languages are incapable of support anonymous functions. For example, 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 support first-class functions if it treats function s as first-class objects. Specifically, this means that the language supports constructing new functions during the execution of a program, storing them in data structures, passing them as arguments to other functions, and returning the... s — JavaScript
JavaScript
JavaScript is a scripting language widely used for client-side web development. It was the originating Programming language dialect of the ECMAScript standard.... , Lisp, Scheme, ML, Haskell
Haskell (programming language)
Haskell is a standardized, purely functional programming language with non-strict programming language, named after logician Haskell Curry. The goals of the language are described as:... , Python
Python (programming language)
Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive.... , Ruby
Ruby (programming language)
Ruby is a dynamic programming language, reflection , general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features.... , Perl
Perl
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... — generally have anonymous function support.
ActionScript is a scripting language based on ECMAScript. ActionScript is used primarily for the development of websites and software using the Adobe Flash Player platform , but is also used in some database applications , and in basic robotics, as with the Make Controller Kit....
C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system....
C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
The D programming language, also known simply as D, is an Object-oriented programming, Imperative programming, Multi-paradigm programming language system programming language by Walter Bright of Digital Mars....
Haskell is a standardized, purely functional programming language with non-strict programming language, named after logician Haskell Curry. The goals of the language are described as:...
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 ....
JavaScript is a scripting language widely used for client-side web development. It was the originating Programming language dialect of the ECMAScript standard....
Standard ML is a general-purpose, Module , 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 automated theorem proving.... , etc.)
Object Pascal refers to a branch of Object-oriented programming derivatives of Pascal , mostly known as the primary programming language of CodeGear Delphi....
Pascal is an influential imperative programming and Procedural programming 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 structure....
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
PHP is a scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in Standalone software Graphical user interface....
Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
Ruby is a dynamic programming language, reflection , general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features....
Visual Basic , formerly called Visual Basic .NET , is an object-oriented programming computer language that can be viewed as an evolution of Microsoft Visual Basic implemented on the .NET Framework.... v9
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
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 , section 5.3.3.29, for more information.
Func foo = x => x*x;
Console.WriteLine(foo(7));
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:
// will NOT compile!
var foo = x => x*x;
Console.WriteLine(foo(7));
As a further example, combining anonymous functions with the Map capability available with System.Collections.Generic.List (in the ConvertAll method) looks like this:
// Initialize the list:
var values = new List ;
// Map the anonymous function over all elements in the list, return the new list
var foo = values.ConvertAll(d => d*d) ;
// the result of the foo variable is of type System.Collections.Generic.List
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 safety function pointer used by the .NET Framework. Delegates specify a Method to call and optionally an Object to call the method on.... . 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:
public class TestDriver
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.
Delphi
program demo;
type
TSimpleProcedure = reference to procedure;
TSimpleFunction = reference to function(x: string): Integer;
var
x1: TSimpleProcedure;
y1: TSimpleFunction;
begin
x1 := procedure
begin
Writeln('Hello World');
end;
x1; //invoke anonymous method just defined
y1 := function(x: string): Integer
begin
Result := Length(x);
end;
Writeln(y1('bar'));
end.
Haskell is a standardized, purely functional programming language with non-strict programming language, named after logician Haskell Curry. The goals of the language are described as:... uses a concise syntax for anonymous functions (lambda expressions).
\arg -> arg * arg
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).
JavaScript is a scripting language widely used for client-side web development. It was the originating Programming language dialect of the ECMAScript standard.... supports anonymous functions.
var foo = function(x)
alert(foo(10));
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) is the same as foo given above).
Lisp
Lisp and Scheme support anonymous functions using the "lambda" construct, which is a reference to lambda calculus
Lambda calculus
In mathematical logic and computer science, lambda calculus, also written as ?-calculus, is a formal system designed to investigate function definition, function application and recursion.... .
(lambda (arg) (* arg arg))
Interestingly, Scheme's "named functions" is simply syntactic sugar for anonymous functions bound to names:
(define (somename arg)
(do-something arg))
expands (and is equivalent) to
(define somename
(lambda (arg)
(do-something arg)))
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
function foo (x) return 2*x end
is just syntactical sugar for
foo = function (x) return 2*x end
An example of using anonymous functions for reverse-order sorting:
table.sort(network, function (a,b)
return (a.name > b.name)
end)
ML
The various dialects of ML support anonymous functions.
Standard ML is a general-purpose, Module , 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 automated theorem proving.... :
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... supports anonymous functions, as follows:
(sub )->; # 1. fully anonymous, called as created
my $squarer = sub ; # 2. assigned to a variable
sub curry (&@)
example of currying in Perl
sub sum # returns the sum of its arguments
my $curried = curry \&sum, 5, 7, 9;
print $curried->(1,2,3), "\n"; # prints 27 ( = 5 + 7 + 9 + 1 + 2 + 3 )
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.
my @squares = map 1..10; # map and grep don't use the 'sub' keyword
my @square2 = map $_ * $_, 1..10; # parentheses not required for a single expression
my @bad_example = map 1..10; # values not passed like normal Perl function
PHP is a scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in Standalone software Graphical user interface.... prior to 4.0.1 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 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 called Closure 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.
$x = 3;
$func = function($z) ;
echo $func($x); // prints 6
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 functions.
PHP 5.3 does support closures but the variables must be explicitly indicated as such:
$x = 3;
$func = function use(&$x) ;
$func;
echo $x; // prints 6
The variable $x is bound by reference so the invocation of $func modifies it and the changes are visible outside of the function.
Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the 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 limits its utility. The value returned by the lamdba 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:
foo = lambda x: x*x
print foo(10)
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 are almost as efficient as the use of a lambda in Python.
Visual Basic , formerly called Visual Basic .NET , is an object-oriented programming computer language that can be viewed as an evolution of Microsoft Visual Basic implemented on the .NET Framework.... v9, 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 VB v9, 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.
Dim foo = Function(x) x * x
Console.WriteLine(foo(10))
Visual Prolog
Anonymous functions (in general anonymous predicates) were introduced in 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.... 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:
In computer science, a programming language is said to support first-class functions if it treats function s as first-class objects. Specifically, this means that the language supports constructing new functions during the execution of a program, storing them in data structures, passing them as arguments to other functions, and returning the...