# Anonymous function

In computer programming, an anonymous function (also function constant, function literal, or lambda function) 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 functions 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 variables). 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. In several programming languages, anonymous functions are introduced using the keyword lambda, and anonymous functions are often referred to as lambda functions.

Anonymous functions have been a feature of programming languages since Lisp in 1958. An increasing number of modern programming languages support anonymous functions, and some recent, notable mainstream languages support them, the most widespread being JavaScript[1] and Ruby.[2] Anonymous functions were added to C++ in 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 (although support for lambda functions is expected in Java 8[3]).

## 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 written in Python 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):

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 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:

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:

a = comp(10)
b = comp(20)

print a(5), a(8), a(13), a(21)
True True False False

print b(5), b(8), b(13), b(21)
True True True False


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.)

### Higher-order functions

#### Map

The map function performs a function call on each element of a list. The following example squares 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).

#### Filter

The filter function returns all elements from a list that evaluate True when passed to a certain function.

a = [1, 2, 3, 4, 5, 6]
print filter(lambda x: x % 2 == 0, a)
[2, 4, 6]


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:

a = [1, 2, 3, 4, 5]
print reduce(lambda x,y: x*y, a)
120


This performs:

$\left( \left( \left( 1 \times 2 \right) \times 3 \right) \times 4 \right) \times 5 = 120$

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 languages 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 functionsDylan, 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 a conventional, statically typed language.

Language Support Notes
ActionScript
C Support is provided in clang 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++ As of the C++11 standard
Clojure
Curl
D
Dart
Dylan
Erlang
F#
Frink
Go
Gosu [4]
Groovy [5]
Java Planned for Java 8
JavaScript
Lisp
Logtalk
Lua
Mathematica
Maple
Matlab
Maxima
OCaml
Octave
Object Pascal Delphi, a dialect of Object Pascal, implements support for anonymous functions (formally, anonymous methods) natively since Delphi 2009. The Oxygene Object Pascal dialect also supports them.
Objective-C (Mac OS X 10.6+) called blocks; in addition to Objective-C, blocks can also be used on C and C++ when programming on Apple's platform
Pascal
Perl
PHP 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 supports anonymous functions through the lambda syntax, in which you can only use expressions (and not statements).
R
Racket
Ruby Ruby's anonymous functions, inherited from Smalltalk, are called blocks.
Scala
Scheme
Smalltalk Smalltalk's anonymous functions are called blocks.
Standard ML
TypeScript
Tcl
Vala
Visual Basic .NET v9
Visual Prolog v 7.2

## Examples

Numerous languages support anonymous functions, or something similar.

### C lambda expressions

The following example works only with GCC. Also note that due to the way macros work, if your l_body contains any commas outside of parentheses then it will not compile as gcc uses the comma as a delimiter for the next argument in the macro. The argument 'l_ret_type' can be removed if '__typeof__' is available to you; in the example below using __typeof__ on array would return testtype *, which can be dereferenced for the actual value if needed.

/* this is the definition of the anonymous function */
#define lambda(l_ret_type, l_arguments, l_body)         \
({                                                    \
l_ret_type l_anonymous_functions_name l_arguments   \
l_body                                            \
&l_anonymous_functions_name;                        \
})

#define forEachInArray(fe_arrType, fe_arr, fe_fn_body)                                            \
{                                                                                         \
int i=0;                                                                                \
for(;i<sizeof(fe_arr)/sizeof(fe_arrType);i++) {  fe_arr[i] = fe_fn_body(&fe_arr[i]); }  \
}

typedef struct __test {
int a;
int b;
} testtype;

testtype array[] = { {0,1}, {2,3}, {4,5} };

printout(array);
/* the anonymous function is given as function for the foreach */
forEachInArray(testtype, array,
lambda (testtype, (void *item),
{
int temp = (*( testtype *) item).a;
(*( testtype *) item).a = (*( testtype *) item).b;
(*( testtype *) item).b = temp;
return (*( testtype *) item);
}));
printout(array);


Using the aforementioned clang extension called block and libdispatch, Code could look simpler like this:

#include <stdio.h>
#include <dispatch.h>

int main(void)
{
void (^f)() = ^{
for (int i = 0; i < 100; i++)
printf("%d\n", i);
} //make a variable of it
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), f); //Pass as a parameter to another function, in this case libdispatch
f(); //Direct invoke
return 0;
}


### 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 calculus. See the C# 4.0 Language Specification, section 5.3.3.29, for more information.

