Names
The names "lambda abstraction", "lambda function", and "lambda expression" refer to the notation of function abstraction in lambda calculus, where the usual function would be written ( is an expression that uses ). Compare to the Python syntax ofUses
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. The 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 ax
, and returns the length of its argument, which is then used by the sort()
method as the criteria for sorting.
Basic syntax of a lambda function in Python is
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 containingCurrying
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 performsd
.
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 exampleFilter
The filter function returns all elements from a list that evaluate True when passed to a certain function.Fold
A fold function runs over all elements in a structure (for lists usually left-to-right, a "left fold", calledreduce
in Python), accumulating a value as it goes. This can be used to combine all elements of a structure into one value, for example:
List of languages
The following is a list ofExamples
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.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
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.
Clang (C, C++, Objective-C, Objective-C++)
return_type (^)(parameters)
.
Using the aforementioned ''blocks'' extension and -fblocks
and linked with -lBlocksRuntime
C++ (since C++11)
and ">/code>and
/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:
[] // 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
The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
// 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.
Variables captured by value are constant by default. Adding mutable
after the parameter list makes them non-constant.
C++14
C++14 is a version of the ISO/IEC 14882 standard for the C++ programming language. It is intended to be a small extension over C++11, featuring mainly bug fixes and small improvements, and was replaced by C++17. Its approval was announced on Augus ...
and newer versions support init-capture, for example:
std::unique_ptr ptr = std::make_unique(42);
tr // copy assignment is deleted for a unique pointer
tr = std::move(ptr) // ok
auto counter = = 0) mutable ; // mutable is required to modify 'i'
counter(); // 0
counter(); // 1
counter(); // 2
The following two examples demonstrate use of a lambda expression:
std::vector some_list;
int total = 0;
std::for_each(begin(some_list), end(some_list),
totalint x) );
// Note that std::accumulate would be a way better alternative here...
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 some_list;
int total = 0;
int value = 5;
std::for_each(begin(some_list), end(some_list),
total, value, thisint x) );
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. However in C++17, the current object can be captured by value (denoted by *this
), or can be captured by reference (denoted by this
). 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
In computing, inline expansion, or inlining, is a manual or compiler optimization that replaces a function call site with the body of the called function. Inline expansion is similar to macro expansion, but occurs during compilation, without cha ...
, 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
Undefined may refer to:
Mathematics
* Undefined (mathematics), with several related meanings
** Indeterminate form, in calculus
Computing
* Undefined behavior, computer code whose behavior is not specified under certain conditions
* 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 = int x) ;
auto my_onheap_lambda_func = new auto( int x) );
Here is an example of storing anonymous functions in variables, vectors, and arrays; and passing them as named parameters:
#include
#include
#include
double eval(std::function f, double x = 2.0)
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 = [](int x) ;
void (* func_ptr)(int) = a_lambda_func;
func_ptr(4); //calls the lambda.
Starting from C++23 C23 or C-23 may refer to:
Vehicles
;Aircraft
* Beechcraft C23 Musketeer, an American civil utility aircraft
* Caspar C 23, a German sport aircraft
* Caudron C.23, a French bomber biplane
* Lockheed C-23 Altair, an American military transport
...
, a lambda expression can be recursive through explicit this
as first parameter:
auto fibonacci = [](this auto self, int n) ;
fibonacci(7); // 13
The Boost (C++ libraries), Boost library provides its own syntax for lambda functions as well, using the following syntax:
for_each(a.begin(), 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
The .NET Framework (pronounced as "''dot net"'') is a proprietary software framework developed by Microsoft that runs primarily on Microsoft Windows. It was the predominant implementation of the Common Language Infrastructure (CLI) until bein ...
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''
''// ''
Func foo = x => x * x;
Console.WriteLine(foo(7));
While the function is anonymous, it cannot be assigned to an implicitly typed variable, because the lambda syntax may be used 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 = (int x) => x * x;
However, a lambda expression can take part in type inference
Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistic ...
and can be used as a method argument, e.g. to use anonymous functions with the Map capability available with System.Collections.Generic.List
(in the ConvertAll()
method):
// Initialize the list:
var values = new List() ;
// Map the anonymous function over all elements in the list, return the new list
var foo = values.ConvertAll(d => d * d) ;
// the result of the foo variable is of type System.Collections.Generic.List
Prior versions of C# had more limited support for anonymous functions. C# v1.0, introduced in February 2002 with the .NET Framework v1.0, provided partial anonymous function support through the use of delegates. 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. 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 Reflection or reflexion may refer to:
Science and technology
* Reflection (physics), a common wave phenomenon
** Specular reflection, reflection from a smooth surface
*** Mirror image, a reflection in a mirror or in water
** Signal reflection, in ...
.
In the case of the C# 3.0 version, the same mechanism applies.
ColdFusion Markup Language (CFML)
Using the keyword:
fn = function();
Or using an arrow function:
fn = () => ;
fn = () => singleExpression // singleExpression is implicitly returned. There is no need for the braces or the return keyword
fn = singleParam =>
fn = (x, y) =>
CFML supports any statements within the function's definition, not simply expressions.
CFML supports recursive anonymous functions:
factorial = function(n);
CFML anonymous functions implement closure.
D
D uses inline delegates to implement anonymous functions. The full syntax for an inline delegate is
return_type delegate(arguments)
If unambiguous, the return type and the keyword ''delegate'' can be omitted.
(x)
delegate (x) // if more verbosity is needed
(int x) // if parameter type cannot be inferred
delegate (int x) // ditto
delegate double(int x) // if return type must be forced manually
Since version 2.0, D allocates closures on the heap unless the compiler can prove it is unnecessary; the scope
keyword can be used for forcing stack allocation.
Since version 2.058, it is possible to use shorthand notation:
x => x*x;
(int x) => x*x;
(x,y) => x*y;
(int x, int y) => x*y;
An anonymous function can be assigned to a variable and used like this:
auto sqr = (double x);
double y = sqr(4);
Dart
Dart
Dart or DART may refer to:
* Dart, the equipment in the game of darts
Arts, entertainment and media
* Dart (comics), an Image Comics superhero
* Dart, a character from ''G.I. Joe''
* Dart, a ''Thomas & Friends'' railway engine character
* Dar ...
supports anonymous functions.
var sqr = (x) => x * x;
print(sqr(5));
or
print(((x) => x * x)(5));
Delphi
Delphi introduced anonymous functions in version 2009.
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.
PascalABC.NET
PascalABC.NET
PascalABC.NET is a Pascal (programming language), Pascal programming language that implements classic Pascal, most Delphi language features, as well as a number of their own extensions. It is implemented on the .NET Framework platform and conta ...
supports anonymous functions using lambda syntax
begin
var n := 10000000;
var pp := Range(1,n)
.Select(x->Rec(Random(),Random()))
.Where(p->sqr(p.Item1)+sqr(p.Item2)<1)
.Count/n*4;
Print(pp);
end.
Elixir
Elixir
ELIXIR (the European life-sciences Infrastructure for biological Information) is an initiative that will allow life science laboratories across Europe to share and store their research data as part of an organised network. Its goal is to bring t ...
uses the closure fn
for anonymous functions.
sum = fn(a, b) -> a + b end
sum.(4, 3)
#=> 7
square = fn(x) -> x * x end
Enum.map , 2, 3, 4
The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline (t ...
square
#=> , 4, 9, 16
The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline (t ...
Erlang
Erlang uses a syntax for anonymous functions similar to that of named functions.
% Anonymous function bound to the Square variable
Square = fun(X) -> X * X end.
% Named function with the same functionality
square(X) -> X * X.
Go
Go supports anonymous functions.
foo := func(x int) int
fmt.Println(foo(10))
Haskell
Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
uses a concise syntax for anonymous functions (lambda expressions). The backslash is supposed to resemble λ.
\x -> x * x
Lambda expressions are fully integrated with the type inference engine, and support all the syntax and features of "ordinary" functions (except for the use of multiple definitions for pattern-matching, since the argument list is only specified once).
map (\x -> x * x) ..5-- returns , 4, 9, 16, 25
The following are all equivalent:
f x y = x + y
f x = \y -> x + y
f = \x y -> x + y
Haxe
In Haxe
Haxe is an open source high-level cross-platform programming language and compiler that can produce applications and source code, for many different computing platforms from one code-base. It is free and open-source software, released under the ...
, anonymous functions are called lambda, and use the syntax function(argument-list) expression;
.
var f = function(x) return x*x;
f(8); // 64
(function(x,y) return x+y)(5,6); // 11
Java
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
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("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) ->
// 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) ->
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),''The Java Tutorials: Lambda Expressions''
docs.oracle.com 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 (the ::
operator) 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(int, int)
, so the compiler looks for a method int sum(int, int)
in the class java.lang.Integer
.
Differences to Anonymous Classes
of lambda-compatible interfaces are similar, but not exactly equivalent, to lambda expressions.
To illustrate, in the following example, and are both instances of that add their two parameters:
IntegerMath anonymousClass = new IntegerMath() ;
IntegerMath lambdaExpression = (a, b) -> a + b;
The main difference here is that the lambda expression does not necessarily need to allocate a new instance for the , and can return the same instance every time this code is run.
Additionally, in the OpenJDK
OpenJDK (Open Java Development Kit) is a free and open-source implementation of the Java Platform, Standard Edition (Java SE). It is the result of an effort Sun Microsystems began in 2006. The implementation is licensed under the GPL-2.0-only w ...
implementation at least, lambdas are compiled to instructions, with the lambda body inserted as a static method into the surrounding class, 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
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
/ECMAScript
ECMAScript (; ES) is a JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262
ECMAScript is commonly used for client-side scripting o ...
supports anonymous functions.
alert((function(x))(10));
ES6
ECMAScript (; ES) is a JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262
ECMAScript is commonly used for client-side scripting o ...
supports "arrow function" syntax, where a => symbol separates the anonymous function's parameter list from the body:
alert((x => x * x)(10));
This construct is often used in Bookmarklet
A bookmarklet is a bookmark stored in a web browser that contains JavaScript commands that add new features to the browser. They are stored as the URL of a bookmark in a web browser or as a hyperlink on a web page. Bookmarklets are usually smal ...
s. For example, to change the title of the current document (visible in its window's title bar
A title is one or more words used before or after a person's name, in certain contexts. It may signify either generation, an official position, or a professional or academic qualification. In some languages, titles may be inserted between the f ...
) to its URL, the following bookmarklet may seem to work.
javascript:document.title=location.href;
However, as the assignment statement returns a value (the URL itself), many browsers actually create a new page to display this value.
Instead, an anonymous function, that does not return a value, can be used:
javascript:(function())();
The function statement in the first (outer) pair of parentheses declares an anonymous function, which is then executed when used with the last pair of parentheses. This is almost equivalent to the following, which populates the environment with f
unlike an anonymous function.
javascript:var f = function(); f();
Use void() to avoid new pages for arbitrary anonymous functions:
javascript:void(function()());
or just:
javascript:void(document.title=location.href);
JavaScript has syntactic subtleties for the semantics of defining, invoking and evaluating anonymous functions. These subliminal nuances are a direct consequence of the evaluation of parenthetical expressions. The following constructs which are called immediately-invoked function expression
An immediately invoked function expression (or IIFE, pronounced "iffy", IPA /ˈɪf.i/) is a programming language idiom which produces a lexical scope using function scoping. It was popular in JavaScript as a method to support modular programming b ...
illustrate this:
(function()()) and
(function())()
Representing "function()
" by f
, the form of the constructs are
a parenthetical within a parenthetical (f())
and a parenthetical applied to a parenthetical (f)()
.
Note the general syntactic ambiguity of a parenthetical expression, parenthesized arguments to a function and the parentheses around the formal parameters in a function definition. In particular, JavaScript defines a ,
(comma) operator in the context of a 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 f
is not identified in the constructs above, they become (())
and ()()
. The first provides no syntactic hint of any resident function but the second MUST evaluate the first parenthetical as a function to be legal JavaScript. (Aside: for instance, the ()
's could be ([],,42,"abc",function()) as long as the expression evaluates to a function.)
Also, a function is an Object instance (likewise objects are Function instances) and the object literal notation brackets,
for braced code, are used when defining a function this way (as opposed to using new Function(...)
). In a very broad non-rigorous sense (especially since global bindings are compromised), an arbitrary sequence of braced JavaScript statements,
, can be considered to be a fixed point of
(function()() )
More correctly but with caveats,
( function()() ) ~=
A_Fixed_Point_of(
function()()
)
Note the implications of the anonymous function in the JavaScript fragments that follow:
* function()()
without surrounding ()
's is generally not legal
* (f=function())
does not "forget" f
globally unlike (function f())
:::Performance metrics
Metric or metrical may refer to:
* Metric system, an internationally adopted decimal system of measurement
* An adjective indicating relation to measurement in general, or a noun describing a specific type of measurement
Mathematics
In mathema ...
to analyze the space
Space is the boundless three-dimensional extent in which objects and events have relative position and direction. In classical physics, physical space is often conceived in three linear dimensions, although modern physicists usually cons ...
and time
Time is the continued sequence of existence and events that occurs in an apparently irreversible succession from the past, through the present, into the future. It is a component quantity of various measurements used to sequence events, ...
complexities of function calls, call stack, etc. in a JavaScript interpreter engine
An engine or motor is a machine designed to convert one or more forms of energy into mechanical energy.
Available energy sources include potential energy (e.g. energy of the Earth's gravitational field as exploited in hydroelectric power ...
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
In computer science, a tail call is a subroutine call performed as the final action of a procedure. If the target of a tail is the same subroutine, the subroutine is said to be tail recursive, which is a special case of direct recursion (computer s ...
.
Julia
In Julia
Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio and Julius. (For further details on etymology, see the Wiktionary entry "Julius".) The given name ''Julia'' had been in use throughout Late Antiquity (e.g ...
anonymous functions are defined using the syntax (arguments)->(expression)
,
julia> f = x -> x*x; f(8)
64
julia> ((x,y)->x+y)(5,6)
11
Kotlin
Kotlin supports anonymous functions with the syntax
,
val sum =
sum(5,6) // returns 11
val even =
even(4) // returns true
Lisp
Lisp and Scheme A scheme is a systematic plan for the implementation of a certain idea.
Scheme or schemer may refer to:
Arts and entertainment
* ''The Scheme'' (TV series), a BBC Scotland documentary series
* The Scheme (band), an English pop band
* ''The Schem ...
support anonymous functions using the "lambda" construct, which is a reference to lambda calculus. Clojure
Clojure (, like ''closure'') is a dynamic and functional dialect of the Lisp programming language on the Java platform. Like other Lisp dialects, Clojure treats code as data and has a Lisp macro system. The current development process is comm ...
supports anonymous functions with the "fn" special form and #() reader syntax.
(lambda (arg) (* arg arg))
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".
(function (lambda (arg) (do-something arg)))
"function" can be abbreviated as #'. Also, macro ''lambda'' exists, which expands into a function form:
; using sharp quote
#'(lambda (arg) (do-something arg))
; using the lambda macro:
(lambda (arg) (do-something arg))
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.
(mapcar #'(lambda (x) (* x x))
'(1 2 3 4))
; -> (1 4 9 16)
The ''lambda form'' in Common Lisp allows a ''lambda expression'' to be written in a function call:
((lambda (x y)
(+ (sqrt x) (sqrt y)))
10.0
12.0)
Anonymous functions in Common Lisp can also later be given global names:
(setf (symbol-function 'sqr)
(lambda (x) (* x x)))
; which allows us to call it using the name SQR:
(sqr 10.0)
Scheme
Scheme's ''named functions'' is simply syntactic sugar
In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an ...
for anonymous functions bound to names:
(define (somename arg)
(do-something arg))
expands (and is equivalent) to
(define somename
(lambda (arg)
(do-something arg)))
Clojure
Clojure
Clojure (, like ''closure'') is a dynamic and functional dialect of the Lisp programming language on the Java platform. Like other Lisp dialects, Clojure treats code as data and has a Lisp macro system. The current development process is comm ...
supports anonymous functions through the "fn" special form:
(fn (+ x 3))
There is also a reader syntax to define a lambda:
#(+ % %2%3) ; Defines an anonymous function that takes three arguments and sums them.
Like Scheme, Clojure's "named functions" are simply syntactic sugar for lambdas bound to names:
(defn func rg(+ 3 arg))
expands to:
(def func (fn rg(+ 3 arg)))
Lua
In Lua
Lua or LUA may refer to:
Science and technology
* Lua (programming language)
* Latvia University of Agriculture
* Last universal ancestor, in evolution
Ethnicity and language
* Lua people, of Laos
* Lawa people, of Thailand sometimes referred t ...
(much as in Scheme) all functions are anonymous. A ''named function'' in Lua is simply a variable holding a reference to a function object.
Thus, in Lua
function foo(x) return 2*x end
is just syntactical sugar for
foo = function(x) return 2*x end
An example of using anonymous functions for reverse-order sorting:
table.sort(network, function(a,b)
return a.name > b.name
end)
Wolfram Language, Mathematica
The Wolfram Language
The Wolfram Language ( ) is a general multi-paradigm programming language developed by Wolfram Research. It emphasizes symbolic computation, functional programming, and rule-based programming and can employ arbitrary structures and data. It ...
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+1 x \unction
Anointing is the ritual act of pouring aromatic oil over a person's head or entire body.
By extension, the term is also applied to related acts of sprinkling, dousing, or smearing a person or object with any perfumed oil, milk, butter, or ot ...
x+1
So, for instance:
f:= #1^2&;f 64
#1+#2& ,6 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 1, 1, #1 * #0[#1-1">1 1, 1, #1 * #0[#1-1&
For example, 6 factorial would be:
If 1, 1, #1 * #0[#1-1">1 1, 1, #1 * #0[#1-1&[6]
720
MATLAB, Octave
Anonymous functions in MATLAB or GNU Octave, Octave are defined using the syntax @(argument-list)expression
. Any variables that are not found in the argument list are inherited from the enclosing scope and are captured by value.
>> f = @(x)x*x; f(8)
ans = 64
>> (@(x,y)x+y)(5,6) % Only works in Octave
ans = 11
Maxima
In Maxima anonymous functions are defined using the syntax lambda(argument-list,expression)
,
f: lambda( x*x); f(8);
64
lambda( ,yx+y)(5,6);
11
ML
The various dialects of ML support anonymous functions.
Anonymous functions in OCaml are functions without a declared name. Here is an example of an anonymous function that multiplies its input by two:
fun x -> x*2
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.
F#
F# supports anonymous functions, as follows:
(fun x -> x * x) 20 // 400
Standard ML
Standard ML supports anonymous functions, as follows:
fn arg => arg * arg
Nim
Nim supports multi-line multi-expression anonymous functions.
var anon = proc (var1, var2: int): int = var1 + var2
assert anon(1, 2) 3
Multi-line example:
var anon = func (x: int): bool =
if x > 0:
result = true
else:
result = false
assert anon(9)
Anonymous functions may be passed as input parameters of other functions:
var cities = @ Frankfurt", "Tokyo", "New York"
cities.sort(
proc (x, y: string): int = cmp(x.len, y.len)
)
An anonymous function is basically a function without a name.
Perl
Perl 5
Perl 5
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
supports anonymous functions, as follows:
(sub )->(); # 1. fully anonymous, called as created
my $squarer = sub ; # 2. assigned to a variable
sub curry
# example of currying in Perl programming
sub sum # returns the sum of its arguments
my $curried = curry \&sum, 5, 7, 9;
print $curried->(1,2,3), "\n"; # prints 27 ( = 5 + 7 + 9 + 1 + 2 + 3 )
Other constructs take ''bare blocks'' as arguments, which serve a function similar to lambda functions of 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
PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group. ...
had no anonymous function support.
PHP 4.0.1 to 5.3
PHP 4.0.1 introduced the create_function
which was the initial anonymous function support. This function call makes a new randomly named function and returns its name (as a string)
$foo = create_function('$x', 'return $x*$x;');
$bar = create_function("\$x", "return \$x*\$x;");
echo $foo(10);
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 (despite possibly not existing) instead of leaving "$x
" 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 create_function
makes a new function, which exists for the rest of the program, and cannot be ''garbage collected
Garbage, trash, rubbish, or refuse is waste material that is discarded by humans, usually due to a perceived lack of utility. The term generally does not encompass bodily waste products, purely liquid or gaseous wastes, or toxic waste
T ...
'', 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 Closure
and magic method __invoke()
that makes a class instance invocable.
$x = 3;
$func = function($z) ;
echo $func($x); // prints 6
In this example, $func
is an instance of Closure
and echo $func($x)
is equivalent to echo $func->__invoke($x)
.
PHP 5.3 mimics anonymous functions but it does not support true anonymous functions because PHP functions are still not first-class objects.
PHP 5.3 does support closures but the variables must be explicitly indicated as such:
$x = 3;
$func = function() use(&$x) ;
$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.
PHP 7.4
Arrow functions were introduced in PHP 7.4
$x = 3;
$func = fn($z) => $z * 2;
echo $func($x); // prints 6
Prolog's dialects
Logtalk
Logtalk
Logtalk is an object-oriented logic programming language that extends and leverages the Prolog language with a feature set suitable for programming in the large.Paulo Moura (2003). Logtalk: Design of an Object-Oriented Logic Programming Language. ...
uses the following syntax for anonymous predicates (lambda expressions):
/ ambdaParameter1, LambdaParameter2, ...>Goal
A simple example with no free variables and using a list mapping predicate is:
, ?- meta::map( ,Y>(Y is 2*X), ,2,3
The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline ...
Ys).
Ys = ,4,6yes
Currying is also supported. The above example can be written as:
, ?- meta::map( >( >(Y is 2*X)), ,2,3
The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline ...
Ys).
Ys = ,4,6yes
Visual Prolog
Anonymous functions (in general anonymous ''predicates'') were introduced in Visual Prolog
Visual Prolog, previously known as PDC Prolog and Turbo Prolog, is a strongly typed object-oriented extension of Prolog. As Turbo Prolog, it was marketed by Borland but it is now developed and marketed by the Danish firm PDC that originally crea ...
in version 7.2. Anonymous predicates can capture values from the context. If created in an object member, it can also access the object state (by capturing This
).
mkAdder
returns an anonymous function, which has captured the argument X
in the closure. The returned function is a function that adds X
to its argument:
clauses
mkAdder(X) = .
Python
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
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
>>> foo(10)
100
In general, Python convention encourages the use of named functions defined in the same scope as one might typically use an anonymous functions in other languages. This is acceptable as locally defined functions implement the full power of closures and are almost as efficient as the use of a lambda in Python. In this example, the built-in power function can be said to have been curried:
>>> def make_pow(n):
... def fixed_exponent_pow(x):
... return pow(x, n)
... return fixed_exponent_pow
...
>>> sqr = make_pow(2)
>>> sqr(10)
100
>>> cub = make_pow(3)
>>> cub(10)
1000
R
In R the anonymous functions are defined using the syntax function(argument-list)expression
.
> f <- function(x)x*x; f(8)
64
> (function(x,y)x+y)(5,6)
11
Raku
In Raku, all blocks (even those associated with if, while, etc.) 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 $squarer1 = -> $x ; # 2a. pointy block
my $squarer2 = ; # 2b. twigil
my $squarer3 = ; # 2c. Perl 5 style
# currying
#:
sub add ($m, $n)
my $seven = add(3, 4);
my $add_one = &add.assuming(m => 1);
my $eight = $add_one($seven);
# WhateverCode object
#:
my $w = * - 1; # 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(main):001:0> # Example 1:
irb(main):002:0* # Purely anonymous functions using blocks.
irb(main):003:0* ex = 6.2, 24.1, 48.3, 32.4, 8.5=> 6.2, 24.1, 48.3, 32.4, 8.5irb(main):004:0> ex.sort_by # Sort by fractional part, ignoring integer part.
=> 4.1, 16.2, 48.3, 32.4, 8.5irb(main):005:0> # Example 2:
irb(main):006:0* # First-class functions as an explicit object of Proc -
irb(main):007:0* ex = Proc.new
=> #
irb(main):008:0> ex.call
Hello, world!
=> nil
irb(main):009:0> # Example 3:
irb(main):010:0* # Function that returns lambda function object with parameters
irb(main):011:0* def multiple_of?(n)
irb(main):012:1> lambda
irb(main):013:1> end
=> nil
irb(main):014:0> multiple_four = multiple_of?(4)
=> #
irb(main):015:0> multiple_four.call(16)
=> true
irb(main):016:0> multiple_four 5=> false
Rust
In Rust
Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO( ...
, 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 (i.e. a body with one line), the curly braces may be omitted:
let f = , x, x * 2;
Closures with no input parameter are written like so:
let f = , , println!("Hello, world!");
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(f: fn(i32) -> i32) -> 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 (&T
). They are used for functions that can still be called if they only have reference access (with &
) to their environment.
* FnMut
: the closure captures by mutable reference (&mut T
). They are used for functions that can be called if they have mutable reference access (with &mut
) to their environment.
* FnOnce
: the closure captures by value (T
). They are used for functions that are only called once.
With these traits, the compiler will capture variables in the least restrictive manner possible. 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.
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 (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) -> i32
where F: Fn(i32) -> i32
fn main()
// ~~ Program output ~~
// I got the value: 5
// 5 * 2 = 10
Scala
In Scala, anonymous functions use the following syntax:
(x: Int, y: Int) => 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(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.
Smalltalk
In Smalltalk anonymous functions are called 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
GNU Smalltalk is an implementation of the Smalltalk programming language by the GNU Project.
The implementation, unlike other Smalltalk environments, uses text files for program input and interprets the contents as Smalltalk code. In this way, ...
,
st> f:= x*x f value: 8 .
64
st> x+yvalue: 5 value: 6 .
11
Smalltalk blocks are technically closures, allowing them to outlive their defining scope and still refer to the variables declared therein.
st> f := [: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
Swift
In Swift (programming language), 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 (e.g. $0, $1, $2, etc.):
Tcl
In Tcl
TCL or Tcl or TCLs may refer to:
Business
* TCL Technology, a Chinese consumer electronics and appliance company
**TCL Electronics, a subsidiary of TCL Technology
* Texas Collegiate League, a collegiate baseball league
* Trade Centre Limited ...
, 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''(''x'') would be
$f $x
where
is the expansion prefix (new in Tcl 8.5). 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 API
An application programming interface (API) is a way for two or more computer programs to communicate with each other. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how ...
s.
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.
Vala
In Vala
Vala or VALA may refer to:
Religion and mythology
* Vala (Vedic), a demon or a stone cavern in the Hindu scriptures
* Völva, also spelled Vala, a priestess in Norse mythology and Norse paganism
Fiction
* Vala (Middle-earth), an angelic being in ...
, anonymous functions are supported as lambda expressions.''Vala Reference Manual''
retrieved 2021-06-09.
delegate int IntOp (int x, int y);
void main ()
Visual Basic .NET
Visual Basic .NET
Visual Basic, originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language, implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Visua ...
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 Function
- it must return a value.
Dim foo = Function(x) x * x
Console.WriteLine(foo(10))
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(Sub ()
For n As Integer = 0 To 10 'Count to 10
Console.WriteLine(n) 'Print each number
Next
End Sub
)
t.Start()
See also
* First-class function
In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning them as the values from ...
References
External links
Anonymous Methods - When Should They Be Used?
(blog about anonymous function in Delphi)
Compiling Lambda Expressions: Scala vs. Java 8
php anonymous functions
php anonymous functions
Lambda functions in various programming languages
{{DEFAULTSORT:Anonymous Function
Data types
Functional programming
Lambda calculus
Subroutines
Articles with example code