Anonymous function: Difference between revisions

Content deleted Content added
Line 497:
|}
 
== Examples of anonymous functions==
{{how-to|section|date=December 2018}}
Numerous languages support anonymous functions, or something similar.
 
{{main|Examples of anonymous functions}}
=== APL ===
Only some dialects support anonymous functions, either as [[direct function | dfn]]s, in the tacit style or a combination of both.
<syntaxhighlight lang="apl">
f←{⍵×⍵} As a dfn
f 1 2 3
1 4 9
g←⊢×⊢ As a tacit 3-train (fork)
g 1 2 3
1 4 9
h←×⍨ As a derived tacit function
h 1 2 3
1 4 9
</syntaxhighlight>
 
=== C (non-standard extension) ===
The anonymous function is not supported by standard C programming language, but supported by some C dialects, such as ''GCC''<ref>{{Cite web|title=Statement Exprs (Using the GNU Compiler Collection (GCC))|url=https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html|access-date=2022-01-12|website=gcc.gnu.org}}</ref> and ''Clang''.
 
==== GCC ====
The [[GNU Compiler Collection]] (GCC) supports anonymous functions, mixed by [[nested function]]s and statement expressions. It has the form:
<syntaxhighlight lang="c">
( { return_type anonymous_functions_name (parameters) { function_body } anonymous_functions_name; } )
</syntaxhighlight>
 
The following example works only with GCC. Because of how macros are expanded, the <code>l_body</code> cannot contain any commas outside of parentheses; GCC treats the comma as a delimiter between macro arguments.
The argument <code>l_ret_type</code> can be removed if <code>__typeof__</code> is available; in the example below using <code>__typeof__</code> on array would return <code>testtype *</code>, which can be dereferenced for the actual value if needed.
<syntaxhighlight lang="c">
#include <stdio.h>
 
//* 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
{
int a;
int b;
} testtype;
 
void printout(const testtype * array)
{
int i;
for ( i = 0; i < 3; ++ i )
printf("%d %d\n", array[i].a, array[i].b);
printf("\n");
}
 
int main(void)
{
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);
return 0;
}
</syntaxhighlight>
 
==== Clang (C, C++, Objective-C, Objective-C++) ====
[[Clang]] supports anonymous functions, called [[Blocks (C language extension)|blocks]],<ref>{{Cite web|title=Language Specification for Blocks — Clang 13 documentation|url=https://clang.llvm.org/docs/BlockLanguageSpec.html|access-date=2022-01-14|website=clang.llvm.org}}</ref> which have the form:
 
<syntaxhighlight lang="c" >
^return_type ( parameters ) { function_body }
</syntaxhighlight>
 
The type of the blocks above is <code>return_type (^)(parameters)</code>.
 
Using the aforementioned ''blocks'' extension and [[Grand Central Dispatch]] (libdispatch), the code could look simpler:
<syntaxhighlight lang="c">
#include <stdio.h>
#include <dispatch/dispatch.h>
 
int main(void) {
void (^count_loop)() = ^{
for (int i = 0; i < 100; i++)
printf("%d\n", i);
printf("ah ah ah\n");
};
 
/* Pass as a parameter to another function */
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), count_loop);
 
/* Invoke directly */
count_loop();
 
return 0;
}
</syntaxhighlight>
 
The code with blocks should be compiled with <code>-fblocks</code> and linked with <code>-lBlocksRuntime</code>
 
=== C++ (since C++11) ===
[[C++11]] supports anonymous functions (technically [[function object]]s), called ''lambda expressions'',<ref>{{Cite web|title=Lambda expressions (since C++11) - cppreference.com|url=https://en.cppreference.com/w/cpp/language/lambda|access-date=2022-01-14|website=en.cppreference.com}}</ref> which have the form:
<syntaxhighlight lang="cpp">
[ captures ] ( params ) specs requires (optional) { body }
</syntaxhighlight>
where "<code>specs</code>" is of the form "<code>specifiers exception [[C++11#Attributes|attr]] [[C++11#Alternative function syntax|trailing-return-type]]</code> in that order; each of these components is optional". If it is absent, the return type is deduced from <code>return</code> statements as if for a function with declared return type <code>auto</code>.
 
This is an example lambda expression:
<syntaxhighlight lang="cpp">
[](int x, int y) { return x + y; }
</syntaxhighlight>
 
C++11 also supports [[Closure (computer science)|closures]], here called captures. Captures are defined between square brackets <code>[</code>and <code>]</code> in the declaration of lambda expression. The mechanism allows these variables to be captured by value or by reference. The following table demonstrates this:
 
<syntaxhighlight lang="cpp">
[] // No captures, the lambda is implicitly convertible to a function pointer.
[x, &y] // x is captured by value and 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 captured by value. Other variables will be captured by reference.
[=, &z] // z is captured by reference. Other variables will be captured by value.
</syntaxhighlight>
 
Variables captured by value are constant by default. Adding <code>mutable</code> after the parameter list makes them non-constant.
 
[[C++14]] and newer versions support init-capture, for example:
<syntaxhighlight lang="cpp">
std::unique_ptr<int> ptr = std::make_unique<int>(42);
[ptr]{ /* ... */ }; // copy assignment is deleted for a unique pointer
[ptr = std::move(ptr)]{ /* ... */ }; // ok
 
auto counter = [i = 0]() mutable { return i++; }; // mutable is required to modify 'i'
counter(); // 0
counter(); // 1
counter(); // 2
</syntaxhighlight>
 
The following two examples demonstrate use of a lambda expression:
<syntaxhighlight lang="cpp">
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; });
// Note that std::accumulate would be a way better alternative here...
</syntaxhighlight>
 
This computes the total of all elements in the list. The variable <code>total</code> is stored as a part of the lambda function's closure. Since it is a reference to the stack variable <code>total</code>, it can change its value.
 
<syntaxhighlight lang="cpp">
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),
[&total, value, this](int x) { total += x * value * this->some_func(); });
</syntaxhighlight>
 
This will cause <code>total</code> to be stored as a reference, but <code>value</code> will be stored as a copy.
 
The capture of <code>this</code> is special. It can only be captured by value, not by reference. However in [[C++17]], the current object can be captured by value (denoted by <code>*this</code>), or can be captured by reference (denoted by <code>this</code>). <code>this</code> 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 <code>this</code> is captured, either explicitly or implicitly, then the scope of the enclosed class members is also tested. Accessing members of <code>this</code> does not need explicit use of <code>this-></code> 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 [[inline expansion|inlining]], and thus need no added 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 behaviour|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 parameter type must be a template type, or they must create a <code>std::function</code> or a similar object to capture the lambda value. The use of the <code>auto</code> keyword can help store the lambda function,
<syntaxhighlight lang="cpp">
auto my_lambda_func = [&](int x) { /*...*/ };
auto my_onheap_lambda_func = new auto([=](int x) { /*...*/ });
</syntaxhighlight>
 
