Examples of anonymous functions

Last updated

Examples of anonymous functions

Numerous languages support anonymous functions, or something similar.

Contents

APL

Only some dialects support anonymous functions, either as dfns, in the tacit style or a combination of both.

f{×}Asadfnf123149g⊢×⊢Asatacit3-train(fork)g123149h×Asaderivedtacitfunctionh123149

C (non-standard extension)

The anonymous function is not supported by standard C programming language, but supported by some C dialects, such as GCC [1] and Clang.

GCC

The GNU Compiler Collection (GCC) supports anonymous functions, mixed by nested functions and statement expressions. It has the form:

({return_typeanonymous_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.

#include<stdio.h>//* this is the definition of the anonymous function */#define lambda(l_ret_type, l_arguments, l_body)        \  ({                                                   \   l_ret_type l_anonymous_functions_name l_arguments   \   l_body                                              \   &l_anonymous_functions_name;                        \   })#define forEachInArray(fe_arrType, fe_arr, fe_fn_body)                                    \{                                                                                         \  int i=0;                                                                                \  for(;i<sizeof(fe_arr)/sizeof(fe_arrType);i++) {  fe_arr[i] = fe_fn_body(&fe_arr[i]); }  \}typedefstruct{inta;intb;}testtype;voidprintout(consttesttype*array){inti;for(i=0;i<3;++i)printf("%d %d\n",array[i].a,array[i].b);printf("\n");}intmain(void){testtypearray[]={{0,1},{2,3},{4,5}};printout(array);/* the anonymous function is given as function for the foreach */forEachInArray(testtype,array,lambda(testtype,(void*item),{inttemp=(*(testtype*)item).a;(*(testtype*)item).a=(*(testtype*)item).b;(*(testtype*)item).b=temp;return(*(testtype*)item);}));printout(array);return0;}

Clang (C, C++, Objective-C, Objective-C++)

Clang supports anonymous functions, called blocks, [2] which have the form:

^return_type(parameters){function_body}

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:

#include<stdio.h>#include<dispatch/dispatch.h>intmain(void){void(^count_loop)()=^{for(inti=0;i<100;i++)printf("%d\n",i);printf("ah ah ah\n");};/* Pass as a parameter to another function */dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),count_loop);/* Invoke directly */count_loop();return0;}

The code with blocks should be compiled with -fblocks and linked with -lBlocksRuntime

C++ (since C++11)

C++11 supports anonymous functions (technically function objects), called lambda expressions, [3] which have the form:

[captures](params)specsrequires(optional){body}

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:

[](intx,inty){returnx+y;}

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:

[]// No captures, the lambda is implicitly convertible to a function pointer.[x,&y]// x is captured by value and y is captured by reference.[&]// Any external variable is implicitly captured by reference if used[=]// Any external variable is implicitly captured by value if used.[&,x]// x is captured by value. Other variables will be captured by reference.[=,&z]// z is captured by reference. Other variables will be captured by value.

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:

std::unique_ptr<int>ptr=std::make_unique<int>(42);[ptr]{/* ... */};// copy assignment is deleted for a unique pointer[ptr=std::move(ptr)]{/* ... */};// okautocounter=[i=0]()mutable{returni++;};// mutable is required to modify 'i'counter();// 0counter();// 1counter();// 2

The following two examples demonstrate use of a lambda expression:

std::vector<int>some_list{1,2,3,4,5};inttotal=0;std::for_each(begin(some_list),end(some_list),[&total](intx){total+=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<int>some_list{1,2,3,4,5};inttotal=0;intvalue=5;std::for_each(begin(some_list),end(some_list),[&total,value,this](intx){total+=x*value*this->some_func();});

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,

automy_lambda_func=[&](intx){/*...*/};automy_onheap_lambda_func=newauto([=](intx){/*...*/});

Here is an example of storing anonymous functions in variables, vectors, and arrays; and passing them as named parameters:

#include<functional>#include<iostream>#include<vector>doubleeval(std::function<double(double)>f,doublex=2.0){returnf(x);}intmain(){std::function<double(double)>f0=[](doublex){return1;};autof1=[](doublex){returnx;};decltype(f0)fa[3]={f0,f1,[](doublex){returnx*x;}};std::vector<decltype(f0)>fv={f0,f1};fv.push_back([](doublex){returnx*x;});for(size_ti=0;i<fv.size();i++){std::cout<<fv[i](2.0)<<std::endl;}for(size_ti=0;i<3;i++){std::cout<<fa[i](2.0)<<std::endl;}for(auto&f:fv){std::cout<<f(2.0)<<std::endl;}for(auto&f:fa){std::cout<<f(2.0)<<std::endl;}std::cout<<eval(f0)<<std::endl;std::cout<<eval(f1)<<std::endl;std::cout<<eval([](doublex){returnx*x;})<<std::endl;}

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:

autoa_lambda_func=[](intx)->void{/*...*/};void(*func_ptr)(int)=a_lambda_func;func_ptr(4);//calls the lambda.

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:

autofibonacci=[](thisautoself,intn){returnn<=1?n:self(n-1)+self(n-2);};fibonacci(7);// 13

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]

for_each(a.begin(),a.end(),std::cout<<_1<<' ');

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:

[captures]<tparams>requires(optional)(params)specsrequires(optional){body}

C#

In C#, support for anonymous functions has deepened through the various versions of the language compiler. The language v3.0, released in November 2007 with .NET Framework v3.5, has full support of anonymous functions. [5] :7–8 [6] :26 C# names them lambda expressions, following the original version of anonymous functions, the lambda calculus. [7] [5] :7–8,91 [6] :91

// the first int is the x' type// the second int is the return type// <see href="http://msdn.microsoft.com/en-us/library/bb549151.aspx" />Func<int,int>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. [5] :101–103 E.g., this does not work:

// will NOT compile!varfoo=(intx)=>x*x;

However, a lambda expression can take part in type inference and can be used as a method argument, e.g. to use anonymous functions with the Map capability available with System.Collections.Generic.List (in the ConvertAll() method):

// Initialize the list:varvalues=newList<int>(){7,13,4,9,3};// Map the anonymous function over all elements in the list, return the new listvarfoo=values.ConvertAll(d=>d*d);// the result of the foo variable is of type System.Collections.Generic.List<Int32>

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. [5] :6 C# names them lambda expressions, following the original version of anonymous functions, the lambda calculus. [5] :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. [5] :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:

publicclassTestDriver{delegateintSquareDelegate(intd);staticintSquare(intd){returnd*d;}staticvoidMain(string[]args){// C# 1.0: Original delegate syntax needed // initializing with a named method.SquareDelegateA=newSquareDelegate(Square);System.Console.WriteLine(A(3));// C# 2.0: A delegate can be initialized with// inline code, called an "anonymous method". This// method takes an int as an input parameter.SquareDelegateB=delegate(intd){returnd*d;};System.Console.WriteLine(B(5));// C# 3.0. A delegate can be initialized with// a lambda expression. The lambda takes an int, and returns an int. // The type of x is inferred by the compiler.SquareDelegateC=x=>x*x;System.Console.WriteLine(C(7));// C# 3.0. A delegate that accepts one input and// returns one output can also be implicitly declared with the Func<> type.System.Func<int,int>D=x=>x*x;System.Console.WriteLine(D(9));}}

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. [5] :103 In the case of the C# 3.0 version, the same mechanism applies.

ColdFusion Markup Language (CFML)

Using the function keyword:

fn=function(){// statements};

Or using an arrow function:

fn=()=>{// statements};fn=()=>singleExpression// singleExpression is implicitly returned. There is no need for the braces or the return keywordfn=singleParam=>{// if the arrow function has only one parameter, there's no need for parentheses// statements}fn=(x,y)=>{// if the arrow function has zero or multiple parameters, one needs to use parentheses// statements}

CFML supports any statements within the function's definition, not simply expressions.

CFML supports recursive anonymous functions:

factorial=function(n){returnn>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 is

return_typedelegate(arguments){/*body*/}

If unambiguous, the return type and the keyword delegate can be omitted.

(x){returnx*x;}delegate(x){returnx*x;}// if more verbosity is needed(intx){returnx*x;}// if parameter type cannot be inferreddelegate(intx){returnx*x;}// dittodelegatedouble(intx){returnx*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;(intx)=>x*x;(x,y)=>x*y;(intx,inty)=>x*y;

An anonymous function can be assigned to a variable and used like this:

autosqr=(doublex){returnx*x;};doubley=sqr(4);

Dart

Dart supports anonymous functions. [8]

varsqr=(x)=>x*x;print(sqr(5));

or

print(((x)=>x*x)(5));

Delphi

Delphi introduced anonymous functions in version 2009.

programdemo;typeTSimpleProcedure=referencetoprocedure;TSimpleFunction=referencetofunction(constx:string):Integer;varx1:TSimpleProcedure;y1:TSimpleFunction;beginx1:=procedurebeginWriteln('Hello World');end;x1;//invoke anonymous method just definedy1:=function(constx:string):IntegerbeginResult:=Length(x);end;Writeln(y1('bar'));end.

PascalABC.NET

PascalABC.NET supports anonymous functions using lambda syntax

beginvarn:=10000000;varpp:=(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. [9]

sum=fn(a,b)->a+bendsum.(4,3)#=> 7square=fn(x)->x*xendEnum.map[1,2,3,4],square#=> [1, 4, 9, 16]

Erlang

Erlang uses a syntax for anonymous functions similar to that of named functions. [10]

% Anonymous function bound to the Square variableSquare=fun(X)->X*Xend.% Named function with the same functionalitysquare(X)->X*X.

Go

Go supports anonymous functions. [11]

foo:=func(xint)int{returnx*x}fmt.Println(foo(10))

Haskell

Haskell 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)[1..5]-- returns [1, 4, 9, 16, 25]

The following are all equivalent:

fxy=x+yfx=\y->x+yf=\xy->x+y

Haxe

In Haxe, anonymous functions are called lambda, and use the syntax function(argument-list) expression; .

varf=function(x)returnx*x;f(8);// 64(function(x,y)returnx+y)(5,6);// 11

Java

Java supports anonymous functions, named Lambda Expressions, starting with JDK 8. [12]

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. [13]

// 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(longid,Stringname)->"id: "+id+", name:"+name// with a code block(a,b)->{returna+b;}// with multiple statements in the lambda body. It needs a code block.// This example also includes two nested lambda expressions (the first one is also a closure).(id,defaultPrice)->{Optional<Product>product=productList.stream().filter(p->p.getId()==id).findFirst();returnproduct.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), [13] as in the following example:

publicclassCalculator{interfaceIntegerMath{intoperation(inta,intb);defaultIntegerMathswap(){return(a,b)->operation(b,a);}}privatestaticintapply(inta,intb,IntegerMathop){returnop.operation(a,b);}publicstaticvoidmain(String...args){IntegerMathaddition=(a,b)->a+b;IntegerMathsubtraction=(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.

IntBinaryOperatorsum=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 compared to Anonymous Classes

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:

IntegerMathanonymousClass=newIntegerMath(){@Overridepublicintoperation(inta,intb){returna+b;}};IntegerMathlambdaExpression=(a,b)->a+b;

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. [14] 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, [15] 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){returnx*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.

varf=function(){document.title=location.href;};f();

Use void() to avoid new pages for arbitrary anonymous functions:

void(function(){returndocument.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(){returnfunction(){return...{returnfunction(){stuff}()}...}()}())

Note the implications of the anonymous function in the JavaScript fragments that follow:

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},

valsum={x:Int,y:Int->x+y}sum(5,6)// returns 11valeven={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)(*argarg))

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-somethingarg)))

"function" can be abbreviated as #'. Also, macro lambda exists, which expands into a function form:

; using sharp quote#'(lambda(arg)(do-somethingarg)); using the lambda macro:(lambda(arg)(do-somethingarg))

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)(*xx))'(1234)); -> (1 4 9 16)

The lambda form in Common Lisp allows a lambda expression to be written in a function call:

((lambda(xy)(+(sqrtx)(sqrty)))10.012.0)

Anonymous functions in Common Lisp can also later be given global names:

(setf(symbol-function'sqr)(lambda(x)(*xx))); which allows us to call it using the name SQR:(sqr10.0)

Scheme

Scheme's named functions is simply syntactic sugar for anonymous functions bound to names:

(define(somenamearg)(do-somethingarg))

expands (and is equivalent) to

(definesomename(lambda(arg)(do-somethingarg)))

Clojure

Clojure supports anonymous functions through the "fn" special form:

(fn [x](+ x3))

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[arg](+ 3arg))

expands to:

(def func(fn [arg](+ 3arg)))

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. [16]

Thus, in Lua

functionfoo(x)return2*xend

is just syntactical sugar for

foo=function(x)return2*xend

An example of using anonymous functions for reverse-order sorting:

table.sort(network,function(a,b)returna.name>b.nameend)

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:

If[#1==1,1,#1*#0[#1-1]]&

For example, 6 factorial would be:

If[#1==1,1,#1*#0[#1-1]]&[6]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 Octaveans=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:

funx->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. [17]

F#

F# supports anonymous functions, [18] as follows:

(funx->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. [19]

varanon=proc(var1,var2:int):int=var1+var2assertanon(1,2)==3

Multi-line example:

varanon=func(x:int):bool=ifx>0:result=trueelse:result=falseassertanon(9)

Anonymous functions may be passed as input parameters of other functions:

varcities=@["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, [20] as follows:

(sub{print"I got called\n"})->();# 1. fully anonymous, called as createdmy$squarer=sub{my$x=shift;$x*$x};# 2. assigned to a variablesubcurry{my($sub,@args)=@_;returnsub{$sub->(@args,@_)};# 3. as a return value of another function}# example of currying in Perl programmingsubsum{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{printfor@_}1..10;# values not passed like normal Perl function

PHP

Before 4.0.1, PHP had no anonymous function support. [21]

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. [22]

$x=3;$func=function($z){return$z*2;};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){$x*=2;};$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 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]>>(Yis2*X), [1,2,3], Ys). Ys= [2,4,6] yes 

Currying is also supported. The above example can be written as:

| ?- meta::map([X]>>([Y]>>(Yis2*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. [23] 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:

clausesmkAdder(X)={(Y)=X+Y}.

Python

Python supports simple anonymous functions through the lambda form. [24] 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=lambdax:x*x>>> foo(10)100

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:

>>> defmake_pow(n):... deffixed_exponent_pow(x):... returnpow(x,n)... returnfixed_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 , which has shorthand since version 4.1.0 \, akin to Haskell.

> f<-function(x)x*x;f(8)[1] 64> (function(x,y)x+y)(5,6)[1] 11> # Since R 4.1.0> (\(x,y)x+y)(5,6)[1] 11

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
    { say"I got called" }; 
  2. assigned to a variable
    my$squarer1 = -> $x { $x * $x };             # 2a. pointy blockmy$squarer2 = { $^x * $^x };                 # 2b. twigilmy$squarer3 = { my$x = shift@_; $x * $x }; # 2c. Perl 5 style
  3. currying
    subadd ($m, $n) { $m + $n } my$seven   = add(3, 4); my$add_one = &add.assuming(m => 1);my $eight   =$add_one($seven); 
  4. WhateverCode object
    my$w = * - 1;       # WhateverCode objectmy$b = { $_ - 1 };  # 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. Procs behave similarly to closures, whereas lambdas behave more analogous to an anonymous function. [25] When passed to a method, a block is converted into a Proc in some circumstances.

# Example 1:# Purely anonymous functions using blocks.ex=[16.2,24.1,48.3,32.4,8.5]=>[16.2,24.1,48.3,32.4,8.5]ex.sort_by{|x|x-x.to_i}# Sort by fractional part, ignoring integer part.=>[24.1,16.2,48.3,32.4,8.5]# Example 2:# First-class functions as an explicit object of Proc -ex=Proc.new{puts"Hello, world!"}=>#<Proc:0x007ff4598705a0@(irb):7>ex.callHello,world!=>nil# Example 3:# Function that returns lambda function object with parametersdefmultiple_of?(n)lambda{|x|x%n==0}end=>nilmultiple_four=multiple_of?(4)=>#<Proc:0x007ff458b45f88@(irb):12 (lambda)>multiple_four.call(16)=>truemultiple_four[15]=>false

Rust

In Rust, anonymous functions are called closures. [26] They are defined using the following syntax:

|<parameter-name>: <type>|-> <return-type>{<body>};

For example:

letf=|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:

letf=|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:

letf=|x|x*2;

Closures with no input parameter are written like so:

letf=||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`.fnapply(f: fn(i32)-> i32)-> i32{// No semicolon, to indicate an implicit returnf(5)}fnmain(){// Defining the closureletf=|x|x*2;println!("{}",apply(f));// 10println!("{}",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: [27]

With these traits, the compiler will capture variables in the least restrictive manner possible. [27] 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. [28]

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`.fnapply_by_ref<F>(f: F)-> i32whereF: Fn(i32)-> i32{f(5)}fnmain(){letf=|x|{println!("I got the value: {}",x);x*2};// Applies the function before printing its return valueprintln!("5 * 2 = {}",apply_by_ref(f));}// ~~ Program output ~~// I got the value: 5// 5 * 2 = 10

The previous function definition can also be shortened for convenience as follows:

fnapply_by_ref(f: implFn(i32)-> i32)-> i32{f(5)}

Scala

In Scala, anonymous functions use the following syntax: [29]

(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.

vallist=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].fvalue:8.64st> [:x:y|x+y] value:5value:6.11

Smalltalk 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.aBlockClosure"returns the inner block, which adds 100 (captured in "a" variable) to its argument."st>fvalue:1.101st>fvalue:2.102

Swift

In Swift, anonymous functions are called closures. [30] The syntax has following form:

{(parameters)->returnTypeinstatement}

For example:

{(s1:String,s2:String)->Boolinreturns1>s2}

For sake of brevity and expressiveness, the parameter types and return type can be omitted if these can be inferred:

{s1,s2inreturns1>s2}

Similarly, Swift also supports implicit return statements for one-statement closures:

{s1,s2ins1>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: [31]

apply{x{expr{$x*$x}}}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 {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. [32]

delegateintIntOp(intx,inty);voidmain(){IntOpfoo=(x,y)=>x*y;stdout.printf("%d\n",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.

Dimfoo=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.

DimtAsNewSystem.Threading.Thread(Sub()FornAsInteger=0To10'Count to 10Console.WriteLine(n)'Print each numberNextEndSub)t.Start()

Related Research Articles

In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

In mathematics and computer science, a higher-order function (HOF) is a function that does at least one of the following:

In computer programming, a default argument is an argument to a function that a programmer is not required to specify. In most programming languages, functions may take one or more arguments. Usually, each argument must be specified in full. Later languages allow the programmer to specify default arguments that always have a value, even if one is not specified when calling the function.

In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax. In some languages, particularly C++, function objects are often called functors.

A function pointer, also called a subroutine pointer or procedure pointer, is a pointer referencing executable code, rather than data. Dereferencing the function pointer yields the referenced function, which can be invoked and passed arguments just as in a normal function call. Such an invocation is also known as an "indirect" call, because the function is being invoked indirectly through a variable instead of directly through a fixed identifier or address.

In computer programming, the ternary conditional operator is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, conditional expression, ternary if, or inline if. An expression if a then b else c or a ? b : c evaluates to b if the value of a is true, and otherwise to c. One can read it aloud as "if a then b otherwise c". The form a ? b : c is the most common, but alternative syntax do exist; for example, Raku uses the syntax a ?? b !! c to avoid confusion with the infix operators ? and !, whereas in Visual Basic .NET, it instead takes the form If(a, b, c).

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 other functions, and assigning them to variables or storing them in data structures. Some programming language theorists require support for anonymous functions as well. In languages with first-class functions, the names of functions do not have any special status; they are treated like ordinary variables with a function type. The term was coined by Christopher Strachey in the context of "functions as first-class citizens" in the mid-1960s.

In computer programming, a nested function is a named function that is defined within another, enclosing, block and is lexically scoped within the enclosing block – meaning it is only callable by name within the body of the enclosing block and can use identifiers declared in outer blocks, including outer functions. The enclosing block is typically, but not always, another function.

In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages.

In computer science, function composition is an act or mechanism to combine simple functions to build more complicated ones. Like the usual composition of functions in mathematics, the result of each function is passed as the argument of the next, and the result of the last one is the result of the whole.

typedef is a reserved keyword in the programming languages C, C++, and Objective-C. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type. As such, it is often used to simplify the syntax of declaring complex data structures consisting of struct and union types, although it is also commonly used to provide specific descriptive type names for integer data types of varying sizes.

C++11 is a version of a joint technical standard, ISO/IEC 14882, by the International Organization for Standardization (ISO) and International Electrotechnical Commission (IEC), for the C++ programming language. C++11 replaced the prior version of the C++ standard, named C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by the publication year of the specification, though it was formerly named C++0x because it was expected to be published before 2010.

In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.

In computing, compile-time function execution is the ability of a compiler, that would normally compile a function to machine code and execute it at run time, to execute the function at compile time. This is possible if the arguments to the function are known at compile time, and the function does not make any reference to or attempt to modify any global state.

In mathematics and computer science, apply is a function that applies a function to arguments. It is central to programming languages derived from lambda calculus, such as LISP and Scheme, and also in functional languages. It has a role in the study of the denotational semantics of computer programs, because it is a continuous function on complete partial orders. Apply is also a continuous function in homotopy theory, and, indeed underpins the entire theory: it allows a homotopy deformation to be viewed as a continuous path in the space of functions. Likewise, valid mutations (refactorings) of computer programs can be seen as those that are "continuous" in the Scott topology.

The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.

In computer programming, variadic templates are templates that take a variable number of arguments.

In the context of the programming language C++, functional refers to a header file that is part of the C++ Standard Library and provides a set of predefined class templates for function objects, including operations for arithmetic, comparisons, and logic. Instances of these class templates are C++ classes that define a function call operator, and the instances of these classes can be called as if they were functions. It is possible to perform very sophisticated operations without writing a new function object, simply by combining predefined function objects and function object adaptors.

In computer programming, ellipsis notation is used to denote ranges, an unspecified number of arguments, or a parent directory. Most programming languages require the ellipsis to be written as a series of periods; a single (Unicode) ellipsis character cannot be used.

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 August 18, 2014. C++14 was published as ISO/IEC 14882:2014 in December 2014.

References

  1. "Statement Exprs (Using the GNU Compiler Collection (GCC))". gcc.gnu.org. Retrieved 2022-01-12.
  2. "Language Specification for Blocks — Clang 13 documentation". clang.llvm.org. Retrieved 2022-01-14.
  3. "Lambda expressions (since C++11) - cppreference.com". en.cppreference.com. Retrieved 2022-01-14.
  4. Järvi, Jaakko; Powell, Gary (n.d.). "Chapter 16. Boost.Lambda". Boost Documentation. Boost. Retrieved December 22, 2014.
  5. 1 2 3 4 5 6 7 Skeet, Jon (23 March 2019). C# in Depth. Manning. ISBN   978-1617294532.
  6. 1 2 Albahari, Joseph (2022). C# 10 in a Nutshell. O'Reilly. ISBN   978-1-098-12195-2.
  7. "C# Language Specification 5.0". Microsoft Download Center.
  8. "A tour of the Dart language". dart.dev. Retrieved 2020-11-24.
  9. "Erlang/Elixir Syntax: A Crash Course". elixir-lang.github.com. Retrieved 2020-11-24.
  10. "Erlang -- Funs". erlang.org. Retrieved 2020-11-24.
  11. "Anonymous Functions in GoLang". GoLang Docs. 9 January 2020. Retrieved 2020-11-24.
  12. "What's New in JDK 8".
  13. 1 2 The Java Tutorials: Lambda Expressions, docs.oracle.com
  14. "Chapter 15. Expressions". docs.oracle.com.
  15. "jdk/LambdaMethod.java". GitHub .
  16. "Programming in Lua - More about Functions". Archived from the original on 14 May 2008. Retrieved 2008-04-25.
  17. "2.7. Anonymous Functions · GitBook". www.cs.cornell.edu.
  18. cartermp. "Lambda Expressions: The fun Keyword - F#". docs.microsoft.com. Retrieved 2020-11-24.
  19. "Nim Manual". nim-lang.github.io.
  20. "perlsub - Perl subroutines - Perldoc Browser". perldoc.perl.org. Retrieved 2020-11-24.
  21. http://php.net/create_function the top of the page indicates this with "(PHP 4 >= 4.0.1, PHP 5)"
  22. "PHP: rfc:closures". wiki.php.net.
  23. "Anonymous Predicates". in Visual Prolog Language Reference
  24. "6. Expressions — Python 3.9.0 documentation". docs.python.org. Retrieved 2020-11-24.
  25. 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.
  26. "Closures - Rust By Example". doc.rust-lang.org.
  27. 1 2 "As input parameters - Rust By Example". doc.rust-lang.org.
  28. "Lifetimes - Rust By Example". doc.rust-lang.org.
  29. "Anonymous Function Syntax - Scala Documentation". Archived from the original on 2013-07-23. Retrieved 2010-12-31.
  30. "Closures — The Swift Programming Language (Swift 5.5)". docs.swift.org.
  31. apply manual page, retrieved 2012-09-06.
  32. Vala Reference Manual, retrieved 2021-06-09.