SUPPORT THE WORK

GetWiki

Anonymous function#C++ (since C++11)

ARTICLE SUBJECTS
aesthetics  →
being  →
complexity  →
database  →
enterprise  →
ethics  →
fiction  →
history  →
internet  →
knowledge  →
language  →
licensing  →
linux  →
logic  →
method  →
news  →
perception  →
philosophy  →
policy  →
purpose  →
religion  →
science  →
sociology  →
software  →
truth  →
unix  →
wiki  →
ARTICLE TYPES
essay  →
feed  →
help  →
system  →
wiki  →
ARTICLE ORIGINS
critical  →
discussion  →
forked  →
imported  →
original  →
Anonymous function#C++ (since C++11)
[ temporary import ]
please note:
- the content below is remote from Wikipedia
- it has been imported raw for GetWiki
{{short description|Function definition that is not bound to an identifier}}In computer programming, an anonymous function (function literal, lambda abstraction, lambda function, lambda expression or block) 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.WEB, Higher order functions,weblink 3 December 2014, learnyouahaskell.com, en-US, 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.{{citation|title=Models of Computation: An Introduction to Computability Theory|series=Undergraduate Topics in Computer Science|first=Maribel|last=Fernandez|publisher=Springer Science & Business Media|year=2009|isbn=9781848824348|page=33|url=https://books.google.com/books?id=FPFsnzzebhQC&pg=PA33|quote=The Lambda calculus ... was introduced by Alonzo Church in the 1930s as a precise notation for a theory of anonymous functions}} 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.{{toclimit|3}}

Names

The names "lambda abstraction", "lambda function", and "lambda expression" refer to the notation of function abstraction in lambda calculus, where the usual function {{math|1={{itco|f}}(x) = M}} would be written {{math|1=(λx.{{itco|M}})}}, and where {{mvar|M}} is an expression that uses {{mvar|x}}. Compare to the Python syntax of lambda x: M.The name "arrow function" refers to the mathematical "maps to" symbol, {{math|x ↦ M}}. Compare to the JavaScript syntax of x => M.WEB, Arrow function expressions - JavaScript,weblink August 21, 2019, MDN, en-US,

Uses

{{Unreferenced Section|date=February 2018}}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 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 = ['house', 'car', 'bike'] a.sort(key=lambda x: len(x)) a
['car', 'bike', 'house']The anonymous function in this example is the lambda expression:lambda x: len(x)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.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 add(20)
40Another example would be sorting items in a list by the name of their class (in Python, everything has a class):
a = [10, 'number', 11.2] a.sort(key=lambda x: x.__class__.__name__) a
[11.2, 10, 'number']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(threshold):
return lambda x: x < threshold
This can be used as a sort of generator of comparison functions:
func_a = comp(10) func_b = comp(20)
print(func_a(5), func_a(8), func_a(13), func_a(21))
True True False False
print(func_b(5), func_b(8), func_b(13), func_b(21))
True True True FalseIt 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(x, y):
... return x / y
def divisor(d):
... return lambda x: divide(x, d)
half = divisor(2) third = divisor(3)
print(half(32), third(32))
16.0 10.666666666666666
print(half(40), third(40))
20.0 13.333333333333334While 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 or returns one as a result. 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 = [1, 2, 3, 4, 5, 6] list(map(lambda x: x*x, a))
[1, 4, 9, 16, 25, 36]The anonymous function accepts an argument and multiplies it by itself (squares it). 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 = [1, 2, 3, 4, 5, 6] [x*x for x in a]
[1, 4, 9, 16, 25, 36]

Filter

The filter function returns all elements from a list that evaluate True when passed to a certain function.
a = [1, 2, 3, 4, 5, 6] list(filter(lambda x: x % 2 == 0, a))
[2, 4, 6]The anonymous function checks if the argument passed to it is even. The same as with map, the form below is considered more appropriate:
a = [1, 2, 3, 4, 5, 6] [x for x in a if x % 2 == 0]
[2, 4, 6]

Fold

A fold function runs over all elements in a structure (for lists usually left-to-right, a "left fold", called reduce in Python), 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 = [1, 2, 3, 4, 5] reduce(lambda x,y: x*y, a)
120This performs
left(
left(
left(
1 times 2
right)
times 3
right)
times 4
right)times 5

120.

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 (C, Pascal, Object Pascal) 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++ (by the C++11 standard). Second, the languages that treat functions as first-class functions (Dylan, Haskell, JavaScript, Lisp, ML, Perl, Python, Ruby, Scheme) generally have anonymous function support so that functions can be defined and passed around as easily as other data types.{{Expand list|date=August 2008}}{| class="sortable wikitable" style="text-align: left; font-size: 0.92em;"|+ List of languages style="position:sticky; top:0"! Language !! Support !! Notes
| ActionScript
{{Y}}}}|
Ada (programming language)>Ada{{N}}}}| Expression functions are a part of Ada2012
| ALGOL 68
{{Y}}}}|
APL (programming language)>APL{{Y}}}}| Dyalog, ngn and dzaima APL fully support both dfns and tacit functions. GNU APL has rather limited support for dfns.
| Assembly languages
{{N}}}}|
AutoHotkey>AHK{{Y}}}}| Since AutoHotkey V2 anonymous functions are supported with a syntax similar to JavaScript.
Bash (Unix shell)>Bash{{Y}}}}GITHUB>URL=HTTPS://GITHUB.COM/SPENCERTIPPING/BASH-LAMBDA, 2019-03-08,
C (programming language)>C{{N}}}}| 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 Sharp (programming language)>C#{{Y}}}}URL=HTTPS://DOCS.MICROSOFT.COM/EN-US/DOTNET/CSHARP/LANGUAGE-REFERENCE/OPERATORS/LAMBDA-EXPRESSIONSWEBSITE=DOCS.MICROSOFT.COM, en-us,
| C++
{{Y}}}}| As of the C++11 standard
ColdFusion Markup Language>CFML{{Y}}}}Railo 4,CLOSURE SUPPORTACCESS-DATE=2014-01-05ARCHIVE-DATE=2014-01-06ColdFusion 10WHATS NEW IN COLDFUSION 10ACCESS-DATE=2014-01-05ARCHIVE-DATE=2014-01-06, dead,
| Clojure
{{Y}}}}ACCESS-DATE=2022-01-14, clojure.org,
| COBOL
{{N}}}}Micro Focus's non-standard Managed COBOL dialect supports lambdas, which are called anonymous delegates/methods.HTTP://DOCUMENTATION.MICROFOCUS.COM/HELP/TOPIC/COM.MICROFOCUS.ECLIPSE.INFOCENTER.VISUALCOBOL.VS/GUID-DA75663F-6357-4064-8112-C87E7457DE51.HTML PUBLISHER=MICRO FOCUS ACCESS-DATE=25 FEBRUARY 2014 ARCHIVE-DATE=25 FEBRUARY 2014,
Curl (programming language)>Curl{{Y}}}}|
D (programming language)>D{{Y}}}}ACCESS-DATE=2022-01-14, dlang.org,
Dart (programming language)>Dart{{Y}}}}ACCESS-DATE=2020-11-24, dart.dev,
Delphi (programming language)>Delphi{{Y}}}}ACCESS-DATE=2020-11-24, docwiki.embarcadero.com,
Dylan (programming language)>Dylan{{Y}}}}ACCESS-DATE=2022-01-14, opendylan.org,
Eiffel (programming language)>Eiffel{{Y}}}}|
Elm (programming language)>Elm{{Y}}}}ACCESS-DATE=2022-01-14, elm-lang.org,
Elixir (programming language)>Elixir{{Y}}}}ACCESS-DATE=2020-11-24LANGUAGE=EN,
Erlang (programming language)>Erlang{{Y}}}}ACCESS-DATE=2020-11-24, erlang.org,
F Sharp (programming language)>F#{{Y}}}}URL=HTTPS://DOCS.MICROSOFT.COM/EN-US/DOTNET/FSHARP/LANGUAGE-REFERENCE/FUNCTIONS/LAMBDA-EXPRESSIONS-THE-FUN-KEYWORDWEBSITE=DOCS.MICROSOFT.COM, en-us,
Microsoft Excel>Excel{{Y}}}}ACCESS-DATE=2021-03-30DATE=25 JANUARY 2021, en-us,
Factor (programming language)>Factor{{Y}}}}ACCESS-DATE=26 DECEMBER 2015, A quotation is an anonymous function (a value denoting a snippet of code) which can be used as a value and called using the Fundamental combinators.,
| Fortran
{{N}}}}|
Frink (programming language)>Frink{{Y}}}}ACCESS-DATE=2020-11-24, frinklang.org,
Go (programming language)>Go{{Y}}}}ACCESS-DATE=2020-11-24DATE=9 JANUARY 2020, en-US,
Gosu (programming language)>Gosu{{Y}}}}ACCESS-DATE=4 MARCH 2013,
Groovy (programming language)>Groovy{{Y}}}}ACCESS-DATE=29 MAY 2012ARCHIVE-DATE=22 MAY 2012, dead,
Haskell (programming language)>Haskell{{Y}}}}ACCESS-DATE=2022-01-14, wiki.haskell.org,
| Haxe
{{Y}}}}ACCESS-DATE=2022-01-14, Haxe - The Cross-platform Toolkit,
Java (programming language)>Java{{Y}}}}Java 8. See the #Java limitations>Java limitations section below for details.
| JavaScript
{{Y}}}}access-date=2022-01-14language=en-US}}
Julia (programming language)>Julia{{Y}}}}ACCESS-DATE=2020-11-24, docs.julialang.org,
Kotlin (programming language)>Kotlin{{Y}}}}ACCESS-DATE=2020-11-24LANGUAGE=EN,
Lisp (programming language)>Lisp{{Y}}}}|
| Logtalk
{{Y}}}}|
Lua (programming language)>Lua{{Y}}}}ACCESS-DATE=2020-11-24, www.lua.org,
MUMPS (programming language)>MUMPS{{N}}}}|
Maple (software)>Maple{{Y}}}}ACCESS-DATE=2020-11-24, www.maplesoft.com,
| MATLAB
{{Y}}}}ACCESS-DATE=2022-01-14, www.mathworks.com,
Maxima (software)>Maxima{{Y}}}}ACCESS-DATE=2020-11-24, maths.cnam.fr,
Nim (programming language)>Nim{{Y}}}}WEBSITE=NIM-LANG.GITHUB.IO,
| OCaml
{{Y}}}}ACCESS-DATE=2020-11-24, ocaml.org,
GNU Octave>Octave{{Y}}}}ACCESS-DATE=2020-11-24, octave.org,
| Object Pascal
{{Y}}}}anonymous methods) natively since Delphi 2009. The Oxygene (programming language)>Oxygene Object Pascal dialect also supports them.
| Objective-C (Mac OS X 10.6+)
{{Y}}}}Blocks (C language extension)>blocks; in addition to Objective-C, blocks can also be used on C and C++ when programming on Apple's platform.
|OpenSCAD
{{Y}}}}WEBSITE=OPENSCAD USER MANUAL ACCESS-DATE=22 FEBRUARY 2021,
Pascal (programming language)>Pascal{{N}}}}|
| Perl
{{Y}}}}ACCESS-DATE=2020-11-24, perldoc.perl.org,
| PHP
{{Y}}}}ACCESS-DATE=2020-11-24, www.php.net, Formerly, only partial anonymous functions were supported, which worked much like C#'s implementation.
| PL/I
{{N}}}}|
Python (programming language)>Python{{Y}}}}ACCESS-DATE=2020-11-24, docs.python.org, which supports only expressions, not statements.
R (programming language)>R{{Y}}}}|
Racket (programming language)>Racket{{Y}}}}ACCESS-DATE=2020-11-24, docs.racket-lang.org,
Raku (programming language)>Raku{{Y}}}}ACCESS-DATE=2022-01-14, docs.raku.org,
| Rexx
{{N}}}}|
IBM RPG>RPG{{N}}}}|
Ruby (programming language)>Ruby{{Y}}}}Smalltalk, are called Ruby (programming language)#Blocks and iterators>blocks.
Rust (programming language)>Rust{{Y}}}}ACCESS-DATE=2022-01-14, doc.rust-lang.org,
Scala (programming language)>Scala{{Y}}}}ACCESS-DATE=2022-01-14, Scala Documentation,
Scheme (programming language)>Scheme{{Y}}}}|
| Smalltalk
{{Y}}}}Smalltalk#Code blocks>blocks.
| Standard ML
{{Y}}}}ACCESS-DATE=2022-01-14, www.cs.cornell.edu,
Swift (programming language)>Swift{{Y}}}}| Swift's anonymous functions are called Closures.
| TypeScript
{{Y}}}}ACCESS-DATE=2022-01-14LANGUAGE=EN,
| Tcl
{{Y}}}}ACCESS-DATE=2020-11-24, wiki.gnome.org,
Vala (programming language)>Vala{{Y}}}}|
| Visual Basic .NET v9
{{Y}}}}URL=HTTPS://DOCS.MICROSOFT.COM/EN-US/DOTNET/VISUAL-BASIC/PROGRAMMING-GUIDE/LANGUAGE-FEATURES/PROCEDURES/LAMBDA-EXPRESSIONSWEBSITE=DOCS.MICROSOFT.COMLANGUAGE=EN-US,
| Visual Prolog v 7.2
{{Y}}}}ACCESS-DATE=2022-01-14, wiki.visual-prolog.com,
| Wolfram Language
{{Y}}}}ACCESS-DATE=2022-01-14LANGUAGE=EN,
Zig (programming language)> Zig{{N}}}}ACCESS-DATE=2023-08-21 LANGUAGE=EN,

