Anonymous function explained

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

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" symbol, . Compare to the JavaScript syntax of x => M.[2]

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.

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.

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 = [10, 'number', 11.2]>>> a.sort(key=lambda x: x.__class__.__name__)>>> a[11.2, 10, 'number']

Note that 11.2 has class name "float", 10 has class name "int", and 'number' has class name "str". The sorted order is "float", "int", then "str".

Closures

See main article: Closure (computer programming).

Closures are functions evaluated in an environment containing bound variables. The following example binds the variable "threshold" in an anonymous function that compares the input to the threshold.

def comp(threshold): return lambda x: x < threshold

This can be used as a sort of generator of comparison functions:

>>> func_a = comp(10)>>> func_b = comp(20)

>>> print(func_a(5), func_a(8), func_a(13), func_a(21))True True False False

>>> print(func_b(5), func_b(8), func_b(13), func_b(21))True True True 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

See main article: 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 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

See main article: Map (higher-order function).

The map function performs a function call on each element of a list. The following example squares every element in an array with an anonymous function.

>>> a = [1, 2, 3, 4, 5, 6]>>> list(map(lambda x: x*x, a))[1, 4, 9, 16, 25, 36]

The anonymous function accepts an argument and multiplies it by itself (squares it). The above form is discouraged by the creators of the language, who maintain that the form presented below has the same meaning and is more aligned with the philosophy of the language:

>>> a = [1, 2, 3, 4, 5, 6]>>> [x*x for x in a][1, 4, 9, 16, 25, 36]

Filter

See main article: Filter (higher-order function).

The filter function returns all elements from a list that evaluate True when passed to a certain function.

>>> a = [1, 2, 3, 4, 5, 6]>>> list(filter(lambda x: x % 2

0, a))[2, 4, 6]

The anonymous function checks if the argument passed to it is even. The same as with map, the form below is considered more appropriate:

>>> a = [1, 2, 3, 4, 5, 6]>>> [x for x in a if x % 2 == 0][2, 4, 6]

Fold

See main article: Fold (higher-order function).

A fold function runs over all elements in a structure (for lists usually left-to-right, a "left fold", called reduce in Python), accumulating a value as it goes. This can be used to combine all elements of a structure into one value, for example:

>>> from functools import reduce>>> a = [1, 2, 3, 4, 5]>>> reduce(lambda x,y: x*y, a)120

This performs

\left(\left(\left(1 x 2 \right) x 3 \right) x 4 \right) x 5 =120.

The anonymous function here is the multiplication of the two arguments.

The result of a fold need not be one value. Instead, both map and filter can be created using fold. In map, the value that is accumulated is a new list, containing the results of applying a function to each element of the original list. In filter, the value that is accumulated is a new list containing only those elements that match the given condition.

List of languages

The following is a list of programming languages that support unnamed anonymous functions fully, or partly as some variant, or not at all.

This table shows some general trends. First, the languages that do not support anonymous functions (C, Pascal, Object Pascal) are all statically typed languages. However, statically typed languages can support anonymous functions. For example, the ML languages are statically typed and fundamentally include anonymous functions, and Delphi, a dialect of Object Pascal, has been extended to support anonymous functions, as has C++ (by the C++11 standard). Second, the languages that treat functions as first-class functions (Dylan, Haskell, JavaScript, Lisp, ML, Perl, Python, Ruby, Scheme) generally have anonymous function support so that functions can be defined and passed around as easily as other data types.

Examples of anonymous functions

See main article: Examples of anonymous functions.

See also

External links

