Anonymous functions can encapsulate functionality that does not require naming and is intended for short-term or localized 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 lacking a
descriptive name may reduce code readability. 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.
Sorting Many languages provide a
generic function that
sorts a list (or array) of objects into an
order determined by a comparison function which compares two objects to determine if they are equal or if one is greater or less than the other. Using an anonymous comparison function expression passed as an argument to a generic sort function is often more concise than creating a named comparison function. Consider this Python code sorting a list of strings by length of the string: a: list[str] = ["house", "car", "bike"] a.sort(key = lambda x: len(x)) print(a) • prints ['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. from typing import Callable add: Callableint], int] = lambda a: a + a print(add(20)) • prints 40 Another example would be sorting items in a list by the name of their class (in Python, everything has a class): a: list[int | str] = [10, "number", 11.2] a.sort(key=lambda x: x.__class__.__name__) print(a) • prints [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" within an anonymous function that compares input values to this threshold. def comp(threshold: int) -> Callableint], bool]: return lambda x: x This can be used as a sort of generator of comparison functions: func_a: Callableint], bool] = comp(10) func_b: Callableint], bool] = comp(20) print(func_a(5), func_a(8), func_a(13), func_a(21)) • prints True True False False print(func_b(5), func_b(8), func_b(13), func_b(21)) • prints 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 transforms a function that takes multiple arguments into a sequence of functions each accepting a single argument. 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: int, y: int) -> float: return x / y def divisor(d: int) -> Callableint], float]: return lambda x: divide(x, d) half: Callableint], float] = divisor(2) third: Callableint], float] = divisor(3) print(half(32), third(32)) • prints 16.0 10.666666666666666 print(half(40), third(40)) • prints 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 is a function that takes a function as an argument or returns one as a result. This technique is frequently employed to tailor the behavior of a generically defined function, such as a loop or recursion pattern. 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: List[int] = [1, 2, 3, 4, 5, 6] print(list(map(lambda x: x * x, a))) • prints [1, 4, 9, 16, 25, 36] The anonymous function takes an argument and returns its square. 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: List[int] = [1, 2, 3, 4, 5, 6] print([x * x for x in a]) • prints [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: List[int] = [1, 2, 3, 4, 5, 6] print(list(filter(lambda x: x % 2 == 0, a))) • prints [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: List[int] = [1, 2, 3, 4, 5, 6] print([x for x in a if x % 2 == 0]) • prints [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: a: List[int] = [1, 2, 3, 4, 5] print(functools.reduce(lambda x, y: x * y, a)) • prints 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. A fold does not necessarily produce a single scalar value; it can also generate structured results such as lists. 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==