Anonymous method
   HOME

TheInfoList



OR:

In
computer programming Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, an anonymous function (function literal, expression or block) is a function definition that is not bound to an
identifier An identifier is a name that identifies (that is, labels the identity of) either a unique object or a unique ''class'' of objects, where the "object" or class may be an idea, person, physical countable object (or class thereof), or physical mass ...
. Anonymous functions are often arguments being passed to
higher-order function In mathematics and computer science, a higher-order function (HOF) is a function that does at least one of the following: * takes one or more functions as arguments (i.e. a procedural parameter, which is a parameter of a procedure that is itself ...
s 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 function In computer science, a programming language is said to have first-class functions if it treats function (programming), functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning ...
s, where they fulfil the same role for the function type as literals do for other
data type In computer science and computer programming, a data type (or simply type) is a collection or grouping of data values, usually specified by a set of possible values, a set of allowed operations on these values, and/or a representation of these ...
s. Anonymous functions originate in the work of
Alonzo Church Alonzo Church (June 14, 1903 – August 11, 1995) was an American computer scientist, mathematician, logician, and philosopher who made major contributions to mathematical logic and the foundations of theoretical computer science. He is bes ...
in his invention of the
lambda calculus In mathematical logic, the lambda calculus (also written as ''λ''-calculus) is a formal system for expressing computability, computation based on function Abstraction (computer science), abstraction and function application, application using var ...
, in which all functions are anonymous, in 1936, before electronic computers. 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 language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s since
Lisp Lisp (historically LISP, an abbreviation of "list processing") is a family of programming languages with a long history and a distinctive, fully parenthesized Polish notation#Explanation, prefix notation. Originally specified in the late 1950s, ...
in 1958, and a growing number of modern programming languages support anonymous functions.


Names

The names "lambda abstraction", "lambda function", and "lambda expression" refer to the notation of function abstraction in lambda calculus, where the usual function would be written , and where is an expression that uses . Compare to the Python syntax of lambda x: M. The name "arrow function" refers to the mathematical "
maps to The maps to symbol, ↦, is a rightward arrow protruding from a vertical bar. It is used in mathematics and in computer science to denote functions. In Z notation, a specification language used in software development, this symbol is called ...
" symbol, . Compare to the JavaScript syntax of x => M.


Uses

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 In mathematics and computer science, currying is the technique of translating a function that takes multiple arguments into a sequence of families of functions, each taking a single argument. In the prototypical example, one begins with a functi ...
. 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 A dynamic programming language is a type of programming language that allows various operations to be determined and executed at runtime. This is different from the compilation phase. Key decisions about variables, method calls, or data types are ...
, more readable, and less error-prone than calling a 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) 40 Another example would be sorting items in a list by the name of their class (in Python, everything has a class): >>> a = 0, 'number', 11.2>>> a.sort(key=lambda x: x.__class__.__name__) >>> a 1.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 variable In mathematics, and in other disciplines involving formal languages, including mathematical logic and computer science, a variable may be said to be either free or bound. Some older books use the terms real variable and apparent variable for f ...
s. 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 False 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

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


Higher-order functions

A
higher-order function In mathematics and computer science, a higher-order function (HOF) is a function that does at least one of the following: * takes one or more functions as arguments (i.e. a procedural parameter, which is a parameter of a procedure that is itself ...
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
square In geometry, a square is a regular polygon, regular quadrilateral. It has four straight sides of equal length and four equal angles. Squares are special cases of rectangles, which have four equal angles, and of rhombuses, which have four equal si ...
s every element in an array with an anonymous function. >>> a = , 2, 3, 4, 5, 6>>> list(map(lambda x: x * x, a)) , 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 = , 2, 3, 4, 5, 6>>> * x for x in a , 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 = , 2, 3, 4, 5, 6>>> list(filter(lambda x: x % 2

0, a))
, 4, 6 The comma is a punctuation mark that appears in several variants in different languages. Some typefaces render it as a small line, slightly curved or straight, but inclined from the vertical; others give it the appearance of a miniature fille ...
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 = , 2, 3, 4, 5, 6>>> for x in a if x % 2

0
, 4, 6 The comma is a punctuation mark that appears in several variants in different languages. Some typefaces render it as a small line, slightly curved or straight, but inclined from the vertical; others give it the appearance of a miniature fille ...


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 = , 2, 3, 4, 5>>> reduce(lambda x, y: x * y, a) 120 This 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 language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s 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 Object Pascal is an extension to the programming language Pascal (programming language), Pascal that provides object-oriented programming (OOP) features such as Class (computer programming), classes and Method (computer programming), methods. T ...
) are all
statically typed In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a ''type'' (for example, integer, floating point, string) to every '' term'' (a word, phrase, or other set of symbols). Usu ...
languages. However, statically typed languages can support anonymous functions. For example, the ML languages are statically typed and fundamentally include anonymous functions, and
Delphi Delphi (; ), in legend previously called Pytho (Πυθώ), was an ancient sacred precinct and the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient Classical antiquity, classical world. The A ...
, a dialect of
Object Pascal Object Pascal is an extension to the programming language Pascal (programming language), Pascal that provides object-oriented programming (OOP) features such as Class (computer programming), classes and Method (computer programming), methods. T ...
, has been extended to support anonymous functions, as has C++ (by the
C++11 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 vers ...
standard). Second, the languages that treat functions as
first-class function In computer science, a programming language is said to have first-class functions if it treats function (programming), functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning ...
s ( Dylan,
Haskell Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
,
JavaScript JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior. Web browsers have ...
,
Lisp Lisp (historically LISP, an abbreviation of "list processing") is a family of programming languages with a long history and a distinctive, fully parenthesized Polish notation#Explanation, prefix notation. Originally specified in the late 1950s, ...
, ML,
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
, Python,
Ruby Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
, Scheme) generally have anonymous function support so that functions can be defined and passed around as easily as other data types.


Examples of anonymous functions


See also

*
First-class function In computer science, a programming language is said to have first-class functions if it treats function (programming), functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning ...
* Lambda calculus definition


References


External links


Anonymous Methods - When Should They Be Used?
(blog about anonymous function in Delphi)
Compiling Lambda Expressions: Scala vs. Java 8

php anonymous functions
php anonymous functions
Lambda functions in various programming languages
* {{DEFAULTSORT:Anonymous Function Data types Functional programming Lambda calculus Subroutines Articles with example code Articles with example C code Articles with example C++ code Articles with example C Sharp code Articles with example D code Articles with example Java code Articles with example JavaScript code Articles with example Julia code Articles with example Lisp (programming language) code Articles with example MATLAB/Octave code Articles with example PHP code Articles with example Python (programming language) code Articles with example R code Articles with example Ruby code Articles with example Scala code Articles with example Smalltalk code Articles with example Tcl code