Here is an example of storing anonymous functions in variables, vectors, and arrays; and passing them as named parameters:
<syntaxhighlight lang="cpp">
#include <functional>
#include <iostream>
#include <vector>
 
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 (size_t i = 0; i < fv.size(); i++) {
std::cout << fv[i](2.0) << std::endl;
}
for (size_t i = 0; i < 3; i++) {
std::cout << fa[i](2.0) << std::endl;
}
for (auto& f : fv) {
std::cout << f(2.0) << std::endl;
}
for (auto& f : fa) {
std::cout << f(2.0) << std::endl;
}
std::cout << eval(f0) << std::endl;
std::cout << eval(f1) << std::endl;
std::cout << eval([](double x) { return x * x; }) << std::endl;
}
</syntaxhighlight>
A lambda expression with an empty capture specification (<code>[]</code>) can be implicitly converted into a function pointer with the same type as the lambda was declared with. So this is legal:
 
<syntaxhighlight lang="cpp">
auto a_lambda_func = [](int x) -> void { /*...*/ };
void (* func_ptr)(int) = a_lambda_func;
func_ptr(4); //calls the lambda.
</syntaxhighlight>
 
Since [[C++17]], a lambda can be declared <code>[[constexpr]]</code>, and since [[C++20]], <code>[[consteval]]</code> with the usual semantics. These specifiers go after the parameter list, like <code>mutable</code>. Starting from [[C++23]], the lambda can also be <code>[[static member function|static]]</code> if it has no captures. The <code>static</code> and <code>mutable</code> specifiers are not allowed to be combined.
 
Also since C++23 a lambda expression can be recursive through explicit <code>this</code> as first parameter:
 
<syntaxhighlight lang="cpp">
auto fibonacci = [](this auto self, int n) { return n <= 1 ? n : self(n - 1) + self(n - 2); };
fibonacci(7); // 13
</syntaxhighlight>
 
In addition to that, C++23 modified the syntax so that the parentheses can be omitted in the case of a lambda that takes no arguments even if the lambda has a specifier. It also made it so that an attribute specifier sequence that appears before the parameter list, lambda specifiers, or noexcept specifier (there must be one of them) applies to the function call operator or operator template of the closure type. Otherwise, it applies to the type of the function call operator or operator template. Previously, such a sequence always applied to the type of the function call operator or operator template of the closure type making e.g the <code>[<nowiki/>[noreturn]]</code> attribute impossible to use with lambdas.
 
The [[Boost (C++ libraries)|Boost]] library provides its own syntax for lambda functions as well, using the following syntax:<ref>{{cite web |url=http://www.boost.org/doc/libs/1_57_0/doc/html/lambda.html|title=Chapter 16. Boost.Lambda|last1=Järvi|first1=Jaakko|last2=Powell|first2=Gary|date=n.d.|website=Boost Documentation|publisher=Boost|access-date=December 22, 2014}}</ref>
 
<syntaxhighlight lang="cpp">
for_each(a.begin(), a.end(), std::cout << _1 << ' ');
</syntaxhighlight>
 
Since [[C++14]], the function parameters of a lambda can be declared with <code>auto</code>. The resulting lambda is called a ''generic lambda'' and is essentially an anonymous function template since the rules for type deduction of the auto parameters are the rules of template argument deduction. As of [[C++20]], template parameters can also be declared explicitly with the following syntax:
<syntaxhighlight lang="cpp">
[ captures ] < tparams > requires (optional) ( params ) specs requires (optional) { body }
</syntaxhighlight>
 
=== C# ===
In [[C Sharp (programming language)|C#]], support for anonymous functions has deepened through the various versions of the language compiler. The language v3.0, released in November 2007 with [[.NET Framework]] v3.5, has full support of anonymous functions.<ref name="Skeet">{{cite book |last=Skeet|first=Jon|title= C# in Depth |date=23 March 2019 |publisher= Manning |isbn= 978-1617294532}}</ref>{{rp|7-8}}<ref name="Albahari">{{cite book |last=Albahari |first=Joseph |title= C# 10 in a Nutshell |year=2022 |publisher= O'Reilly |isbn= 978-1-098-12195-2}}</ref>{{rp|26}} C# names them ''lambda expressions'', following the original version of anonymous functions, the [[lambda calculus]].<ref>{{Cite web|url=https://www.microsoft.com/en-us/download/details.aspx?id=7029|title=C# Language Specification 5.0|website=Microsoft Download Center}}</ref><ref name="Skeet"/>{{rp|7-8, 91}}<ref name="Albahari"/>{{rp|91}}
 
''// 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" />''
<syntaxhighlight lang="csharp" inline>Func<int,int> foo = x => x * x;</syntaxhighlight>
<syntaxhighlight lang="csharp" inline>Console.WriteLine(foo(7));</syntaxhighlight>
 
While the function is anonymous, it cannot be assigned to an implicitly typed variable, because the lambda syntax may be used for denoting an anonymous function or an expression tree, and the choice cannot automatically be decided by the compiler.<ref name="Skeet"/>{{rp|101-103}} E.g., this does not work:
<syntaxhighlight lang="csharp">
// will NOT compile!
var foo = (int x) => x * x;
</syntaxhighlight>
 
However, a lambda expression can take part in [[type inference]] and can be used as a [[Parameter (computer science)|method argument]], e.g. to use anonymous functions with the Map capability available with <code>System.Collections.Generic.List</code> (in the <code>ConvertAll()</code> method):
<syntaxhighlight lang="csharp">
// 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>
</syntaxhighlight>
 
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 [[Delegate (CLI)|delegates]].<ref name="Skeet"/>{{rp|6}} C# names them ''lambda expressions'', following the original version of anonymous functions, the [[lambda calculus]].<ref name="Skeet"/>{{rp|91}} 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 unneeded 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.<ref name="Skeet"/>{{rp|6-7}} 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:
 
<syntaxhighlight lang="csharp">
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 needed
// initializing 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 one input and
// returns one output can also be implicitly declared with the Func<> type.
System.Func<int,int> D = x => x * x;
System.Console.WriteLine(D(9));
}
}
</syntaxhighlight>
 
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 (computer science)|reflection]].<ref name="Skeet"/>{{rp|103}}
In the case of the C# 3.0 version, the same mechanism applies.
 