// the first int is the x' type
// the second int is the return type
// <see href="http://msdn.microsoft.com/en-us/library/bb549151.aspx" />
Func<int,int> foo = x => x*x;
Console.WriteLine(foo(7));


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:

// will NOT compile!
var foo = (int x) => x*x;


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 System.Collections.Generic.List (in the ConvertAll() method):

// Initialize the list:
var values = new List<int>() { 7, 13, 4, 9, 3 };
// 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<Int32>


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:

  public class TestDriver
{
delegate int SquareDelegate(int d);
static int Square(int d)
{
return d*d;
}

static void Main(string[] args)
{
// C# 1.0: Original delegate syntax required
// initialization with a named method.
SquareDelegate A = new SquareDelegate(Square);
System.Console.WriteLine(A(3));

// C# 2.0: A delegate can be initialized with
// inline code, called an "anonymous method." This
// method takes an int as an input parameter.
SquareDelegate B = delegate(int d) { return d*d; };
System.Console.WriteLine(B(5));

// C# 3.0. A delegate can be initialized with
// a lambda expression. The lambda takes an int, and returns an int.
// The type of x is inferred by the compiler.
SquareDelegate C = x => x*x;
System.Console.WriteLine(C(7));

// C# 3.0. A delegate that accepts a single input and
// returns a single output can also be implicitly declared with the Func<> type.
System.Func<int,int> D = x => x*x;
System.Console.WriteLine(D(9));
}
}


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.

### C++

C++11 provides support for anonymous functions, called lambda functions in the specification. A lambda expression has the form:

[capture](parameters)->return-type{body}


If there are no parameters the empty parentheses can be omitted. The return type can often be omitted, if the body consists only of one return statement or the return type is void.

[capture](parameters){body}


An example lambda function is defined as follows:

[](int x, int y) { return x + y; } // implicit return type from 'return' statement
[](int& x) { ++x; }   // no return statement -> lambda function's return type is 'void'
[]() { ++global_x; }  // no parameters, just accessing a global variable
[]{ ++global_x; }     // the same, so () can be omitted


The return type of this unnamed function is decltype(x+y) (in the first example above). 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:

[](int x, int y) -> int { int z = x + y; return z; }


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. 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:

[]        //no variables defined. Attempting to use any external variables in the lambda is an error.
[x, &y]   //x is captured by value, y is captured by reference
[&]       //any external variable is implicitly captured by reference if used
[=]       //any external variable is implicitly captured by value if used
[&, x]    //x is explicitly captured by value. Other variables will be captured by reference
[=, &z]   //z is explicitly captured by reference. Other variables will be captured by value


The following two examples demonstrate usage of a lambda expression:

std::vector<int> some_list{ 1, 2, 3, 4, 5 };
int total = 0;
std::for_each(begin(some_list), end(some_list), [&total](int x) {
total += x;
});


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.

std::vector<int> some_list{ 1, 2, 3, 4, 5 };
int total = 0;
int value = 5;
std::for_each(begin(some_list), end(some_list), [&, value, this](int x) {
total += x * value * this->some_func();
});


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. 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, 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 they 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,

auto my_lambda_func = [&](int x) { /*...*/ };
auto my_onheap_lambda_func = new auto([=](int x) { /*...*/ });


Here is an example of storing anonymous functions in variables, vectors, and arrays; and passing them as named parameters:

#include<functional>
#include<vector>
#include<iostream>
double eval(std::function<double(double)> f, double x = 2.0){return f(x);}
int main(){
std::function<double(double)> f0    = [](double x){return 1;};
auto                          f1    = [](double x){return x;};
decltype(f0)                  fa[3] = {f0,f1,[](double x){return x*x;}};
std::vector<decltype(f0)>     fv    = {f0,f1};
fv.push_back                  ([](double x){return x*x;});
for(int i=0;i<fv.size();i++)  std::cout << fv[i](2.0) << "\n";
for(int i=0;i<3;i++)          std::cout << fa[i](2.0) << "\n";
for(auto &f : fv)             std::cout << f(2.0) << "\n";
for(auto &f : fa)             std::cout << f(2.0) << "\n";
std::cout << eval(f0) << "\n";
std::cout << eval(f1) << "\n";
std::cout << eval([](double x){return x*x;}) << "\n";
return 0;
}


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:

auto a_lambda_func = [](int x) { /*...*/ };
void(*func_ptr)(int) = a_lambda_func;
func_ptr(4); //calls the lambda.


### D

