Numerous languages support anonymous functions, or something similar.
Only some dialects support anonymous functions, either as dfns, in the tacit style or a combination of both.
The anonymous function is not supported by standard C programming language, but supported by some C dialects, such as GCC1 and Clang.
The GNU Compiler Collection (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.
Clang supports anonymous functions, called blocks,2 which have the form:
The type of the blocks above is return_type (^)(parameters).
Using the aforementioned blocks extension and Grand Central Dispatch (libdispatch), the code could look simpler:
The code with blocks should be compiled with -fblocks and linked with -lBlocksRuntime
C++11 supports anonymous functions (technically function objects), called lambda expressions,3 which have the form:
where "specs" is of the form "specifiers exception attr trailing-return-type in that order; each of these components is optional". If it is absent, the return type is deduced from return statements as if for a function with declared return type auto.
This is an example lambda expression:
C++11 also supports closures, here called captures. Captures are defined between square brackets [and ] in the declaration of lambda expression. The mechanism allows these variables to be captured by value or by reference. The following table demonstrates this:
Variables captured by value are constant by default. Adding mutable after the parameter list makes them non-constant.
C++14 and newer versions support init-capture, for example:
The following two examples demonstrate use of a lambda expression:
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.
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, 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,
Here is an example of storing anonymous functions in variables, vectors, and arrays; and passing them as named parameters:
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:
Since C++17, a lambda can be declared constexpr, and since C++20, consteval with the usual semantics. These specifiers go after the parameter list, like mutable. Starting from C++23, the lambda can also be static if it has no captures. The static and mutable specifiers are not allowed to be combined.
Also since C++23 a lambda expression can be recursive through explicit this as first parameter:
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 [[noreturn]] attribute impossible to use with lambdas.
The Boost library provides its own syntax for lambda functions as well, using the following syntax:4
Since C++14, the function parameters of a lambda can be declared with auto. 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:
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.5: 7–8 6: 26 C# names them lambda expressions, following the original version of anonymous functions, the lambda calculus.78: 7–8, 91 9: 91
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.10: 101–103 E.g., this does not work:
However, a lambda expression can take part in type inference and can be used as a method argument, e.g. to use anonymous functions with the Map capability available with System.Collections.Generic.List (in the ConvertAll() method):
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.11: 6 C# names them lambda expressions, following the original version of anonymous functions, the lambda calculus.12: 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.13: 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:
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.14: 103 In the case of the C# 3.0 version, the same mechanism applies.
Using the function keyword:
Or using an arrow function:
CFML supports any statements within the function's definition, not simply expressions.
CFML supports recursive anonymous functions:
CFML anonymous functions implement closure.
D uses inline delegates to implement anonymous functions. The full syntax for an inline delegate is
If unambiguous, the return type and the keyword delegate can be omitted.
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:
An anonymous function can be assigned to a variable and used like this:
Dart supports anonymous functions.15
or
Delphi introduced anonymous functions in version 2009.
PascalABC.NET supports anonymous functions using lambda syntax
Elixir uses the closure fn for anonymous functions.16
Erlang uses a syntax for anonymous functions similar to that of named functions.17
Go supports anonymous functions.18
Haskell uses a concise syntax for anonymous functions (lambda expressions). The backslash is supposed to resemble λ.
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).
The following are all equivalent:
In Haxe, anonymous functions are called lambda, and use the syntax function(argument-list) expression; .
Java supports anonymous functions, named Lambda Expressions, starting with JDK 8.19
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.20
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),21 as in the following example:
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 does not indicate the number or types of arguments because those are extracted from the abstract method of the functional interface.
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.
Anonymous classes of lambda-compatible interfaces are similar, but not exactly equivalent, to lambda expressions. To illustrate, in the following example, anonymousClass and lambdaExpression are both instances of IntegerMath that add their two parameters:
The main difference here is that the lambda expression does not necessarily need to allocate a new instance for the IntegerMath, and can return the same instance every time this code is run.22 Additionally, in the OpenJDK implementation at least, lambdas are compiled to invokedynamic instructions, with the lambda body inserted as a static method into the surrounding class,23 rather than generating a new class file entirely.
Java 8 lambdas have the following limitations:
JavaScript/ECMAScript supports anonymous functions.
ES6 supports "arrow function" syntax, where a => symbol separates the anonymous function's parameter list from the body:
This construct is often used in Bookmarklets. For example, to change the title of the current document (visible in its window's title bar) to its URL, the following bookmarklet may seem to work.
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:
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.
Use void() to avoid new pages for arbitrary anonymous functions:
or just:
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:
and
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, {stuff}, can be considered to be a fixed point of
More correctly but with caveats,
Note the implications of the anonymous function in the JavaScript fragments that follow:
In Julia anonymous functions are defined using the syntax (arguments)->(expression),
Kotlin supports anonymous functions with the syntax {arguments -> expression},
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:
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:
Anonymous functions in Common Lisp can also later be given global names:
Scheme's named functions is simply syntactic sugar for anonymous functions bound to names:
expands (and is equivalent) to
Clojure supports anonymous functions through the "fn" special form:
There is also a reader syntax to define a lambda:
Like Scheme, Clojure's "named functions" are simply syntactic sugar for lambdas bound to names:
expands to:
In Lua (much as in Scheme) all functions are anonymous. A named function in Lua is simply a variable holding a reference to a function object.24
Thus, in Lua
is just syntactical sugar for
An example of using anonymous functions for reverse-order sorting:
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.
So, for instance:
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:
For example, 6 factorial would be:
Anonymous functions in MATLAB or 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.
In Maxima anonymous functions are defined using the syntax lambda(argument-list,expression),
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:
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.25
F# supports anonymous functions,26 as follows:
Standard ML supports anonymous functions, as follows:
Nim supports multi-line multi-expression anonymous functions.27
Multi-line example:
Anonymous functions may be passed as input parameters of other functions:
An anonymous function is basically a function without a name.
Perl 5 supports anonymous functions,28 as follows:
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.
Before 4.0.1, PHP had no anonymous function support.29
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)
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, 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 added a new class called Closure and magic method __invoke() that makes a class instance invocable.30
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:
The variable $x is bound by reference so the invocation of $func modifies it and the changes are visible outside of the function.
Arrow functions were introduced in PHP 7.4
Logtalk uses the following syntax for anonymous predicates (lambda expressions):
A simple example with no free variables and using a list mapping predicate is:
Currying is also supported. The above example can be written as:
Anonymous functions (in general anonymous predicates) were introduced in Visual Prolog in version 7.2.31 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:
Python supports simple anonymous functions through the lambda form.32 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:
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 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:
Further information: R (programming language)
In R the anonymous functions are defined using the syntax function(argument-list)expression , which has shorthand since version 4.1.0 \, akin to Haskell.
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.
Further information: 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. Procs behave similarly to closures, whereas lambdas behave more analogous to an anonymous function.33 When passed to a method, a block is converted into a Proc in some circumstances.
In Rust, anonymous functions are called closures.34 They are defined using the following syntax:
For example:
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:
With closures with a single expression (i.e. a body with one line) and implicit return type, the curly braces may be omitted:
Closures with no input parameter are written like so:
Closures may be passed as input parameters of functions that expect a function pointer:
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:35
With these traits, the compiler will capture variables in the least restrictive manner possible.36 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.37
The following demonstrates how one may pass a closure as an input parameter using the Fn trait:
The previous function definition can also be shortened for convenience as follows:
In Scala, anonymous functions use the following syntax:38
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.
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,
Smalltalk blocks are technically closures, allowing them to outlive their defining scope and still refer to the variables declared therein.
In Swift, anonymous functions are called closures.39 The syntax has following form:
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.):
In Tcl, applying the anonymous squaring function to 2 looks as follows:40
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
where {*} is the expansion prefix (new in Tcl 8.5). The command prefix in the above example is apply {x {expr {$x*$x}}} Command names can be bound to command prefixes by means of the interp alias command. Command prefixes support currying. Command prefixes are very common in Tcl APIs.
The other candidate for "function" in Tcl is usually called a lambda, and appears as the {x {expr {$x*$x}}} part of the above example. This is the part which caches the compiled form of the anonymous function, but it can only be invoked by being passed to the apply command. Lambdas do not support currying, unless paired with an apply to form a command prefix. Lambdas are rare in Tcl APIs.
In Vala, anonymous functions are supported as lambda expressions.41
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 Function - it must return a value.
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.
"Statement Exprs (Using the GNU Compiler Collection (GCC))". gcc.gnu.org. Retrieved 2022-01-12. https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html ↩
"Language Specification for Blocks — Clang 13 documentation". clang.llvm.org. Retrieved 2022-01-14. https://clang.llvm.org/docs/BlockLanguageSpec.html ↩
"Lambda expressions (since C++11) - cppreference.com". en.cppreference.com. Retrieved 2022-01-14. https://en.cppreference.com/w/cpp/language/lambda ↩
Järvi, Jaakko; Powell, Gary (n.d.). "Chapter 16. Boost.Lambda". Boost Documentation. Boost. Retrieved December 22, 2014. http://www.boost.org/doc/libs/1_57_0/doc/html/lambda.html ↩
Skeet, Jon (23 March 2019). C# in Depth. Manning. ISBN 978-1617294532. 978-1617294532 ↩
Albahari, Joseph (2022). C# 10 in a Nutshell. O'Reilly. ISBN 978-1-098-12195-2. 978-1-098-12195-2 ↩
"C# Language Specification 5.0". Microsoft Download Center. https://www.microsoft.com/en-us/download/details.aspx?id=7029 ↩
"A tour of the Dart language". dart.dev. Retrieved 2020-11-24. https://dart.dev/guides/language/language-tour ↩
"Erlang/Elixir Syntax: A Crash Course". elixir-lang.github.com. Retrieved 2020-11-24. https://elixir-lang.org/crash-course.html ↩
"Erlang -- Funs". erlang.org. Retrieved 2020-11-24. https://erlang.org/doc/programming_examples/funs.html ↩
"Anonymous Functions in GoLang". GoLang Docs. 9 January 2020. Retrieved 2020-11-24. https://golangdocs.com/anonymous-functions-in-golang ↩
"What's New in JDK 8". http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html ↩
The Java Tutorials: Lambda Expressions, docs.oracle.com http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html ↩
"Chapter 15. Expressions". docs.oracle.com. https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27.4 ↩
"jdk/LambdaMethod.java". GitHub. https://github.com/openjdk/jdk/blob/master/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java#L329-L334 ↩
"Programming in Lua - More about Functions". Archived from the original on 14 May 2008. Retrieved 2008-04-25. http://www.lua.org/pil/6.html ↩
"2.7. Anonymous Functions · GitBook". www.cs.cornell.edu. https://www.cs.cornell.edu/courses/cs3110/2019sp/textbook/basics/anonymous_functions.html ↩
cartermp. "Lambda Expressions: The fun Keyword - F#". docs.microsoft.com. Retrieved 2020-11-24. https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/functions/lambda-expressions-the-fun-keyword ↩
"Nim Manual". nim-lang.github.io. https://nim-lang.github.io/Nim/manual.html#procedures-anonymous-procs ↩
"perlsub - Perl subroutines - Perldoc Browser". perldoc.perl.org. Retrieved 2020-11-24. https://perldoc.perl.org/perlsub ↩
http://php.net/create_function the top of the page indicates this with "(PHP 4 >= 4.0.1, PHP 5)" http://php.net/create_function ↩
"PHP: rfc:closures". wiki.php.net. https://wiki.php.net/rfc/closures ↩
"Anonymous Predicates". in Visual Prolog Language Reference http://wiki.visual-prolog.com/index.php?title=Language_Reference/Terms#Anonymous_Predicates ↩
"6. Expressions — Python 3.9.0 documentation". docs.python.org. Retrieved 2020-11-24. https://docs.python.org/3/reference/expressions.html ↩
Sosinski, Robert (2008-12-21). "Understanding Ruby Blocks, Procs and Lambdas". Reactive.IO. Archived from the original on 2014-05-31. Retrieved 2014-05-30. https://web.archive.org/web/20140531123646/http://www.reactive.io/tips/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/ ↩
"Closures - Rust By Example". doc.rust-lang.org. https://doc.rust-lang.org/stable/rust-by-example/fn/closures.html ↩
"As input parameters - Rust By Example". doc.rust-lang.org. https://doc.rust-lang.org/stable/rust-by-example/fn/closures/input_parameters.html ↩
"Lifetimes - Rust By Example". doc.rust-lang.org. https://doc.rust-lang.org/stable/rust-by-example/scope/lifetime.html ↩
"Anonymous Function Syntax - Scala Documentation". Archived from the original on 2013-07-23. Retrieved 2010-12-31. https://web.archive.org/web/20130723023605/http://www.scala-lang.org/node/133 ↩
"Closures — The Swift Programming Language (Swift 5.5)". docs.swift.org. https://docs.swift.org/swift-book/LanguageGuide/Closures.html ↩
apply manual page, retrieved 2012-09-06. http://www.tcl.tk/man/tcl8.5/TclCmd/apply.htm ↩
Vala Reference Manual, retrieved 2021-06-09. https://wiki.gnome.org/Projects/Vala/Manual/Methods#Lambdas ↩