Notes and References

  1. Web site: Higher order functions . 3 December 2014 . learnyouahaskell.com . en-US.
  2. Web site: Arrow function expressions - JavaScript . August 21, 2019 . MDN . en-US.
  3. Web site: Access Types . 2024-06-27 . www.adaic.org.
  4. Web site: Bash lambda. GitHub. 2019-03-08.
  5. Web site: BillWagner. Lambda expressions - C# reference. 2020-11-24. docs.microsoft.com. en-us.
  6. Web site: Closure support. 2014-01-05. https://web.archive.org/web/20140106031957/http://www.getrailo.org/index.cfm/whats-up/railo-40-beta-released/features/closures/. 2014-01-06. dead.
  7. Web site: Whats new in ColdFusion 10. 2014-01-05. https://web.archive.org/web/20140106032853/https://learn.adobe.com/wiki/display/coldfusionen/Whats+new+in+ColdFusion+10. 2014-01-06. dead.
  8. Web site: Clojure - Higher Order Functions. 2022-01-14. clojure.org.
  9. Web site: Managed COBOL Reference . . Micro Focus Documentation . 25 February 2014 . https://archive.today/20140225190401/http://documentation.microfocus.com/help/topic/com.microfocus.eclipse.infocenter.visualcobol.vs/GUID-DA75663F-6357-4064-8112-C87E7457DE51.html . 25 February 2014.
  10. Web site: Functions - D Programming Language. 2022-01-14. dlang.org.
  11. Web site: A tour of the Dart language. 2020-11-24. dart.dev.
  12. Web site: Anonymous Methods in Delphi - RAD Studio. 2020-11-24. docwiki.embarcadero.com.
  13. Web site: Functions — Dylan Programming. 2022-01-14. opendylan.org.
  14. Web site: docs/syntax. 2022-01-14. elm-lang.org.
  15. Web site: Erlang/Elixir Syntax: A Crash Course. 2020-11-24. elixir-lang.github.com. en.
  16. Web site: Erlang -- Funs. 2020-11-24. erlang.org.
  17. Web site: cartermp. Lambda Expressions: The fun Keyword - F#. 2020-11-24. docs.microsoft.com. en-us.
  18. Web site: LAMBDA: The ultimate Excel worksheet function. 2021-03-30. microsoft.com. 25 January 2021. en-us.
  19. Web site: Quotations - Factor Documentation. 26 December 2015. A quotation is an anonymous function (a value denoting a snippet of code) which can be used as a value and called using the Fundamental combinators..
  20. Web site: Frink. 2020-11-24. frinklang.org.
  21. Web site: Anonymous Functions in GoLang. 2020-11-24. GoLang Docs. 9 January 2020 . en-US.
  22. Web site: Gosu Documentation. 4 March 2013.
  23. Web site: Groovy Documentation. 29 May 2012. https://web.archive.org/web/20120522213410/http://groovy.codehaus.org/Closures. 22 May 2012. dead.
  24. Web site: Anonymous function - HaskellWiki. 2022-01-14. wiki.haskell.org.
  25. Web site: Lambda. 2022-01-14. Haxe - The Cross-platform Toolkit.
  26. Web site: Functions - JavaScript MDN. 2022-01-14. developer.mozilla.org. en-US.
  27. Web site: Functions · The Julia Language. 2020-11-24. docs.julialang.org.
  28. Web site: Higher-Order Functions and Lambdas - Kotlin Programming Language. 2020-11-24. Kotlin. en.
  29. Web site: Programming in Lua : 6. 2020-11-24. www.lua.org.
  30. Web site: Maple Programming: 1.6: Anonymous functions and expressions - Application Center. 2020-11-24. www.maplesoft.com.
  31. Web site: Anonymous Functions - MATLAB & Simulink. 2022-01-14. www.mathworks.com.
  32. Web site: Maxima 5.17.1 Manual: 39. Function Definition. 2020-11-24. maths.cnam.fr.
  33. Web site: Nim Manual. nim-lang.github.io.
  34. Web site: Code Examples – OCaml. 2020-11-24. ocaml.org.
  35. Web site: GNU Octave: Anonymous Functions. 2020-11-24. octave.org.
  36. Web site: Function Literals . OpenSCAD User Manual . Wikibooks . 22 February 2021.
  37. Web site: perlsub - Perl subroutines - Perldoc Browser. 2020-11-24. perldoc.perl.org.
  38. Web site: PHP: Anonymous functions - Manual. 2020-11-24. www.php.net.
  39. Web site: 6. Expressions — Python 3.9.0 documentation. 2020-11-24. docs.python.org.
  40. Web site: 4.4 Functions: lambda. 2020-11-24. docs.racket-lang.org.
  41. Web site: Functions. 2022-01-14. docs.raku.org.
  42. Web site: Understanding Ruby Blocks, Procs and Lambdas . Sosinski . Robert . Reactive.IO . 2008-12-21 . 2014-05-30 . dead . https://web.archive.org/web/20140531123646/http://www.reactive.io/tips/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/ . 2014-05-31 .
  43. Web site: Closures: Anonymous Functions that Can Capture Their Environment - The Rust Programming Language. 2022-01-14. doc.rust-lang.org.
  44. Web site: Anonymous Functions. 2022-01-14. Scala Documentation.
  45. Web site: Recitation 3: Higher order functions. 2022-01-14. www.cs.cornell.edu.
  46. Web site: Closures — The Swift Programming Language (Swift 5.5). docs.swift.org.
  47. Web site: Documentation - Everyday Types. 2022-01-14. www.typescriptlang.org. en.
  48. Web site: Function Type - Typst Documentation. 2024-09-10. typst.app. en.
  49. Web site: Projects/Vala/Tutorial - GNOME Wiki!. 2020-11-24. wiki.gnome.org.
  50. Web site: KathleenDollard. Lambda Expressions - Visual Basic. 2022-01-14. docs.microsoft.com. 15 September 2021 . en-us.
  51. Web site: Language Reference/Terms/Anonymous Predicates - wiki.visual-prolog.com. 2022-01-14. wiki.visual-prolog.com.
  52. Web site: Pure Anonymous Function: Elementary Introduction to the Wolfram Language. 2022-01-14. www.wolfram.com. en.
  53. Web site: Lambdas, Closures and everything in between · Issue #1048 · ziglang/zig . 2023-08-21 . GitHub . en.