In computer programming, an anonymous function (function literal, 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. [1] 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. [2] 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.
The names "lambda abstraction", "lambda function", and "lambda expression" refer to the notation of function abstraction in lambda calculus, where the usual function f(x) = M would be written (λx.M), and where M is an expression that uses x. Compare to the Python syntax of lambdax:M
.
The name "arrow function" refers to the mathematical "maps to" symbol, x ↦ M. Compare to the JavaScript syntax of x=>M
. [3]
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. Anonymous functions often provide a briefer notation than defining named functions. In languages that do not permit the definition of named functions in local scopes, anonymous functions may provide encapsulation via localized scope, however the code in the body of such anonymous function may not be re-usable, or amenable to separate testing. Short/simple anonymous functions used in expressions may be easier to read and understand than separately defined named functions, though without a descriptive name they may be more difficult to understand.
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 in a Dynamic programming language, more readable, and less error-prone than calling a named function.
The following examples are written in Python 3.
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=lambdax:len(x))>>>a['car','bike','house']
The anonymous function in this example is the lambda expression:
lambdax: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
lambdaarg1,arg2,arg3,...:<operationontheargumentsreturningavalue>
The expression returned by the lambda function can be assigned to a variable and used in the code at multiple places.
>>>add=lambdaa:a+a>>>add(20)40
Another 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=lambdax: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 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.
defcomp(threshold):returnlambdax: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))TrueTrueFalseFalse>>>print(func_b(5),func_b(8),func_b(13),func_b(21))TrueTrueTrueFalse
It would be impractical to create a function for every possible comparison function and may be too inconvenient to keep the threshold around for further use. Regardless of the reason why a closure is used, the anonymous function is the entity that contains the functionality that does the comparing.
Currying 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.
>>>defdivide(x,y):...returnx/y>>>defdivisor(d):...returnlambdax:divide(x,d)>>>half=divisor(2)>>>third=divisor(3)>>>print(half(32),third(32))16.010.666666666666666>>>print(half(40),third(40))20.013.333333333333334
While the use of anonymous functions is perhaps not common with currying, it still can be used. In the above example, the function divisor generates functions with a specified divisor. The functions half and third curry the divide function with a fixed divisor.
The divisor function also forms a closure by binding the variable d
.
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.
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(lambdax: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*xforxina][1,4,9,16,25,36]
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(lambdax: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]>>>[xforxinaifx%2==0][2,4,6]
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:
>>>fromfunctoolsimportreduce>>>a=[1,2,3,4,5]>>>reduce(lambdax,y:x*y,a)120
This performs
The anonymous function here is the multiplication of the two arguments.
The result of a fold need not be one value. Instead, both map and filter can be created using fold. In map, the value that is accumulated is a new list, containing the results of applying a function to each element of the original list. In filter, the value that is accumulated is a new list containing only those elements that match the given condition.
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.
Language | Support | Notes |
---|---|---|
ActionScript | ||
Ada | Expression functions are a part of Ada2012, access-to-subprogram [4] | |
ALGOL 68 | ||
APL | Dyalog, ngn and dzaima APL fully support both dfns and tacit functions. GNU APL has rather limited support for dfns. | |
Assembly languages | ||
AHK | Since AutoHotkey V2 anonymous functions are supported with a syntax similar to JavaScript. | |
Bash | A library has been made to support anonymous functions in Bash. [5] | |
C | Support is provided in Clang and along with the LLVM compiler-rt lib. GCC support is given for a macro implementation which enables the possibility of use. See below for more details. | |
C# | [6] | |
C++ | As of the C++11 standard | |
CFML | As of Railo 4, [7] ColdFusion 10 [8] | |
Clojure | [9] | |
COBOL | Micro Focus's non-standard Managed COBOL dialect supports lambdas, which are called anonymous delegates/methods. [10] | |
Curl | ||
D | [11] | |
Dart | [12] | |
Delphi | [13] | |
Dylan | [14] | |
Eiffel | ||
Elm | [15] | |
Elixir | [16] | |
Erlang | [17] | |
F# | [18] | |
Excel | Excel worksheet function, 2021 beta release [19] | |
Factor | "Quotations" support this [20] | |
Fortran | ||
Frink | [21] | |
Go | [22] | |
Gosu | [23] | |
Groovy | [24] | |
Haskell | [25] | |
Haxe | [26] | |
Java | Supported in Java 8. See the Java limitations section below for details. | |
JavaScript | [27] | |
Julia | [28] | |
Kotlin | [29] | |
Lisp | ||
Logtalk | ||
Lua | [30] | |
MUMPS | ||
Maple | [31] | |
MATLAB | [32] | |
Maxima | [33] | |
Nim | [34] | |
OCaml | [35] | |
Octave | [36] | |
Object Pascal | Delphi, a dialect of Object Pascal, supports anonymous functions (formally, anonymous methods) natively since Delphi 2009. The Oxygene Object Pascal dialect also supports them. | |
Objective-C (Mac OS X 10.6+) | Called blocks; in addition to Objective-C, blocks can also be used on C and C++ when programming on Apple's platform. | |
OpenSCAD | Function Literal support was introduced with version 2021.01. [37] | |
Pascal | ||
Perl | [38] | |
PHP | As of PHP 5.3.0, true anonymous functions are supported. [39] Formerly, only partial anonymous functions were supported, which worked much like C#'s implementation. | |
PL/I | ||
Python | Python supports anonymous functions through the lambda syntax, [40] which supports only expressions, not statements. | |
R | ||
Racket | [41] | |
Raku | [42] | |
Rexx | ||
RPG | ||
Ruby | Ruby's anonymous functions, inherited from Smalltalk, are called blocks. [43] | |
Rust | [44] | |
Scala | [45] | |
Scheme | ||
Smalltalk | Smalltalk's anonymous functions are called blocks. | |
Standard ML | [46] | |
Swift | Swift's anonymous functions are called Closures. [47] | |
TypeScript | [48] | |
Typst | [49] | |
Tcl | [50] | |
Vala | [50] | |
Visual Basic .NET v9 | [51] | |
Visual Prolog v 7.2 | [52] | |
Wolfram Language | [53] | |
Zig | [54] |
In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that map values to other values, rather than a sequence of imperative statements which update the running state of the program.
In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed and which also avoids repeated evaluations.
Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation.
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 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.
In computer programming, a callback is a function that is stored as data and designed to be called by another function – often back to the original abstraction layer.
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 computing, the modulo operation returns the remainder or signed remainder of a division, after one number is divided by another, called the modulus of the operation.
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.
Scala is a strong statically typed high-level general-purpose programming language that supports both object-oriented programming and functional programming. Designed to be concise, many of Scala's design decisions are intended to address criticisms of Java.
The syntax of the Python programming language is the set of rules that defines how a Python program will be written and interpreted. The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages. It supports multiple programming paradigms, including structured, object-oriented programming, and functional programming, and boasts a dynamic type system and automatic memory management.
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.
In computer science, partial application refers to the process of fixing a number of arguments of a function, producing another function of smaller arity. Given a function , we might fix the first argument, producing a function of type . Evaluation of this function might be represented as . Note that the result of partial function application in this case is a function that takes two arguments. Partial application is sometimes incorrectly called currying, which is a related, but distinct concept.
Lisp Flavored Erlang (LFE) is a functional, concurrent, garbage collected, general-purpose programming language and Lisp dialect built on Core Erlang and the Erlang virtual machine (BEAM). LFE builds on Erlang to provide a Lisp syntax for writing distributed, fault-tolerant, soft real-time, non-stop applications. LFE also extends Erlang to support metaprogramming with Lisp macros and an improved developer experience with a feature-rich read–eval–print loop (REPL). LFE is actively supported on all recent releases of Erlang; the oldest version of Erlang supported is R14.
Swift is a high-level general-purpose, multi-paradigm, compiled programming language created by Chris Lattner in 2010 for Apple Inc. and maintained by the open-source community. Swift compiles to machine code and uses an LLVM-based compiler. Swift was first released in June 2014 and the Swift toolchain has shipped in Xcode since version 6, released in 2014.
Nim is a general-purpose, multi-paradigm, statically typed, compiled high-level system programming language, designed and developed by a team around Andreas Rumpf. Nim is designed to be "efficient, expressive, and elegant", supporting metaprogramming, functional, message passing, procedural, and object-oriented programming styles by providing several features such as compile time code generation, algebraic data types, a foreign function interface (FFI) with C, C++, Objective-C, and JavaScript, and supporting compiling to those same languages as intermediate representations.
A callable object, in computer programming, is any object that can be called like a function.
The Lambda calculus ... was introduced by Alonzo Church in the 1930s as a precise notation for a theory of anonymous functions
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.