Anonymous function
In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions, or used for constructing the result of a higher-order function that needs to return a function.
If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.
Anonymous functions originate in the work of Alonzo Church in his invention of the lambda calculus, in which all functions are anonymous, in 1936, before electronic computers. In several programming languages, anonymous functions are introduced using the keyword lambda, and anonymous functions are often referred to as lambdas or lambda abstractions. Anonymous functions have been a feature of programming languages since Lisp in 1958, and a growing number of modern programming languages support anonymous functions.
Uses
Anonymous functions can be used for containing functionality that need not be named and possibly for short-term use. Some notable examples include closures and currying.Use of anonymous functions is a matter of style. Using them is never the only way to solve a problem; each anonymous function could instead be defined as a named function and called by name. Some programmers use anonymous functions to encapsulate specific, non-reusable code without littering the code with a lot of little one-line normal functions.
In some programming languages, anonymous functions are commonly implemented for very specific purposes such as binding events to callbacks, or instantiating the function for particular values, which may be more efficient, more readable, and less error-prone than calling a more-generic named function.
The following examples are written in Python 3.
Sorting
When attempting to sort in a non-standard way, it may be easier to contain the sorting 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 function that determines how to compare whether two elements are equal or if one is greater or less than the other.
Consider this Python code sorting a list of strings by length of the string:
>>> a =
>>> a.sort
The anonymous function in this example is the lambda expression:
lambda x: len
Basic syntax of a lambda function in python is
lambda arg1, arg2, arg3,...:
The expression returned by the lambda function can be assigned to a variable and used in the code at multiple places.
add = lambda a: a + a
40
The anonymous function accepts one argument,
x
, and returns the length of its argument, which is then used by the sort
method as the criteria for sorting.Another example would be sorting items in a list by the name of their class :
>>> a =
>>> a.sort
Note that
11.2
has class name "float
", 10
has class name "int
", and 'number'
has class name "str
". The sorted order is "float
", "int
", then "str
".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:
return lambda x: x < threshold
This can be used as a sort of generator of comparison functions:
>>> func_a = comp
>>> func_b = comp
>>> print, func_a, func_a, func_a)
True True False False
>>> print, func_b, func_b, func_b)
True True True False
It would be 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 the process of changing a function so that rather than taking multiple inputs, it takes a single input and returns a function which accepts the second input, and so forth. In this example, a function that performs division by any integer is transformed into one that performs division by a set integer.>>> def divide:
... return x / y
>>> def divisor:
... return lambda x: divide
>>> half = divisor
>>> third = divisor
>>> print, third)
16.0 10.666666666666666
>>> print, third)
20.0 13.333333333333334
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.
The divisor function also forms a closure by binding the variable
d
.Higher-order functions
A higher-order function is a function that takes a function as an argument. This is commonly used to customize the behavior of a generically defined function, often a looping construct or recursion scheme. Anonymous functions are a convenient way to specify such function arguments. The following examples are in Python 3.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 =
The anonymous function accepts an argument and multiplies it by itself. The above form is discouraged by the creators of the language, who maintain that the form presented below has the same meaning and is more aligned with the philosophy of the language:
>>> a =
Filter
The filter function returns all elements from a list that evaluate True when passed to a certain function.>>> a =
The anonymous function checks if the argument passed to it is even. The same as with map form below is considered as more appropriate:
>>> a =
Fold
A fold function runs over all elements in a structure, accumulating a value as it goes. This can be used to combine all elements of a structure into one value, for example:>>> from functools import reduce
>>> a =
120
This performs
The anonymous function here is the multiplication of the two arguments.
The result of a fold need not be one value. Instead, 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 support unnamed anonymous functions fully, or partly as some variant, or not at all.This table shows some general trends. First, the languages that do not support anonymous functions are all statically typed languages. However, statically typed languages can support 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, as has C++. Second, the languages that treat functions as first-class functions generally have anonymous function support so that functions can be defined and passed around as easily as other data types.
Language | Support | Notes |
ActionScript | ||
Ada | Expression functions are a part of Ada2012 | |
ALGOL 68 | ||
APL | Dyalog, ngn and dzaima APL fully support both dfns and tacit functions. GNU APL has rather limited support for dfns. | |
Assembly languages | ||
Bash | A library has been made to support anonymous functions in Bash. | |
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 use. See below for more details. | |
C# | ||
C++ | As of the C++11 standard | |
CFML | As of Railo 4, ColdFusion 10 | |
Clojure | ||
COBOL | Micro Focus's non-standard Managed COBOL dialect supports lambdas, which are called anonymous delegates/methods. | |
Curl | ||
D | ||
Dart | ||
Delphi | ||
Dylan | ||
Eiffel | ||
Elm | ||
Elixir | ||
Erlang | ||
F# | ||
Factor | "Quotations" support this | |
Fortran | ||
Frink | ||
Go | ||
Gosu | ||
Groovy | ||
Haskell | ||
Haxe | ||
Java | Supported in Java 8. See the Java Limitations section below for details. | |
JavaScript | ||
Julia | ||
Kotlin | ||
Lisp | ||
Logtalk | ||
Lua | ||
MUMPS | ||
Mathematica | ||
Maple | ||
MATLAB | ||
Maxima | ||
Next Generation Shell | - | |
OCaml | ||
Octave | ||
Object Pascal | Delphi, a dialect of Object Pascal, supports anonymous functions natively since Delphi 2009. The Oxygene Object Pascal dialect also supports them. | |
Objective-C | 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. Formerly, only partial anonymous functions were supported, which worked much like C#'s implementation. | |
PL/I | ||
Python | Python supports anonymous functions through the lambda syntax, which supports only expressions, not statements. | |
R | ||
Racket | ||
Raku | ||
Rexx | ||
RPG | ||
Ruby | Ruby's anonymous functions, inherited from Smalltalk, are called blocks. | |
Rust | ||
Scala | ||
Scheme | ||
Smalltalk | Smalltalk's anonymous functions are called blocks. | |
Standard ML | ||
Swift | Swift's anonymous functions are called Closures. | |
TypeScript | ||
Tcl | ||
Vala | ||
Visual Basic.NET v9 | ||
Visual Prolog v 7.2 | ||
WLanguage v25 | PCSoft's W-Language used by its WinDev/WebDev/WinDev Mobile suite supports anonymous functions as-of release 25 | |
Wolfram Language |
Examples
Numerous languages support anonymous functions, or something similar.APL
Only some dialects support anonymous functions, either as dfns, in the tacit style or a combination of both.f← ⍝ As a dfn
f 1 2 3
1 4 9
g←⊢×⊢ ⍝ As a tacit 3-train
g 1 2 3
1 4 9
h←×⍨ ⍝ As a derived tacit function
h 1 2 3
1 4 9
C (non-standard extension)
The anonymous function is not supported by standard C programming language, but supported by some C dialects, such as GCC and Clang.GCC
supports anonymous functions, mixed by nested functions and statement expressions. It has the form:The following example works only with GCC. Because of how macros are expanded, the
l_body
cannot contain any commas outside of parentheses; GCC treats the comma as a delimiter between macro arguments.The argument
l_ret_type
can be removed if __typeof__
is available; in the example below using __typeof__
on array would return testtype *, which can be dereferenced for the actual value if needed.- include
- define lambda \
- define forEachInArray \
testtype;
void printout
int main
Clang (C, C++, Objective-C, Objective-C++)
supports anonymous functions, called blocks, which have the form:^return_type
The type of the blocks above is
return_type
.Using the aforementioned blocks extension and Grand Central Dispatch, the code could look simpler:
- include
- include
The code with blocks should be compiled with
-fblocks
and linked with -lBlocksRuntime
C++ (since C++11)
supports anonymous functions, called lambda expressions, which have the form:-> return_type
This is an example lambda expression:
-> int
C++11 also supports closures. Closures are defined between square brackets
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 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 is explicitly captured by value. Other variables will be captured by reference
//z is explicitly captured by reference. Other variables will be captured by value
Variables captured by value are constant by default. Adding
mutable
after the parameter list makes them non-constant.The following two examples demonstrate use of a lambda expression:
std::vector
int total = 0;
std::for_each, end,
;
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 total = 0;
int value = 5;
std::for_each, end,
;
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 need 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 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.
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
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 = ;
auto my_onheap_lambda_func = new auto;
Here is an example of storing anonymous functions in variables, vectors, and arrays; and passing them as named parameters:
- include
- include
- include
int main
A lambda expression 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 = ;
void = a_lambda_func;
func_ptr; //calls the lambda.
The Boost library provides its own syntax for lambda functions as well, using the following syntax:
for_each, a.end, std::cout << _1 << ' ');
C#
In 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. C# names them lambda expressions, following the original version of anonymous functions, the lambda calculus.// the first int is the x' type
// the second int is the return type
//
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. E.g., this does not work:
// will NOT compile!
var foo = => 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
:// Initialize the list:
var values = new List
// Map the anonymous function over all elements in the list, return the new list
var foo = values.ConvertAll ;
// the result of the foo variable is of type System.Collections.Generic.List
Prior versions of C# had more limited support for anonymous functions. C# v1.0, introduced in February 2002 with the.NET Framework v1.0, provided partial anonymous function support through the use of delegates. 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. C# v2.0, released in November 2005 with the.NET Framework v2.0, introduced the concept of anonymous methods as a way to write unnamed inline statement blocks that can be executed in a delegate invocation. C# 3.0 continues to support these constructs, but also supports the lambda expression construct.
This example will compile in C# 3.0, and exhibits the three forms:
public class TestDriver
In the case of the C# 2.0 version, the C# compiler takes the code block of the anonymous function and creates a static private function. Internally, the function gets a generated name, of course; this generated name is based on the name of the method in which the Delegate is declared. But the name is not exposed to application code except by using reflection.
In the case of the C# 3.0 version, the same mechanism applies.
ColdFusion Markup Language (CFML)
fn = function;
CFML supports any statements within the function's definition, not simply expressions.
CFML supports recursive anonymous functions:
factorial = function;
CFML anonymous functions implement closure.
D
D uses inline delegates to implement anonymous functions. The full syntax for an inline delegate isreturn_type delegate
If unambiguous, the return type and the keyword delegate can be omitted.
delegate // if more verbosity is needed
// if parameter type cannot be inferred
delegate // ditto
delegate double // 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 for forcing stack allocation.Since version 2.058, it is possible to use shorthand notation:
x => x*x;
=> x*x;
=> x*y;
=> x*y;
An anonymous function can be assigned to a variable and used like this:
auto sqr = ;
double y = sqr;
Dart
supports anonymous functions.var sqr = => x * x;
print;
or
print);
Delphi
introduced anonymous functions in version 2009.program demo;
type
TSimpleProcedure = reference to procedure;
TSimpleFunction = reference to function: Integer;
var
x1: TSimpleProcedure;
y1: TSimpleFunction;
begin
x1 := procedure
begin
Writeln;
end;
x1; //invoke anonymous method just defined
y1 := function: Integer
begin
Result := Length;
end;
Writeln;
end.
PascalABC.NET
supports anonymous functions using lambda syntaxbegin
var n := 10000000;
var pp := Range
.Select,Random))
.Where+sqr
.Count/n*4;
Print;
end.
Elixir
uses the closurefn
for anonymous functions.sum = fn -> a + b end
sum.
- => 7
Enum.map , square
- =>
Erlang
uses a syntax for anonymous functions similar to that of named functions.% Anonymous function bound to the Square variable
Square = fun -> X * X end.
% Named function with the same functionality
square -> X * X.
Go
supports anonymous functions.foo := func int
fmt.Println
Haskell
uses a concise syntax for anonymous functions.\x -> x * x
Lambda expressions are fully integrated with the type inference engine, and support all the syntax and features of "ordinary" functions.
map -- returns
The following are all equivalent:
f x y = x + y
f x = \y -> x + y
f = \x y -> x + y
Haxe
In Haxe, anonymous functions are called lambda, and use the syntaxfunction expression;
.var f = function return x*x;
f; // 64
; // 11
Java
supports anonymous functions, named Lambda Expressions, starting with JDK 8.A lambda expression consists of a comma separated list of the formal parameters enclosed in parentheses, an arrow token, 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.
// with no parameter
-> System.out.println
// with one parameter.
a -> a
// with one expression
-> a + b
// with explicit type information
-> "id: " + id + ", name:" + name
// with a code block
->
// with multiple statements in the lambda body. It needs a code block.
// This example also includes two nested lambda expressions.
->
Lambda expressions are converted to "functional interfaces", as in the following example:
public class Calculator
In this example, a functional interface called
IntegerMath
is declared. Lambda expressions that implement IntegerMath
are passed to the apply
method to be executed. Default methods like swap
define methods on functions.Java 8 introduced another mechanism named method reference to create a lambda on an existing method. A method reference doesn't indicate the number or types of arguments because those are extracted from the abstract method of the functional interface.
IntBinaryOperator sum = Integer::sum;
In the example above, the functional interface
IntBinaryOperator
declares an abstract method int applyAsInt
, so the compiler looks for a method int sum
in the class java.lang.Integer
.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
alert);
ES6 supports "arrow function" syntax, where a => symbol separates the anonymous function's parameter list from the body:
alert);
This construct is often used in Bookmarklets. For example, to change the title of the current document to its URL, the following bookmarklet may seem to work.
javascript:document.title=location.href;
However, as the assignment statement returns a value, 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:);
The function statement in the first 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; f;
Use void to avoid new pages for arbitrary anonymous functions:
javascript:void);
or just:
javascript:void;
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:
Representing "
function
" by f
, the form of the constructs are a parenthetical within a parenthetical
)
and a parenthetical applied to a parenthetical
.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
,
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 ! 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. 's could be ) as long as the expression evaluates to a function.)Also, a function is an Object instance and the object literal notation brackets,
for braced code, are used when defining a function this way. In a very broad non-rigorous sense, an arbitrary sequence of braced JavaScript statements,
, can be considered to be a fixed point of)
More correctly but with caveats,
) ~=
A_Fixed_Point_of
)
Note the implications of the anonymous function in the JavaScript fragments that follow:
-
function
without surrounding's is generally not legal
-
)
does not "forget"f
globally unlike)
Julia
->
,julia> f = x -> x*x; f
64
julia>
11
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.)
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".))
"function" can be abbreviated as #'. Also, macro lambda exists, which expands into a function form:
; using sharp quote
- ' )
)
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.
)
')
; ->
The lambda form in Common Lisp allows a lambda expression to be written in a function call:
))
10.0
12.0)
Anonymous functions in Common Lisp can also later be given global names:
))
; which allows us to call it using the name SQR:
Scheme
named functions is simply syntactic sugar for anonymous functions bound to names:)
expands to
))
Clojure
supports anonymous functions through the "fn" special form:There is also a reader syntax to define a lambda:
- ; 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:
expands to:
Lua
In Lua all functions are anonymous. A named function in Lua is simply a variable holding a reference to a function object.Thus, in Lua
function foo return 2*x end
is just syntactical sugar for
foo = function return 2*x end
An example of using anonymous functions for reverse-order sorting:
table.sort
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.#1
refers to the first argument and &
marks the end of the anonymous function.#1+1&
Function
x \ x+1
So, for instance:
f:= #1^2&;f
64
#1+#2&
11
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:
If
720
MATLAB, Octave
Anonymous functions in MATLAB or Octave are defined using the syntax@expression
. Any variables that are not found in the argument list are inherited from the enclosing scope.> f = @x*x; f
ans = 64
> % Only works in Octave
ans = 11
Maxima
In Maxima anonymous functions are defined using the syntaxlambda
,f: lambda; f;
64
lambda;
11
ML
The various dialects of ML support anonymous functions.[OCaml]
OCaml functions do not have to have names; they may be anonymous. For example, here is an anonymous function that increments its input: fun x -> x+1. Here, fun is a keyword indicating an anonymous function, x is the argument, and -> separates the argument from the body.We now have two ways we could write an increment function:
let inc x = x + 1
let inc = fun x -> x+1
They are syntactically different but semantically equivalent. That is, even though they involve different keywords and put some identifiers in different places, they mean the same thing.
Anonymous functions are also called lambda expressions, a term that comes out of the lambda calculus, which is a mathematical model of computation in the same sense that Turing machines are a model of computation. In the lambda calculus, fun x -> e would be written λx.e. The λ denotes an anonymous function.
Syntax.
fun x1... xn -> e
Static semantics.
If by assuming that x1:t1 and x2:t2 and... and xn:tn, we can conclude that e:u, then fun x1... xn -> e : t1 -> t2 ->... -> tn -> u.
Dynamic semantics.
An anonymous function is already a value. There is no computation to be performed.
fun arg -> arg * arg
Snippet from CS3110, Cornell, taught by Michael R. Clarkson, Robert L. Constable, Nate Foster, Michael D. George, Dan Grossman, Daniel P. Huttenlocher, Dexter Kozen, Greg Morrisett, Andrew C. Myers, Radu Rugina, and Ramin Zabih.
F#
supports anonymous functions, as follows:20 // 400
Standard ML
supports anonymous functions, as follows:
fn arg => arg * arg
Next Generation Shell
has several syntaxes for anonymous functions due to their prevalence in the language and different use cases.Syntaxes:
f = X*X; f # Result: 64
f = ; f # Result: 10
f = F x*y+2; f # Result: 14
f = "$ is all about $"
f # Result: "programming is all about semantics"
.map # Result:
data =
data.map # Result:
Perl
Perl 5
supports anonymous functions, as follows:->; # 1. fully anonymous, called as created
my $squarer = sub ; # 2. assigned to a variable
sub curry
- example of currying in Perl programming
my $curried = curry \&sum, 5, 7, 9;
print $curried->, "\n"; # prints 27
Other constructs take bare blocks as arguments, which serve a function similar to lambda functions of one 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; # braces unneeded for one expression
my @bad_example = map 1..10; # values not passed like normal Perl function
PHP
Before 4.0.1, PHP had no anonymous function support.PHP 4.0.1 to 5.3
PHP 4.0.1 introduced thecreate_function
which was the initial anonymous function support. This function call makes a new randomly named function and returns its name $foo = create_function;
$bar = create_function;
echo $foo;
The argument list and function body must be in single quotes, or the dollar signs must be escaped.
Otherwise, PHP assumes "
$x
" means the variable $x
and will substitute it into the string 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.
Each invocation of
create_function
makes a new function, which exists for the rest of the program, and cannot be 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 calledClosure
and magic method __invoke
that makes a class instance invocable.$x = 3;
$func = function ;
echo $func; // prints 6
In this example,
$func
is an instance of Closure
and echo $func
is equivalent to echo $func->__invoke
.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 ;
$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.Prolog's dialects
Logtalk
uses the following syntax for anonymous predicates :/>>Goal
A simple example with no free variables and using a list mapping predicate is:
Ys =
yes
Currying is also supported. The above example can be written as:
Ys =
yes
Visual Prolog
Anonymous functions were introduced in Visual Prolog in version 7.2. Anonymous predicates can capture values from the context. If created in an object member, it can also access the object state.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 =.
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
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:
... def fixed_exponent_pow:
... return pow
... return fixed_exponent_pow
...
>>> sqr = make_pow
100
>>> cub = make_pow
1000
R
In R the anonymous functions are defined using the syntaxfunctionexpression
.> f <- functionx*x; f
64
>
11
Raku
In Raku, all blocks are anonymous functions. A block that is not used as an rvalue is executed immediately.- fully anonymous, called as created
- :
- assigned to a variable
- :
my $squarer2 = ; # 2b. twigil
my $squarer3 = ; # 2c. Perl 5 style
- currying
- :
my $seven = add;
my $add_one = &add.assuming;
my $eight = $add_one;
- WhateverCode object
- :
my $b = ; # same functionality, but as Callable block
Ruby
Ruby supports anonymous functions by using a syntactical structure called block. There are two data types for blocks in Ruby.Proc
s behave similarly to closures, whereas lambda
s behave more analogous to an anonymous function. When passed to a method, a block is converted into a Proc in some circumstances.irb:001:0> # Example 1:
irb:002:0* # Purely anonymous functions using blocks.
irb:003:0* ex =
=>
irb:004:0> ex.sort_by # Sort by fractional part, ignoring integer part.
=>
irb:005:0> # Example 2:
irb:006:0* # First-class functions as an explicit object of Proc -
irb:007:0* ex = Proc.new
=> #
irb:008:0> ex.call
Hello, world!
=> nil
irb:009:0> # Example 3:
irb:010:0* # Function that returns lambda function object with parameters
irb:011:0* def is_multiple_of
irb:012:1> lambda
irb:013:1> end
=> nil
irb:014:0> multiple_four = is_multiple_of
=> #
irb:015:0> multiple_four.call
=> true
irb:016:0> multiple_four
=> false
Rust
In Rust, anonymous functions are called closures. They are defined using the following syntax:For example:
let f = |x: i32| -> i32 ;
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:
let f = |x| ;
With closures with a single expression, the curly braces may be omitted:
let f = |x| x * 2;
Closures with no input parameter are written like so:
let f = || println!;
Closures may be passed as input parameters of functions that expect a function pointer:
// A function which takes a function pointer as an argument and calls it with
// the value `5`.
fn apply -> i32
fn main
However, one may need complex rules to describe how values in the body of the closure are captured. They are implemented using the
Fn
, FnMut
, and FnOnce
traits:-
Fn
: the closure captures by reference. They are used for functions that can still be called if they only have reference access to their environment. -
FnMut
: the closure captures by mutable reference. They are used for functions that can be called if they have mutable reference access to their environment. -
FnOnce
: the closure captures by value. They are used for functions that are only called once.
The following demonstrates how one may pass a closure as an input parameter using the
Fn
trait:// A function that takes a value of type F
// and calls it with the value `5`.
fn apply_by_ref
where F: Fn -> i32
fn main
// ~~ Program output ~~
// I got the value: 5
// 5 * 2 = 10
Scala
In Scala, anonymous functions use the following syntax:=> x + y
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.
val list = List
list.reduceLeft
// 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.
Smalltalk
In Smalltalk anonymous functions are called blocks and they are invoked by sending them a "value" message. If arguments are to be passed, a "value:...value:" message with a corresponding number of value arguments must be used.value: 4
"returns 16"
Smalltalk blocks are technically closures, allowing them to outlive their defining scope and still refer to the variables declared therein.
] value: 10
"returns the inner block, which adds 10 to its argument."
Swift
In Swift, anonymous functions are called closures. The syntax has following form:For example:
For sake of brevity and expressiveness, the parameter types and return type can be omitted if these can be inferred:
Similarly, Swift also supports implicit return statements for one-statement closures:
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 :
Tcl
In Tcl, applying the anonymous squaring function to 2 looks as follows:apply 2
- returns 4
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 would be
$f $x
where
is the expansion prefix. The command prefix in the above example is apply
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
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 .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.NETFunction
- it must return a value. Dim foo = Function x * x
Console.WriteLine
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.
Dim t As New System.Threading.Thread
For n As Integer = 0 To 10 'Count to 10
Console.WriteLine 'Print each number
Next
End Sub
)
t.Start