=== ColdFusion Markup Language (CFML) ===
 
Using the {{samp|function}} keyword:
 
<syntaxhighlight lang=CFC>
fn = function(){
// statements
};
</syntaxhighlight>
 
Or using an arrow function:
 
<syntaxhighlight lang=CFC>
fn = () => {
// statements
};
 
fn = () => singleExpression // singleExpression is implicitly returned. There is no need for the braces or the return keyword
 
fn = singleParam => { // if the arrow function has only one parameter, there's no need for parentheses
// statements
}
 
fn = (x, y) => { // if the arrow function has zero or multiple parameters, one needs to use parentheses
// statements
}
 
 
</syntaxhighlight>
 
CFML supports any statements within the function's definition, not simply expressions.
 
CFML supports recursive anonymous functions:
<syntaxhighlight lang=CFC>
factorial = function(n){
return n > 1 ? n * factorial(n-1) : 1;
};
</syntaxhighlight>
CFML anonymous functions implement closure.
 
=== D ===
D uses inline [[Delegation (programming)|delegates]] to implement anonymous functions. The full syntax for an inline delegate is
<syntaxhighlight lang="d">
return_type delegate(arguments){/*body*/}
</syntaxhighlight>
If unambiguous, the return type and the keyword ''delegate'' can be omitted.
<syntaxhighlight lang="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
</syntaxhighlight>
Since version 2.0, [[D programming language|D]] allocates closures on the heap unless the compiler can prove it is unnecessary; the <code>scope</code> keyword can be used for forcing stack allocation.
Since version 2.058, it is possible to use shorthand notation:
<syntaxhighlight lang="d">
x => x*x;
(int x) => x*x;
(x,y) => x*y;
(int x, int y) => x*y;
</syntaxhighlight>
An anonymous function can be assigned to a variable and used like this:
<syntaxhighlight lang="d">
auto sqr = (double x){return x*x;};
double y = sqr(4);
</syntaxhighlight>
 
===Dart===
[[Dart (programming language)|Dart]] supports anonymous functions.<ref name=":0" />
<syntaxhighlight lang="javascript">
var sqr = (x) => x * x;
print(sqr(5));
</syntaxhighlight>
or
<syntaxhighlight lang="javascript">
print(((x) => x * x)(5));
</syntaxhighlight>
 
===Delphi===
[[Delphi (programming language)|Delphi]] introduced anonymous functions in version 2009.
<syntaxhighlight lang="delphi">
program demo;
 
type
TSimpleProcedure = reference to procedure;
TSimpleFunction = reference to function(const x: string): Integer;
 
var
x1: TSimpleProcedure;
y1: TSimpleFunction;
 
begin
x1 := procedure
begin
Writeln('Hello World');
end;
x1; //invoke anonymous method just defined
 
y1 := function(const x: string): Integer
begin
Result := Length(x);
end;
Writeln(y1('bar'));
end.
</syntaxhighlight>
 
===PascalABC.NET===
[[PascalABC.NET]] supports anonymous functions using lambda syntax
<syntaxhighlight lang="delphi">
begin
var n := 10000000;
var pp := (1..n)
.Select(x -> (Random, Random))
.Where(p -> Sqr(p[0]) + Sqr(p[1]) < 1)
.Count / n * 4;
Print(pp);
end.
</syntaxhighlight>
 
===Elixir===
[[Elixir (programming language)|Elixir]] uses the [[Closure (computer programming)|closure]] <code>fn</code> for anonymous functions.<ref name=":1" />
<syntaxhighlight lang="elixir">
sum = fn(a, b) -> a + b end
sum.(4, 3)
#=> 7
 
square = fn(x) -> x * x end
Enum.map [1, 2, 3, 4], square
#=> [1, 4, 9, 16]
</syntaxhighlight>
 
===Erlang===
[[Erlang (programming language)|Erlang]] uses a syntax for anonymous functions similar to that of named functions.<ref name=":2" />
<syntaxhighlight lang="erlang">
% Anonymous function bound to the Square variable
Square = fun(X) -> X * X end.
 
% Named function with the same functionality
square(X) -> X * X.
</syntaxhighlight>
 
===Go===
 
[[Go (programming language)|Go]] supports anonymous functions.<ref name=":4" />
 
<syntaxhighlight lang="go">
foo := func(x int) int {
return x * x
}
fmt.Println(foo(10))
</syntaxhighlight>
 
=== Haskell ===
[[Haskell (programming language)|Haskell]] uses a concise syntax for anonymous functions (lambda expressions). The backslash is supposed to resemble &lambda;.
 
<syntaxhighlight lang="haskell">
\x -> x * x
</syntaxhighlight>
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).
<syntaxhighlight lang="haskell">
map (\x -> x * x) [1..5] -- returns [1, 4, 9, 16, 25]
</syntaxhighlight>
 
The following are all equivalent:
<syntaxhighlight lang="haskell">
f x y = x + y
f x = \y -> x + y
f = \x y -> x + y
</syntaxhighlight>
 
=== Haxe ===
In [[Haxe]], anonymous functions are called lambda, and use the syntax <code>function(argument-list) expression;</code> .
<syntaxhighlight lang="actionscript">
var f = function(x) return x*x;
f(8); // 64
 
(function(x,y) return x+y)(5,6); // 11
</syntaxhighlight>
 