(x){return x*x;}
delegate (x){return x*x;} // if more verbosity is needed
(int x){return x*x;} // if parameter type cannot be inferred
delegate (int x){return x*x;} // ditto
delegate double(int x){return x*x;} // if return type must be forced manually


Since version 2.0, D allocates closures on the heap unless the compiler can prove it is unnecessary; the scope keyword can be used to force stack allocation. Since version 2.058, it is possible to use shorthand notation:

x => x*x;
(int x) => x*x;
(x,y) => x*y;
(int x, int y) => x*y;


### Dart

Dart supports anonymous functions.

var sqr = (x) => x * x;
print(sqr(5));


or

print(((x) => x * x)(5));


### Delphi (since v. 2009)

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.


### Erlang

Erlang uses a syntax for anonymous functions similar to that of named functions.

% Anonymous function bound to the Square variable
Square = fun(X) -> X * X end.

% Named function with the same functionality
square(X) -> X * X.


Haskell uses a concise syntax for anonymous functions (lambda expressions).

 \x -> x * x


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).

 map (\x -> x * x) [1..5] -- returns [1, 4, 9, 16, 25]


The following are all equivalent:

 f x y = x + y
f x = \y -> x + y
f = \x y -> x + y


### JavaScript

JavaScript supports anonymous functions.

alert((function(x){
return x*x;
})(10));


This construct is often used in Bookmarklets. 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.

javascript:document.title=location.href;


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, that does not return a value, can be used:

javascript:(function(){document.title=location.href;})();


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 almost equivalent to the following, which populates the environment with f unlike an anonymous function.

javascript:var f = function(){document.title=location.href;}; f();


Use void() to avoid new pages for arbitrary anonymous functions:

javascript:void(function(){return document.title=location.href;}());


(or just:

javascript:void(document.title=location.href);


)

Javascript has syntactic subtleties for the semantics of defining, invoking and evaluating anonymous functions. These subliminal nuances are a direct consequence of the evaluation of parenthetical expressions. The following constructs which are called immediately-invoked function expression illustrate this:

(function(){ ... }())


and

(function(){ ... })()


.

Representing "function(){ ... }" by f, the form of the constructs are a parenthetical within a parenthetical (f()) and a parenthetical applied to a parenthetical (f)().

Note the general syntactic ambiguity of a parethentical expression, parenthesized arguments to a function and the parentheses around the formal parameters in a function definition. In particular, Javascript defines a , (comma) operator in the context of a parathentical expression. It is no mere coincidence that the syntatic forms coincide for an expression and a function's arguments (ignoring the function formal parameter syntax)! If f is not identified in the constructs above, they become (()) and ()(). The first provides no syntactic hint of any resident function but the second MUST evaluate the first parenthetical as a function to be legal Javascript. (Aside: for instance, the ()'s could be ([],{},42,"abc",function(){}) as long as the expression evaluates to a function.)

Also, a function is an Object instance (likewise objects are Function instances) and the object literal notation brackets, {} for braced code, are used when defining a function this way (as opposed to using new Function(...)). In a very broad non-rigorous sense (especially since global bindings are compromised), an arbitrary sequence of braced Javascripts statements, {stuff}, can be considered to be a fixed point of

(function(){( function(){( ... {( function(){stuff}() )} ... )}() )}() )


More correctly but with caveats,

( function(){stuff}() ) ~=
A_Fixed_Point_of(
function(){ return function(){ return ... { return function(){stuff}() } ... }() }()
)


Note the implications of the anonymous function in the javascripts that follow:

• function(){ ... }() without surrounding ()'s is generally not legal
• (f=function(){ ... }) does not "forget" f globally unlike (function f(){ ... })
• "relaxed" function "naming" such as:
RA[3]=function(){ ... }
or even this bizarre "name" creation
eval( "f:j=function(x){ alert((x)) }" ); eval("f:j")(eval("f:j"));
(this simply prints function(x){ alert((x)) } )
• objects can have function property identifiers (ie. be "indexed" by a function):
({}[function(){}])=42
alert(function (obj){ obj[function(){}]=42; return obj}({})[function(){}]) /* 42 */
• (function(f,x){return (f)(x)}) is a particularly "potent" lambda potion
• (function (l){return (l)(l)})(function (l){return (l)(l)}) ie. (lambda)(lambda)
(function (l){return (l(l))} (function (l){return (l(l))}))
• (function (i){return (i)(i)(i)(i) ... (i)(i)})(function (f){return f})
• (function (r){return (r(r(r(r(...(r)...)))))})(function (f){return f})
• (function (r){return ((((...(((r)(r))(r))...)(r))(r))(r))})(function (f){return f})
Performance metrics to analyze the space and time complexities of function calls, call stack, etc. in a Javascript interpreter engine implement easily with these last anonymous function constructs. From the implications of the results, it is possible to deduce some of an engine's recursive versus iterative implementation details, especially tail-recursion .