Examples

{{how-to|section|date=December 2018}}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 (fork)
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 GCCWEB, Statement Exprs (Using the GNU Compiler Collection (GCC)),weblink 2022-01-12, gcc.gnu.org, and Clang.

GCC

The GNU Compiler Collection (GCC) supports anonymous functions, mixed by nested functions and statement expressions. It has the form:( { return_type anonymous_functions_name (parameters) { function_body } anonymous_functions_name; } )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.
  1. include
//* this is the definition of the anonymous function */
  1. define lambda(l_ret_type, l_arguments, l_body)


({
l_ret_type l_anonymous_functions_name l_arguments
l_body
&l_anonymous_functions_name;
})
  1. define forEachInArray(fe_arrType, fe_arr, fe_fn_body)
{
int i=0;
for(;i 1 ? n * factorial(n-1) : 1;
};CFML anonymous functions implement closure.

D

D uses inline delegates to implement anonymous functions. The full syntax for an inline delegate isreturn_type delegate(arguments){/*body*/}If unambiguous, the return type and the keyword delegate can be omitted.(x){return x*x;}delegate (x){return x*x;} // if more verbosity is needed(int x){return x*x;} // if parameter type cannot be inferreddelegate (int x){return x*x;} // dittodelegate double(int x){return x*x;} // if return type must be forced manuallySince 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){return x*x;};double y = sqr(4);

Dart

Dart supports anonymous functions.var sqr = (x) => x * x;print(sqr(5));orprint(((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 supports anonymous functions using lambda syntaxbegin
var n := 10000000;
var pp := (1..n)
.Select(x -> (Random, Random))
.Where(p -> Sqr(p[0]) + Sqr(p[1]) < 1)
.Count / n * 4;
Print(pp);
end.

Elixir

Elixir uses the closure fn for anonymous functions.sum = fn(a, b) -> a + b endsum.(4, 3)
  1. => 7
square = fn(x) -> x * x endEnum.map [1, 2, 3, 4], square
  1. => [1, 4, 9, 16]

Erlang

Erlang uses a syntax for anonymous functions similar to that of named functions.% Anonymous function bound to the Square variableSquare = fun(X) -> X * X end.% Named function with the same functionalitysquare(X) -> X * X.

Go

Go supports anonymous functions.foo := func(x int) int { return x * x}fmt.Println(foo(10))

Haskell

Haskell uses a concise syntax for anonymous functions (lambda expressions). The backslash is supposed to resemble λ.x -> x * xLambda expressions are fully integrated with the type inference engine, and support all the syntax and features of "ordinary" functions (except for the use of multiple definitions for pattern-matching, since the argument list is only specified once).map (x -> x * x) [1..5] -- returns [1, 4, 9, 16, 25]The following are all equivalent:f x y = x + yf x = y -> x + yf = x y -> x + y

Haxe

In Haxe, 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 supports anonymous functions, named Lambda Expressions, starting with JDK 8.WEB,weblink What's New in 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) -> { return a + b; }// with multiple statements in the lambda body. It needs a code block.// This example also includes two nested lambda expressions (the first one is also a closure).(id, defaultPrice) -> {
Optional product = productList.stream().filter(p -> p.getId() == id).findFirst();
return product.map(p -> p.getPrice()).orElse(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 {
interface IntegerMath {
int operation(int a, int b);


default IntegerMath swap() {
return (a, b) -> operation(b, a);
}
}


private static int apply(int a, int b, IntegerMath op) {
return op.operation(a, b);
}


public static void main(String... args) {
IntegerMath addition = (a, b) -> a + b;
IntegerMath subtraction = (a, b) -> a - b;
System.out.println("40 + 2 = " + apply(40, 2, addition));
System.out.println("20 - 10 = " + apply(20, 10, subtraction));
System.out.println("10 - 20 = " + apply(20, 10, subtraction.swap()));
}
}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.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

Anonymous classes of lambda-compatible interfaces are similar, but not exactly equivalent, to lambda expressions.To illustrate, in the following example, {{code|anonymousClass}} and {{code|lambdaExpression}} are both instances of {{code|IntegerMath}} that add their two parameters:IntegerMath anonymousClass = new IntegerMath() {
@Override
public int operation(int a, int b) {
return a + b;
}
};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 {{code|IntegerMath}}, and can return the same instance every time this code is run.WEB,weblink Chapter 15. Expressions, docs.oracle.com, Additionally, in the OpenJDK implementation at least, lambdas are compiled to {{mono|invokedynamic}} instructions, with the lambda body inserted as a static method into the surrounding class,WEB, jdk/LambdaMethod.java, GitHub,weblink rather than generating a new class file entirely.

Java limitations

Java 8 lambdas have the following limitations:
  • Lambdas can throw checked exceptions, but such lambdas will not work with the interfaces used by the Collection API.
  • Variables that are in-scope where the lambda is declared may only be accessed inside the lambda if they are effectively final, i.e. if the variable is not mutated inside or outside of the lambda scope.

JavaScript

JavaScript/ECMAScript supports anonymous functions.alert((function(x){
return x * x;
})(10));ES6 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 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.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:(function(){document.title=location.href;})();The function statement in the first (outer) pair of parentheses declares an anonymous function, which is then executed when used with the last pair of parentheses. This is almost equivalent to the following, which populates the environment with f unlike an anonymous function.var f = function(){document.title=location.href;}; f();Use void() to avoid new pages for arbitrary anonymous functions:void(function(){return document.title=location.href;}());or just:void(document.title=location.href);JavaScript has syntactic subtleties for the semantics of defining, invoking and evaluating anonymous functions. These subliminal nuances are a direct consequence of the evaluation of parenthetical expressions. The following constructs which are called immediately-invoked function expression illustrate this:(function(){ ... }()) and (function(){ ... })()Representing "function(){ ... }" by f, the form of the constructs are a parenthetical within a parenthetical (f()) and a parenthetical applied to a parenthetical (f)().Note the general syntactic ambiguity of a 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(function(){( function(){( ... {( function(){stuff}() )} ... )}() )}() )More correctly but with caveats, ( function(){stuff}() ) ~=
A_Fixed_Point_of(
function(){ return function(){ return ... { return function(){stuff}() } ... }() }()
)
Note the implications of the anonymous function in the JavaScript fragments that follow:
  • function(){ ... }() without surrounding ()'s is generally not legal
  • (f=function(){ ... }) does not "forget" f globally unlike (function f(){ ... })


Performance metrics to analyze the space and time complexities of function calls, call stack, etc. in a JavaScript interpreter engine implement easily with these last anonymous function constructs. From the implications of the results, it is possible to deduce some of an engine's recursive versus iterative implementation details, especially tail-recursion.

Julia

In Julia anonymous functions are defined using the syntax (arguments)->(expression),julia> f = x -> x*x; f(8)64julia> ((x,y)->x+y)(5,6)11

Kotlin

Kotlin supports anonymous functions with the syntax {arguments -> expression},val sum = { x: Int, y: Int -> x + y }sum(5,6) // returns 11val even = { x: Int -> x%2==0}even(4) // returns true

Lisp

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

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
  1. '(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 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 supports anonymous functions through the "fn" special form:(fn [x] (+ x 3))There is also a reader syntax to define a lambda:
  1. (+ % %2%3) ; Defines an anonymous function that takes three arguments and sums them.
Like Scheme, Clojure's "named functions" are simply syntactic sugar for lambdas bound to names:(defn func [arg] (+ 3 arg))expands to:(def func (fn [arg] (+ 3 arg)))

Lua

In Lua (much as in Scheme) all functions are anonymous. A named function in Lua is simply a variable holding a reference to a function object.WEB, Programming in Lua - More about Functions,weblink 2008-04-25,weblink" title="web.archive.org/web/20080514220940weblink">weblink 14 May 2008, live, Thus, in Luafunction foo(x) return 2*x endis just syntactical sugar forfoo = function(x) return 2*x endAn 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 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]
x [Function] x+1
So, for instance:
f:= #1^2&;f[8]
64
#1+#2&[5,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: For example, 6 factorial would be: 720

MATLAB, Octave

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.
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*x); f(8);64lambda([x,y],x+y)(5,6);11

ML

The various dialects of ML support anonymous functions.

OCaml

Anonymous functions in OCaml are functions without a declared name. Here is an example of an anonymous function that multiplies its input by two: fun x -> x*2In 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.WEB,weblink 2.7. Anonymous Functions · GitBook, www.cs.cornell.edu,

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 + var2assert anon(1, 2) == 3Multi-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 supports anonymous functions, as follows:(sub { print "I got calledn" })->(); # 1. fully anonymous, called as createdmy $squarer = sub { my $x = shift; $x * $x }; # 2. assigned to a variablesub curry {
my ($sub, @args) = @_;
return sub { $sub->(@args, @_) }; # 3. as a return value of another function
}
  1. example of currying in Perl programming
sub sum { my $tot = 0; $tot += $_ for @_; $tot } # returns the sum of its argumentsmy $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 do not have the same parameter-passing convention as functions -- @_ is not set.my @squares = map { $_ * $_ } 1..10; # map and grep don't use the 'sub' keywordmy @square2 = map $_ * $_, 1..10; # braces unneeded for one expressionmy @bad_example = map { print for @_ } 1..10; # values not passed like normal Perl function

PHP

Before 4.0.1, PHP had no anonymous function supportweblink the top of the page indicates this with "(PHP 4 >= 4.0.1, PHP 5)"

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, 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.WEB,weblink PHP: rfc:closures, wiki.php.net, $x = 3;$func = function($z) { return $z * 2; };echo $func($x); // prints 6In 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) { $x *= 2; };$func();echo $x; // prints 6The 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 uses the following syntax for anonymous predicates (lambda expressions):{FreeVar1, FreeVar2, ...}/[LambdaParameter1, LambdaParameter2, ...]>>Goal A simple example with no free variables and using a list mapping predicate is:| ?- meta::map([X,Y]>>(Y is 2*X), [1,2,3], Ys).Ys = [2,4,6]yesCurrying is also supported. The above example can be written as:| ?- meta::map([X]>>([Y]>>(Y is 2*X)), [1,2,3], Ys).Ys = [2,4,6]yes

Visual Prolog

Anonymous functions (in general anonymous predicates) were introduced in Visual Prolog in version 7.2.WEB, Anonymous Predicates,weblink in Visual Prolog Language Reference Anonymous predicates can capture values from the context. If created in an object member, it can also access the object state (by capturing This).mkAdder returns an anonymous function, which has captured the argument X in the closure. The returned function is a function that adds X to its argument:clauses
mkAdder(X) = { (Y) = X+Y }.

Python

Python supports simple anonymous functions through the lambda form. The executable body of the lambda must be an expression and can't be a statement, which is a restriction that limits its utility. The value returned by the lambda is the value of the contained expression. Lambda forms can be used anywhere ordinary functions can. However these restrictions make it a very limited version of a normal function. Here is an example:
foo = lambda x: x * x foo(10)
100In 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:
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

{{details|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.
f (function(x,y)x+y)(5,6)
[1] 11
# Since R 4.1.0 ((x,y) x+y)(5, 6)
[1] 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.
  1. fully anonymous, called as created
  2. :
{ say "I got called" };
  1. assigned to a variable
  2. :
my $squarer1 = -> $x { $x * $x }; # 2a. pointy blockmy $squarer2 = { $^x * $^x }; # 2b. twigilmy $squarer3 = { my $x = shift @_; $x * $x }; # 2c. Perl 5 style
  1. currying
  2. :
sub add ($m, $n) { $m + $n }my $seven = add(3, 4);my $add_one = &add.assuming(m => 1);my $eight = $add_one($seven);
  1. WhateverCode object
  2. :
my $w = * - 1; # WhateverCode objectmy $b = { $_ - 1 }; # same functionality, but as Callable block

Ruby

{{details|Ruby (programming language)#Blocks and iterators}}Ruby supports anonymous functions by using a syntactical structure called block. There are two data types for blocks in Ruby. Procs behave similarly to closures, whereas lambdas behave more analogous to an anonymous function.WEB,weblink Understanding Ruby Blocks, Procs and Lambdas, Sosinski, Robert, Reactive.IO, 2008-12-21, 2014-05-30, dead,weblink" title="web.archive.org/web/20140531123646weblink">weblink 2014-05-31, When passed to a method, a block is converted into a Proc in some circumstances.
  1. Example 1:
  2. Purely anonymous functions using blocks.
ex = [16.2, 24.1, 48.3, 32.4, 8.5]

> [16.2, 24.1, 48.3, 32.4, 8.5]

ex.sort_by { |x| x - x.to_i } # Sort by fractional part, ignoring integer part.

> [24.1, 16.2, 48.3, 32.4, 8.5]

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

> #

ex.callHello, world!

> nil

  1. Example 3:
  2. Function that returns lambda function object with parameters
def multiple_of?(n)
lambda{|x| x % n == 0}
end

> nil

multiple_four = multiple_of?(4)

> #

multiple_four.call(16)

> true

multiple_four[15]

> false

Rust

In Rust, anonymous functions are called closures.WEB,weblink Closures - Rust By Example, doc.rust-lang.org, They are defined using the following syntax: -> { };For example:let f = |x: i32| -> i32 { x * 2 };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| { x * 2 };With closures with a single expression (i.e. a body with one line) and implicit return type, 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 {
// No semicolon, to indicate an implicit return
f(5)
}fn main() {
// Defining the closure
let f = |x| x * 2;


println!("{}", apply(f)); // 10
println!("{}", f(5)); // 10
}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:WEB,weblink As input parameters - Rust By Example, doc.rust-lang.org,
  • 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.WEB, Lifetimes - Rust By Example,weblink doc.rust-lang.org, 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
{
f(5)
}fn main() {
let f = |x| {
println!("I got the value: {}", x);
x * 2
};

// Applies the function before printing its return value
println!("5 * 2 = {}", apply_by_ref(f));
}// ~~ Program output ~~// I got the value: 5// 5 * 2 = 10The previous function definition can also be shortened for convenience as follows:fn apply_by_ref(f: impl Fn(i32) -> i32) -> i32 {
f(5)
}

Scala

In Scala, anonymous functions use the following syntax:WEB, Anonymous Function Syntax - Scala Documentation,weblink dead,weblink" title="web.archive.org/web/20130723023605weblink">weblink 2013-07-23, 2010-12-31, en-US, (x: Int, y: Int) => x + yIn 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]],st> f:=[:x|x*x]. f value: 8 .64st> [:x :y|x+y] value: 5 value: 6 .11Smalltalk blocks are technically closures, allowing them to outlive their defining scope and still refer to the variables declared therein.st> f := [:a|[:n|a+n) value: 100 .a BlockClosure"returns the inner block, which adds 100 (captured in "a" variable) to its argument."st> f value: 1 .101st> f value: 2 .102

Swift

In Swift, anonymous functions are called closures.WEB,weblink Closures — The Swift Programming Language (Swift 5.5), docs.swift.org, The syntax has following form:{ (parameters) -> returnType in
statement
}For example:{ (s1: String, s2: String) -> Bool in
return s1 > s2
}For sake of brevity and expressiveness, the parameter types and return type can be omitted if these can be inferred:{ s1, s2 in return s1 > s2 }Similarly, Swift also supports implicit return statements for one-statement closures:{ s1, s2 in s1 > s2 }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.):{ $0 > $1 }

Tcl

In Tcl, applying the anonymous squaring function to 2 looks as follows:apply manual page, retrieved 2012-09-06.apply {x {expr {$x*$x}}} 2
  1. 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 $xwhere {*} 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.

Vala

In Vala, anonymous functions are supported as lambda expressions.Vala Reference Manual, retrieved 2021-06-09.delegate int IntOp (int x, int y);void main () { IntOp foo = (x, y) => x * y; stdout.printf("%dn", foo(10,5));}

Visual Basic .NET

Visual Basic .NET 2008 introduced anonymous functions through the lambda form. Combined with implicit typing, VB provides an economical syntax for anonymous functions. As with Python, in VB.NET, anonymous functions must be defined on one line; they cannot be compound statements. Further, an anonymous function in VB.NET must truly be a VB.NET Function - it must return a value. Dim foo = Function(x) x * xConsole.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

{{Clear}}

References

{{Reflist|30em}}

External links

{{Authority control}}

- content above as imported from Wikipedia
- "Anonymous function#C++ (since C++11)" does not exist on GetWiki (yet)
- time: 5:11am EDT - Sat, May 18 2024
[ this remote article is provided by Wikipedia ]
LATEST EDITS [ see all ]
GETWIKI 23 MAY 2022
GETWIKI 09 JUL 2019
Eastern Philosophy
History of Philosophy
GETWIKI 09 MAY 2016
GETWIKI 18 OCT 2015
M.R.M. Parrott
Biographies
GETWIKI 20 AUG 2014
CONNECT