=== Java ===
[[Java (programming language)|Java]] supports anonymous functions, named ''Lambda Expressions'', starting with [[Java 8|JDK 8]].<ref>{{Cite web|url=http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html|title=What's New in JDK 8}}</ref>
 
A lambda expression consists of a comma separated list of the formal parameters enclosed in parentheses, an arrow token (<code>-></code>), and a body. Data types of the parameters can always be omitted, as can the parentheses if there is only one parameter. The body can consist of one statement or a statement block.<ref name="JavaLambda" />
 
<syntaxhighlight lang="java">
// with no parameter
() -> System.out.println("Hello, world.")
 
// with one parameter (this example is an identity function).
a -> a
 
// with one expression
(a, b) -> a + b
 
// with explicit type information
(long id, String name) -> "id: " + id + ", name:" + name
 
// with a code block
(a, b) -> { return a + b; }
 
// with multiple statements in the lambda body. It needs a code block.
// This example also includes two nested lambda expressions (the first one is also a closure).
(id, defaultPrice) -> {
Optional<Product> product = productList.stream().filter(p -> p.getId() == id).findFirst();
return product.map(p -> p.getPrice()).orElse(defaultPrice);
}
</syntaxhighlight>
 
Lambda expressions are converted to "functional interfaces" (defined as interfaces that contain only one abstract method in addition to one or more default or static methods),<ref name="JavaLambda">[http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html ''The Java Tutorials: Lambda Expressions''], docs.oracle.com</ref> as in the following example:
 
<syntaxhighlight lang="java">
public class Calculator {
interface IntegerMath {
int operation(int a, int b);
 
default IntegerMath swap() {
return (a, b) -> operation(b, a);
}
}
 
private static int apply(int a, int b, IntegerMath op) {
return op.operation(a, b);
}
 
public static void main(String... args) {
IntegerMath addition = (a, b) -> a + b;
IntegerMath subtraction = (a, b) -> a - b;
System.out.println("40 + 2 = " + apply(40, 2, addition));
System.out.println("20 - 10 = " + apply(20, 10, subtraction));
System.out.println("10 - 20 = " + apply(20, 10, subtraction.swap()));
}
}
</syntaxhighlight>
 
In this example, a functional interface called <code>IntegerMath</code> is declared. Lambda expressions that implement <code>IntegerMath</code> are passed to the <code>apply()</code> method to be executed. Default methods like <code>swap</code> define methods on functions.
 
Java 8 introduced another mechanism named method reference (the <code>::</code> operator) to create a lambda on an existing method. A method reference does not indicate the number or types of arguments because those are extracted from the abstract method of the functional interface.
<syntaxhighlight lang="java">
IntBinaryOperator sum = Integer::sum;
</syntaxhighlight>
In the example above, the functional interface <code>IntBinaryOperator</code> declares an abstract method <code>int applyAsInt(int, int)</code>, so the compiler looks for a method <code>int sum(int, int)</code> in the class <code>java.lang.Integer</code>.
 
==== Differences compared to Anonymous Classes ====
 
[https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html Anonymous classes] of lambda-compatible interfaces are similar, but not exactly equivalent, to lambda expressions.
To illustrate, in the following example, {{code|anonymousClass}} and {{code|lambdaExpression}} are both instances of {{code|IntegerMath}} that add their two parameters:
 
<syntaxhighlight lang="java">
IntegerMath anonymousClass = new IntegerMath() {
@Override
public int operation(int a, int b) {
return a + b;
}
};
IntegerMath lambdaExpression = (a, b) -> a + b;
</syntaxhighlight>
 
The main difference here is that the lambda expression does not necessarily need to allocate a new instance for the {{code|IntegerMath}}, and can return the same instance every time this code is run.<ref>{{Cite web|url=https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27.4|title=Chapter&nbsp;15.&nbsp;Expressions|website=docs.oracle.com}}</ref>
Additionally, in the [[OpenJDK]] implementation at least, lambdas are compiled to {{mono|invokedynamic}} instructions, with the lambda body inserted as a static method into the surrounding class,<ref>{{cite web |title=jdk/LambdaMethod.java |website=[[GitHub]] |url=https://github.com/openjdk/jdk/blob/master/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java#L329-L334}}</ref> rather than generating a new class file entirely.
 
==== Java limitations ====
Java 8 lambdas have the following limitations:
* Lambdas can throw checked exceptions, but such lambdas will not work with the interfaces used by the Collection API.
* Variables that are in-scope where the lambda is declared may only be accessed inside the lambda if they are effectively final, i.e. if the variable is not mutated inside or outside of the lambda scope.
 
===JavaScript===
[[JavaScript]]/[[ECMAScript]] supports anonymous functions.
<syntaxhighlight lang="javascript">
alert((function(x){
return x * x;
})(10));
</syntaxhighlight>
 
[[ES6]] supports "arrow function" syntax, where a '''=>''' symbol separates the anonymous function's parameter list from the body:
<syntaxhighlight lang="javascript">
alert((x => x * x)(10));
</syntaxhighlight>
 
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.
<syntaxhighlight lang="javascript">
document.title=___location.href;
</syntaxhighlight>
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:
<syntaxhighlight lang="javascript">
(function(){document.title=___location.href;})();
</syntaxhighlight>
 
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 <code>f</code> unlike an anonymous function.
<syntaxhighlight lang="javascript">
var f = function(){document.title=___location.href;}; f();
</syntaxhighlight>
 
Use [[Bookmarklets#History|void()]] to avoid new pages for arbitrary anonymous functions:
<syntaxhighlight lang="javascript">
void(function(){return document.title=___location.href;}());
</syntaxhighlight>
or just:
<syntaxhighlight lang="javascript">
void(document.title=___location.href);
</syntaxhighlight>
 
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:
<syntaxhighlight lang="javascript">(function(){ ... }())</syntaxhighlight> and
<syntaxhighlight lang="javascript">(function(){ ... })()</syntaxhighlight>
Representing "<code>function(){ ... }</code>" by <code>f</code>, the form of the constructs are
a parenthetical within a parenthetical <code>(f())</code> and a parenthetical applied to a parenthetical <code>(f)()</code>.
 
Note the general syntactic ambiguity of a parenthetical expression, parenthesized arguments to a function and the parentheses around the formal parameters in a function definition. In particular, JavaScript defines a <code>,</code> (comma) operator in the context of a parenthetical expression. It is no mere coincidence that the syntactic forms coincide for an expression and a function's arguments (ignoring the function formal parameter syntax)! If <code>f</code> is not identified in the constructs above, they become <code>(())</code> and <code>()()</code>. 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 <code>()</code>'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, <code>{}</code> for braced code, are used when defining a function this way (as opposed to using <code>new Function(...)</code>). In a very broad non-rigorous sense (especially since global bindings are compromised), an arbitrary sequence of braced JavaScript statements, <code>{stuff}</code>, can be considered to be a [[Fixed point (mathematics)|fixed point]] of
<syntaxhighlight lang="javascript">
(function(){( function(){( ... {( function(){stuff}() )} ... )}() )}() )
</syntaxhighlight>
More correctly but with caveats,
<syntaxhighlight lang="javascript">
( function(){stuff}() ) ~=
A_Fixed_Point_of(
function(){ return function(){ return ... { return function(){stuff}() } ... }() }()
)
</syntaxhighlight>
 
Note the implications of the anonymous function in the JavaScript fragments that follow:
 
* <code>function(){ ... }()</code> without surrounding <code>()</code>'s is generally not legal
* <code>(f=function(){ ... })</code> does not "forget" <code>f</code> globally unlike <code>(function f(){ ... })</code>
 
:::Performance [[Software metric|metrics]] to analyze the [[Space complexity theory|space]] and [[Time complexity|time]] [[Computational complexity theory|complexities]] of function calls, call stack, etc. in a JavaScript [[Interpreter (computing)|interpreter]] [[Software engine|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]].
 
=== Julia ===
In [[Julia (programming language)|Julia]] anonymous functions are defined using the syntax <code>(arguments)->(expression)</code>,
<syntaxhighlight lang="jlcon">
julia> f = x -> x*x; f(8)
64
julia> ((x,y)->x+y)(5,6)
11
</syntaxhighlight>
 
===Kotlin===
[[Kotlin (programming language)|Kotlin]] supports anonymous functions with the syntax <code>{arguments -> expression}</code>,
<syntaxhighlight lang="kotlin">
val sum = { x: Int, y: Int -> x + y }
sum(5,6) // returns 11
val even = { x: Int -> x%2==0}
even(4) // returns true
</syntaxhighlight>
 
===Lisp===
[[Lisp (programming language)|Lisp]] and [[Scheme (programming language)|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.
<syntaxhighlight lang="lisp">
(lambda (arg) (* arg arg))
</syntaxhighlight>
 
====Common Lisp====
[[Common Lisp]] has the concept of lambda expressions. A lambda expression is written as a list with the symbol "lambda" as its first element. The list then contains the argument list, documentation or declarations and a function body. Lambda expressions can be used inside lambda forms and with the special operator "function".
 
<syntaxhighlight lang="lisp">
(function (lambda (arg) (do-something arg)))
</syntaxhighlight>
 
"function" can be abbreviated as #'. Also, macro ''lambda'' exists, which expands into a function form:
<syntaxhighlight lang="lisp">
; using sharp quote
#'(lambda (arg) (do-something arg))
; using the lambda macro:
(lambda (arg) (do-something arg))
</syntaxhighlight>
 
One typical use of anonymous functions in Common Lisp is to pass them to higher-order functions like ''mapcar'', which applies a function to each element of a list and returns a list of the results.
<syntaxhighlight lang="lisp">
(mapcar #'(lambda (x) (* x x))
'(1 2 3 4))
; -> (1 4 9 16)
</syntaxhighlight>
 
The ''lambda form'' in Common Lisp allows a ''lambda expression'' to be written in a function call:
<syntaxhighlight lang="lisp">
((lambda (x y)
(+ (sqrt x) (sqrt y)))
10.0
12.0)
</syntaxhighlight>
 
Anonymous functions in Common Lisp can also later be given global names:
<syntaxhighlight lang="lisp">
(setf (symbol-function 'sqr)
(lambda (x) (* x x)))
; which allows us to call it using the name SQR:
(sqr 10.0)
</syntaxhighlight>
 
====Scheme====
[[Scheme (programming language)|Scheme's]] ''named functions'' is simply [[syntactic sugar]] for anonymous functions bound to names:
<syntaxhighlight lang="scheme">
(define (somename arg)
(do-something arg))
</syntaxhighlight>
expands (and is equivalent) to
<syntaxhighlight lang="scheme">
(define somename
(lambda (arg)
(do-something arg)))
</syntaxhighlight>
 
====Clojure====
[[Clojure]] supports anonymous functions through the "fn" special form:
<syntaxhighlight lang="clojure">
(fn [x] (+ x 3))
</syntaxhighlight>
There is also a reader syntax to define a lambda:
<syntaxhighlight lang="clojure">
#(+ % %2%3) ; Defines an anonymous function that takes three arguments and sums them.
</syntaxhighlight>
 
Like Scheme, Clojure's "named functions" are simply syntactic sugar for lambdas bound to names:
<syntaxhighlight lang="clojure">
(defn func [arg] (+ 3 arg))
</syntaxhighlight>
expands to:
<syntaxhighlight lang="clojure">
(def func (fn [arg] (+ 3 arg)))
</syntaxhighlight>
 
===Lua===
In [[Lua (programming language)|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.<ref>{{cite web |title=Programming in Lua - More about Functions |url=http://www.lua.org/pil/6.html |access-date=2008-04-25 |archive-url=https://web.archive.org/web/20080514220940/http://www.lua.org/pil/6.html |archive-date=14 May 2008 |url-status=live}}</ref>
 
Thus, in Lua
<syntaxhighlight lang="lua">
function foo(x) return 2*x end
</syntaxhighlight>
is just syntactical sugar for
<syntaxhighlight lang="lua">
foo = function(x) return 2*x end
</syntaxhighlight>
 
An example of using anonymous functions for reverse-order sorting:
<syntaxhighlight lang="lua">
table.sort(network, function(a,b)
return a.name > b.name
end)
</syntaxhighlight>
 
===Wolfram Language, Mathematica===
The [[Wolfram Language]] is the programming language of [[Mathematica]]. Anonymous functions are important in programming the latter. There are several ways to create them. Below are a few anonymous functions that increment a number. The first is the most common. <code>#1</code> refers to the first argument and <code>&</code> marks the end of the anonymous function.
 
<syntaxhighlight lang="mathematica">
#1+1&
Function[x,x+1]
x \[Function] x+1
</syntaxhighlight>
 
So, for instance:
 
<syntaxhighlight lang="mathematica">
f:= #1^2&;f[8]
64
#1+#2&[5,6]
11
</syntaxhighlight>
 
Also, Mathematica has an added construct to make recursive anonymous functions. The symbol '#0' refers to the entire function. The following function calculates the factorial of its input:
<syntaxhighlight lang="mathematica">
If[#1 == 1, 1, #1 * #0[#1-1]]&
</syntaxhighlight>
For example, 6 factorial would be:
 
<syntaxhighlight lang="mathematica">
If[#1 == 1, 1, #1 * #0[#1-1]]&[6]
720
</syntaxhighlight>
 
===MATLAB, Octave===
Anonymous functions in [[MATLAB]] or [[GNU Octave|Octave]] are defined using the syntax <code>@(argument-list)expression</code>. Any variables that are not found in the argument list are inherited from the enclosing scope and are captured by value.
<syntaxhighlight lang="matlab">
>> f = @(x)x*x; f(8)
ans = 64
>> (@(x,y)x+y)(5,6) % Only works in Octave
ans = 11
</syntaxhighlight>
 
===Maxima===
In [[Maxima (software)|Maxima]] anonymous functions are defined using the syntax <code>lambda(argument-list,expression)</code>,
<syntaxhighlight lang="maxima" highlight="1,4">
f: lambda([x],x*x); f(8);
64
 
lambda([x,y],x+y)(5,6);
11
</syntaxhighlight>
 
===ML===
The various dialects of [[ML (programming language)|ML]] support anonymous functions.
 
====[[OCaml]]====
 
Anonymous functions in OCaml are functions without a declared name. Here is an example of an anonymous function that multiplies its input by two:
 
<syntaxhighlight lang="ocaml">fun x -> x*2</syntaxhighlight>
 
In the example, fun is a keyword indicating that the function is an anonymous function. We are passing in an argument x and -> to separate the argument from the body.<ref>{{Cite web|url=https://www.cs.cornell.edu/courses/cs3110/2019sp/textbook/basics/anonymous_functions.html|title=2.7. Anonymous Functions · GitBook|website=www.cs.cornell.edu}}</ref>
 
====F#====
[[F Sharp (programming language)|F#]] supports anonymous functions,<ref name=":3" /> as follows:
<syntaxhighlight lang="fsharp">
(fun x -> x * x) 20 // 400
</syntaxhighlight>
 
====Standard ML====
[[Standard ML]] supports anonymous functions, as follows:
<pre>
fn arg => arg * arg
</pre>
 
===Nim===
[[Nim (programming language)|Nim]] supports multi-line multi-expression anonymous functions. <ref name="auto1"/>
 
<syntaxhighlight lang="nim">
var anon = proc (var1, var2: int): int = var1 + var2
assert anon(1, 2) == 3
</syntaxhighlight>
 
Multi-line example:
 
<syntaxhighlight lang="nim">
var anon = func (x: int): bool =
if x > 0:
result = true
else:
result = false
 
assert anon(9)
</syntaxhighlight>
 
Anonymous functions may be passed as input parameters of other functions:
 
<syntaxhighlight lang="nim">
var cities = @["Frankfurt", "Tokyo", "New York"]
 
cities.sort(
proc (x, y: string): int = cmp(x.len, y.len)
)
</syntaxhighlight>
 
An anonymous function is basically a function without a name.
 
===Perl===
 
====Perl 5====
[[Perl 5]] supports anonymous functions,<ref name=":5" /> as follows:
<syntaxhighlight lang="perl">
(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 )
</syntaxhighlight>
 
Other constructs take ''bare blocks'' as arguments, which serve a function similar to lambda functions of one parameter, but do not have the same parameter-passing convention as functions -- @_ is not set.
 
<syntaxhighlight lang="perl">
my @squares = map { $_ * $_ } 1..10; # map and grep don't use the 'sub' keyword
my @square2 = map $_ * $_, 1..10; # braces unneeded for one expression
 
my @bad_example = map { print for @_ } 1..10; # values not passed like normal Perl function
</syntaxhighlight>
 
===PHP===
Before 4.0.1, [[PHP]] had no anonymous function support.<ref>http://php.net/create_function the top of the page indicates this with "(PHP 4 >= 4.0.1, PHP 5)"</ref>
 
====PHP 4.0.1 to 5.3====
PHP 4.0.1 introduced the <code>create_function</code> which was the initial anonymous function support. This function call makes a new randomly named function and returns its name (as a string)
 
<syntaxhighlight lang="php">
$foo = create_function('$x', 'return $x*$x;');
$bar = create_function("\$x", "return \$x*\$x;");
echo $foo(10);
</syntaxhighlight>
 
The argument list and function body must be in single quotes, or the dollar signs must be escaped.
Otherwise, PHP assumes "<code>$x</code>" means the variable <code>$x</code> and will substitute it into the string (despite possibly not existing) instead of leaving "<code>$x</code>" in the string.
For functions with quotes or functions with many variables, it can get quite tedious to ensure the intended function body is what PHP interprets.
 
Each invocation of <code>create_function</code> makes a new function, which exists for the rest of the program, and cannot be ''[[Garbage collection (computer science)|garbage collected]]'', using memory in the program irreversibly. If this is used to create anonymous functions many times, e.g., in a loop, it can cause problems such as memory bloat.
 
====PHP 5.3====
PHP 5.3 added a new class called <code>Closure</code> and magic method <code>__invoke()</code> that makes a class instance invocable.<ref>{{Cite web|url=https://wiki.php.net/rfc/closures|title=PHP: rfc:closures|website=wiki.php.net}}</ref>
<syntaxhighlight lang="php">
$x = 3;
$func = function($z) { return $z * 2; };
echo $func($x); // prints 6
</syntaxhighlight>
 
In this example, <code>$func</code> is an instance of <code>Closure</code> and <code>echo $func($x)</code> is equivalent to <code>echo $func->__invoke($x)</code>.
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:
 
<syntaxhighlight lang="php">
$x = 3;
$func = function() use(&$x) { $x *= 2; };
$func();
echo $x; // prints 6
</syntaxhighlight>
 
The variable <code>$x</code> is bound by reference so the invocation of <code>$func</code> modifies it and the changes are visible outside of the function.
 
====PHP 7.4====
Arrow functions were introduced in PHP 7.4
<syntaxhighlight lang="php">
$x = 3;
$func = fn($z) => $z * 2;
echo $func($x); // prints 6
</syntaxhighlight>
 
=== Prolog's dialects ===
 
==== Logtalk ====
[[Logtalk]] uses the following syntax for anonymous predicates (lambda expressions):
<syntaxhighlight lang="logtalk">
{FreeVar1, FreeVar2, ...}/[LambdaParameter1, LambdaParameter2, ...]>>Goal
</syntaxhighlight>
A simple example with no free variables and using a list mapping predicate is:
<syntaxhighlight lang="logtalk">
| ?- meta::map([X,Y]>>(Y is 2*X), [1,2,3], Ys).
Ys = [2,4,6]
yes
</syntaxhighlight>
Currying is also supported. The above example can be written as:
<syntaxhighlight lang="logtalk">
| ?- meta::map([X]>>([Y]>>(Y is 2*X)), [1,2,3], Ys).
Ys = [2,4,6]
yes
</syntaxhighlight>
 
==== Visual Prolog ====
Anonymous functions (in general anonymous ''predicates'') were introduced in [[Visual Prolog]] in version 7.2.<ref>{{cite web |title=Anonymous Predicates |url=http://wiki.visual-prolog.com/index.php?title=Language_Reference/Terms#Anonymous_Predicates}} in Visual Prolog Language Reference</ref> Anonymous predicates can capture values from the context. If created in an object member, it can also access the object state (by capturing <code>This</code>).
 
<code>mkAdder</code> returns an anonymous function, which has captured the argument <code>X</code> in the closure. The returned function is a function that adds <code>X</code> to its argument:
 
<syntaxhighlight lang="Prolog">
clauses
mkAdder(X) = { (Y) = X+Y }.
</syntaxhighlight>
 
===Python===
[[Python (programming language)|Python]] supports simple anonymous functions through the lambda form.<ref name=":6" /> 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:
 
<syntaxhighlight lang="pycon">
>>> foo = lambda x: x * x
>>> foo(10)
100
</syntaxhighlight>
 
In general, the Python convention encourages the use of named functions defined in the same scope as one might typically use an anonymous function in other languages. This is acceptable as locally defined functions implement the full power of [[closure (computer science)|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 [[Currying|curried]]:
 
<syntaxhighlight lang="pycon">
>>> def make_pow(n):
... def fixed_exponent_pow(x):
... return pow(x, n)
... return fixed_exponent_pow
...
>>> sqr = make_pow(2)
>>> sqr(10)
100
>>> cub = make_pow(3)
>>> cub(10)
1000
</syntaxhighlight>
 
===R===
{{details|R (programming language)}}
In R the anonymous functions are defined using the syntax <code>function(argument-list)expression</code> , which has shorthand since version 4.1.0 <code>\</code>, akin to Haskell.
<syntaxhighlight lang="rout">
> f <- function(x)x*x; f(8)
[1] 64
> (function(x,y)x+y)(5,6)
[1] 11
> # Since R 4.1.0
> (\(x,y) x+y)(5, 6)
[1] 11
</syntaxhighlight>
 
===Raku===
In [[Raku (programming language)|Raku]], all blocks (even those associated with if, while, etc.) are anonymous functions. A block that is not used as an [[Value (computer science)|rvalue]] is executed immediately.
 
# fully anonymous, called as created
#: <syntaxhighlight lang="perl6">
{ say "I got called" };
</syntaxhighlight>
# assigned to a variable
#:<syntaxhighlight lang="perl6">
my $squarer1 = -> $x { $x * $x }; # 2a. pointy block
my $squarer2 = { $^x * $^x }; # 2b. twigil
my $squarer3 = { my $x = shift @_; $x * $x }; # 2c. Perl 5 style
</syntaxhighlight>
# currying
#:<syntaxhighlight lang="perl6" highlight="4">
sub add ($m, $n) { $m + $n }
my $seven = add(3, 4);
my $add_one = &add.assuming(m => 1);
my $eight = $add_one($seven);
</syntaxhighlight>
# WhateverCode object
#:<syntaxhighlight lang="perl6">
my $w = * - 1; # WhateverCode object
my $b = { $_ - 1 }; # same functionality, but as Callable block
</syntaxhighlight>
 
===Ruby===
{{details|Ruby (programming language)#Blocks and iterators}}
 
Ruby supports anonymous functions by using a syntactical structure called ''block''. There are two data types for blocks in Ruby. <code>Proc</code>s behave similarly to [[Closure (computer programming)|closures]], whereas <code>lambda</code>s behave more analogous to an anonymous function.<ref name=":10">{{cite web|url=http://www.reactive.io/tips/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/ |title=Understanding Ruby Blocks, Procs and Lambdas |last=Sosinski |first=Robert |publisher=Reactive.IO |date=2008-12-21 |access-date=2014-05-30 |url-status=dead |archive-url=https://web.archive.org/web/20140531123646/http://www.reactive.io/tips/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/ |archive-date=2014-05-31 }}</ref> When passed to a method, a block is converted into a Proc in some circumstances.
 
<syntaxhighlight lang="ruby">
# Example 1:
# Purely anonymous functions using blocks.
ex = [16.2, 24.1, 48.3, 32.4, 8.5]
=> [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!" }
=> #<Proc:0x007ff4598705a0@(irb):7>
ex.call
Hello, world!
=> nil
 
# Example 3:
# Function that returns lambda function object with parameters
def multiple_of?(n)
lambda{|x| x % n == 0}
end
=> nil
multiple_four = multiple_of?(4)
=> #<Proc:0x007ff458b45f88@(irb):12 (lambda)>
multiple_four.call(16)
=> true
multiple_four[15]
=> false
</syntaxhighlight>
 
===Rust===
In [[Rust (programming language)|Rust]], anonymous functions are called closures.<ref>{{Cite web|url=https://doc.rust-lang.org/stable/rust-by-example/fn/closures.html|title=Closures - Rust By Example|website=doc.rust-lang.org}}</ref> They are defined using the following syntax:
 
<syntaxhighlight lang="rust">
|<parameter-name>: <type>| -> <return-type> { <body> };
</syntaxhighlight>
 
For example:
<syntaxhighlight lang="rust">
let f = |x: i32| -> i32 { x * 2 };
</syntaxhighlight>
 
With type inference, however, the compiler is able to infer the type of each parameter and the return type, so the above form can be written as:
<syntaxhighlight lang="rust">
let f = |x| { x * 2 };
</syntaxhighlight>
 
With closures with a single expression (i.e. a body with one line) and implicit return type, the curly braces may be omitted:
<syntaxhighlight lang="rust">
let f = |x| x * 2;
</syntaxhighlight>
 
Closures with no input parameter are written like so:
<syntaxhighlight lang="rust">
let f = || println!("Hello, world!");
</syntaxhighlight>
 
Closures may be passed as input parameters of functions that expect a function pointer:
<syntaxhighlight lang="rust">
// A function which takes a function pointer as an argument and calls it with
// the value `5`.
fn apply(f: fn(i32) -> i32) -> i32 {
// No semicolon, to indicate an implicit return
f(5)
}
 
fn main() {
// Defining the closure
let f = |x| x * 2;
 
println!("{}", apply(f)); // 10
println!("{}", f(5)); // 10
}
</syntaxhighlight>
 
However, one may need complex rules to describe how values in the body of the closure are captured. They are implemented using the <code>Fn</code>, <code>FnMut</code>, and <code>FnOnce</code> traits:<ref name="auto">{{Cite web|url=https://doc.rust-lang.org/stable/rust-by-example/fn/closures/input_parameters.html|title=As input parameters - Rust By Example|website=doc.rust-lang.org}}</ref>
 
* <code>Fn</code>: the closure captures by reference (<code>&T</code>). They are used for functions that can still be called if they only have reference access (with <code>&</code>) to their environment.
* <code>FnMut</code>: the closure captures by mutable reference (<code>&mut T</code>). They are used for functions that can be called if they have mutable reference access (with <code>&mut</code>) to their environment.
* <code>FnOnce</code>: the closure captures by value (<code>T</code>). They are used for functions that are only called once.
 
With these traits, the compiler will capture variables in the least restrictive manner possible.<ref name="auto"/> They help govern how values are moved around between scopes, which is largely important since Rust follows a lifetime construct to ensure values are "borrowed" and moved in a predictable and explicit manner.<ref>{{Cite web |title=Lifetimes - Rust By Example |url=https://doc.rust-lang.org/stable/rust-by-example/scope/lifetime.html |website=doc.rust-lang.org}}</ref>
 
The following demonstrates how one may pass a closure as an input parameter using the <code>Fn</code> trait:
 
<syntaxhighlight lang="rust">
// A function that takes a value of type F (which is defined as
// a generic type that implements the `Fn` trait, e.g. a closure)
// and calls it with the value `5`.
fn apply_by_ref<F>(f: F) -> i32
where F: Fn(i32) -> i32
{
f(5)
}
 
fn main() {
let f = |x| {
println!("I got the value: {}", x);
x * 2
};
// Applies the function before printing its return value
println!("5 * 2 = {}", apply_by_ref(f));
}
 
// ~~ Program output ~~
// I got the value: 5
// 5 * 2 = 10
</syntaxhighlight>
 
The previous function definition can also be shortened for convenience as follows:
<syntaxhighlight lang="rust">
fn apply_by_ref(f: impl Fn(i32) -> i32) -> i32 {
f(5)
}
</syntaxhighlight>
 
===Scala===
In [[Scala (programming language)|Scala]], anonymous functions use the following syntax:<ref>{{cite web |title=Anonymous Function Syntax - Scala Documentation |url=http://www.scala-lang.org/node/133 |url-status=dead |archive-url=https://web.archive.org/web/20130723023605/http://www.scala-lang.org/node/133 |archive-date=2013-07-23 |access-date=2010-12-31 |language=en-US}}</ref>
<syntaxhighlight lang="scala">
(x: Int, y: Int) => x + y
</syntaxhighlight>
 
In certain contexts, like when an anonymous function is a parameter being passed 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.
<syntaxhighlight lang="scala">
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.
// Thus, it needs no 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.
</syntaxhighlight>
 
===Smalltalk===
In [[Smalltalk]] anonymous functions are called [[Smalltalk#Code blocks|blocks]] and they are invoked (called) by sending them a "value" message. If several arguments are to be passed, a "value:...value:" message with a corresponding number of value arguments must be used.
 
For example, in [[GNU Smalltalk]],
<syntaxhighlight lang="smalltalk">
st> f:=[:x|x*x]. f value: 8 .
64
st> [:x :y|x+y] value: 5 value: 6 .
11
</syntaxhighlight>
Smalltalk blocks are technically closures, allowing them to outlive their defining scope and still refer to the variables declared therein.
<syntaxhighlight lang="smalltalk">
st> f := [:a|[:n|a+n]] value: 100 .
a BlockClosure
"returns the inner block, which adds 100 (captured in "a" variable) to its argument."
st> f value: 1 .
101
st> f value: 2 .
102
</syntaxhighlight>
 
===Swift===
In [[Swift (programming language)|Swift]], anonymous functions are called closures.<ref name=":9">{{Cite web|url=https://docs.swift.org/swift-book/LanguageGuide/Closures.html|title=Closures — The Swift Programming Language (Swift 5.5)|website=docs.swift.org}}</ref> The syntax has following form:
<syntaxhighlight lang="objc">
{ (parameters) -> returnType in
statement
}
</syntaxhighlight>
For example:
<syntaxhighlight lang="objc">
{ (s1: String, s2: String) -> Bool in
return s1 > s2
}
</syntaxhighlight>
 
For sake of brevity and expressiveness, the parameter types and return type can be omitted if these can be inferred:
<syntaxhighlight lang="objc">
{ s1, s2 in return s1 > s2 }
</syntaxhighlight>
Similarly, Swift also supports implicit return statements for one-statement closures:
<syntaxhighlight lang="objc">
{ s1, s2 in s1 > s2 }
</syntaxhighlight>
Finally, the parameter names can be omitted as well; when omitted, the parameters are referenced using shorthand argument names, consisting of the $ symbol followed by their position (e.g. $0, $1, $2, etc.):
<syntaxhighlight lang="objc">
{ $0 > $1 }
</syntaxhighlight>
 
===Tcl===
In [[Tcl]], applying the anonymous squaring function to 2 looks as follows:<ref>[http://www.tcl.tk/man/tcl8.5/TclCmd/apply.htm ''apply manual page''], retrieved 2012-09-06.</ref>
<syntaxhighlight lang="tcl">
apply {x {expr {$x*$x}}} 2
# returns 4
</syntaxhighlight>
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
<syntaxhighlight lang="tcl">
{*}$f $x
</syntaxhighlight>
where <code>{*}</code> is the expansion prefix (new in Tcl 8.5). The command prefix in the above example is
apply <code>{x {expr {$x*$x}}}
</code> Command names can be bound to command prefixes by means of the <code>interp alias</code> command. Command prefixes support [[currying]]. Command prefixes are very common in Tcl [[Application programming interface|API]]s.
 
The other candidate for "function" in Tcl is usually called a ''lambda'', and appears as the <code>{x {expr {$x*$x}}}</code> 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 <code>apply</code> command. Lambdas do not support currying, unless paired with an <code>apply</code> to form a command prefix. Lambdas are rare in Tcl APIs.
 
===Vala===
In [[Vala (programming language)|Vala]], anonymous functions are supported as lambda expressions.<ref>[https://wiki.gnome.org/Projects/Vala/Manual/Methods#Lambdas ''Vala Reference Manual''], retrieved 2021-06-09.</ref>
<syntaxhighlight lang="vala">
delegate int IntOp (int x, int y);
 
void main () {
IntOp foo = (x, y) => x * y;
stdout.printf("%d\n", foo(10,5));
}
</syntaxhighlight>
 
===Visual Basic .NET===
[[Visual Basic .NET]] 2008 introduced anonymous functions through the lambda form. Combined with implicit typing, VB provides an economical syntax for anonymous functions. As with Python, in VB.NET, anonymous functions must be defined on one line; they cannot be compound statements. Further, an anonymous function in VB.NET must truly be a VB.NET <code>Function</code> - it must return a value.
<syntaxhighlight lang="vbnet">
Dim foo = Function(x) x * x
Console.WriteLine(foo(10))
</syntaxhighlight>
Visual Basic.NET 2010 added support for multiline lambda expressions and anonymous functions without a return value. For example, a function for use in a Thread.
<syntaxhighlight lang="vbnet">
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()
</syntaxhighlight>
 
==See also==