### Lisp

Lisp and Scheme support anonymous functions using the "lambda" construct, which is a reference to lambda calculus. Clojure supports anonymous functions with the "fn" special form and #() reader syntax.

(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)))


Clojure supports anonymous functions through the "fn" special form:

(fn [x] (+ x 3))


There is also a reader syntax to define a lambda:

# (+ % %2 %3) ; Defines an anonymous function that takes three arguments and sums them.


Like Scheme, Clojure's "named functions" are simply syntactic sugar for lambdas bound to names:

(defn func [arg] (+ 3 arg))


expands to:

(def func (fn [arg] (+ 3 arg)))


### Logtalk

Logtalk 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.[6]

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)


### 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.

     #1+1&
Function[x,x+1]
x \[Function] x+1


Additionally, Mathematica has an additional construct to for making recursive anonymous functions. The symbol '#0' refers to the entire function.

     If[#1 == 1, 1, #1 * #0[#1-1]]&


### Maxima

In Maxima anonymous functions are defined using the syntax lambda(argument-list,expression),

 f: lambda([x],x*x); f(8);
64

lambda([x,y],x+y)(5,6);
11


### ML

The various dialects of ML support anonymous functions.

fun arg -> arg * arg


F#:

(fun x -> x * x) 20 // 400

fn arg => arg * arg


### Octave/MATLAB

Anonymous functions in GNU Octave or MATLAB are defined using the syntax @(argument-list)expression. Any variables that are not found in the argument list are inherited from the enclosing scope.

> f = @(x)x*x; f(8)
ans =  64
> (@(x,y)x+y)(5,6)
ans =  11



### Perl

#### Perl 5

Perl 5 supports anonymous functions, as follows:

(sub { print "I got called\n" })->();         # 1. fully anonymous, called as created

my $squarer = sub { my$x = shift; $x *$x }; # 2. assigned to a variable

sub curry {
my ($sub, @args) = @_; return sub {$sub->(@args, @_) };         # 3. as a return value of another function
}

# example of currying in Perl programming
sub sum { my $tot = 0;$tot += $_ for @_;$tot } # 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 { print for @_ } 1..10; # values not passed like normal Perl function


#### Perl 6

In Perl 6, 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.

{ say "I got called" };           # 1. fully anonymous, called as created

my $squarer1 = ->$x { $x *$x };             # 2a. assigned to a variable, pointy block
my $squarer2 = {$^x * $^x }; # 2b. assigned to a variable, twigil my$squarer3 = { my $x = shift @_;$x * $x }; # 2b. assigned to a variable, Perl 5 style # 3 currying sub add ($m, $n) {$m + $n } my$seven   = add(3, 4);
my $add_one = &add.assuming(m => 1); my$eight   = $add_one($seven);


### PHP

Prior to 4.0.1, PHP had no anonymous function support.[7]

#### PHP 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)

$foo = create_function('$x', 'return $x*$x;');
$bar = create_function("\$x", "return \$x*\$x;");
echo $foo(10);  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.

It must also be noted that each invocation of create_function will create a new function which exists for the rest of the program, and cannot be "garbage collected". If one uses this to create anonymous functions many times, e.g. in a loop, it will irreversibly use up memory in the program.

#### PHP 5.3

PHP 5.3 added a new class called Closure and magic method __invoke() that makes a class instance invocable.[8] Lambda functions are a compiler "trick"[9] that instantiates a new Closure instance that can be invoked as if the function were invokable.

$x = 3;$func = function($z) { return$z *= 2; };
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 objects.

PHP 5.3 does support closures but the variables must be explicitly indicated as such:

$x = 3;$func = function() use(&$x) {$x *= 2; };
$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

Python 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:

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 implement the full power of closures 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:

def make_pow(n):
def fixed_exponent_pow(x):
return pow(x, n)
return fixed_exponent_pow
sqr = make_pow(2)
print sqr(10) # Emits 100
cub = make_pow(3)
print cub(10) # Emits 1000


### R

In GNU R the anonymous functions are defined using the syntax function(argument-list)expression .

f <- function(x)x*x; f(8)
64
(function(x,y)x+y)(5,6)
11



### 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.

# Example 1:
# Purely anonymous functions using blocks.
ex = [16.2, 24.1, 48.3, 32.4, 8.5]
ex.sort_by { |x| x - x.to_i } # sort by fractional part, ignoring integer part.
# [24.1, 16.2, 48.3, 32.4, 8.5]

# Example 2:
# First-class functions as an explicit object of Proc -
ex = Proc.new { puts "Hello, world!" }
ex.call # Hello, world!

# Example 3:
# Function that returns lambda function object with parameters
def is_multiple_of(n)
lambda{|x| x % n == 0}
end
multiple_four = is_multiple_of(4)
multiple_four.call(16)
#true
multiple_four[15]
#false


### Scala

In Scala, anonymous functions use the following syntax:[10]

 (x: Int, y: Int) => x + y


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.

 val list = List(1, 2, 3, 4)
list.reduceLeft( (x, y) => x + y )
// Here, the compiler can infer that the types of x and y are both Int.
// Therefore, it does not require type annotations on the parameters of the anonymous function.

list.reduceLeft( _ + _ )
// Each underscore stands for a new unnamed parameter in the anonymous function.
// This results in an even shorter equivalent to the anonymous function above.


### Smalltalk

In Smalltalk anonymous functions are called blocks

[ :x | x*x ] value: 2
"returns 4"


### Tcl

In Tcl, applying the anonymous squaring function to 2 looks as follows:[11]

apply {x {expr {$x*$x}}} 2
# returns 4


It should be observed that this example involves two candidates for what it means to be a "function" in Tcl. The most generic is usually called a command prefix, and if the variable f holds such a function, then the way to perform the function application f(x) would be

{*}$f$x


where {*} is the expansion prefix (new in Tcl 8.5). The command prefix in the above example is apply {x {expr {$x*$x}}}. Command names can be bound to command prefixes by means of the interp alias command. Command prefixes support currying. Command prefixes are very common in Tcl APIs.

The other candidate for "function" in Tcl is usually called a lambda, and appears as the {x {expr {$x*$x}}} part of the above example. This is the part which caches the compiled form of the anonymous function, but it can only be invoked by being passed to the apply command. Lambdas do not support currying, unless paired with an apply to form a command prefix. Lambdas are rare in Tcl APIs.

### Visual Basic

Visual Basic 2008, 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, 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 Basic 2010, released April 12, 2010, added support for multiline lambda expressions and anonymous functions without a return value. For example, a function for use in a Thread.

Dim t As New System.Threading.Thread(Sub()
For n as Integer = 0 to 10   'Count to 10
Console.WriteLine(n)     'Print each number
Next
End Sub)
t.Start()


### Visual Prolog

Anonymous functions (in general anonymous predicates) were introduced in Visual Prolog in version 7.2.[12] 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:

clauses
mkAdder(X) = { (Y) = X+Y }.


## References

1. ^ ;"JavaScript anonymous functions". Retrieved 2011-02-17. "Anonymous functions are functions that are dynamically declared at runtime that don’t have to be given a name. ... [They] are declared using the function operator. You can use the function operator to create a new function wherever it’s valid to put an expression. For example you could declare a new function as a parameter to a function call or to assign a property of another object."
2. ^ https://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls#Understanding_blocks.2C_Procs_and_methods
3. ^ ;"OpenJDK: Project Lambda". Retrieved 2012-09-24. "JSR 335 (Lambda Expressions for the JavaTM Programming Language) aims to support programming in a multicore environment by adding closures and related features to the Java language. [...] The goal of OpenJDK Project Lambda is to host a prototype implementation of JSR 335 suitable for inclusion in JDK 8, the Reference Implementation of Java SE 8."
4. ^ "Gosu Documentation". Retrieved 4 March 2013.
5. ^ "Groovy Documentation". Retrieved 29 May 2012.
6. ^ "Programming in Lua - More about Functions". Archived from the original on 14 May 2008. Retrieved 2008-04-25.
7. ^ http://php.net/create_function the top of the page indicates this with "(PHP 4 >= 4.0.1, PHP 5)"
8. ^ http://wiki.php.net/rfc/closures
9. ^ http://wiki.php.net/rfc/closures#zend_internal_perspective
10. ^ http://www.scala-lang.org/node/133
11. ^ apply manual page Retrieved 2012-09-06.
12. ^ in Visual Prolog Language Reference

http://www.technetfixes.com/2010/03/c-anonymous-functions.html