Movatterモバイル変換


[0]ホーム

URL:


Wikipedia

Anonymous function

Incomputer programming, ananonymous function (function literal,expression orblock) is afunction definition that is notbound to anidentifier. Anonymous functions are often arguments being passed tohigher-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 infunctional programming languages and other languages withfirst-class functions, where they fulfil the same role for thefunction type asliterals do for otherdata types.

Anonymous functions originate in the work ofAlonzo Church in his invention of thelambda calculus, in which all functions are anonymous, in 1936, before electronic computers.[2] In several programming languages, anonymous functions are introduced using the keywordlambda, and anonymous functions are often referred to as lambdas or lambda abstractions. Anonymous functions have been a feature ofprogramming languages sinceLisp in 1958, and a growing number of modern programming languages support anonymous functions.

Names

edit

The names "lambda abstraction", "lambda function", and "lambda expression" refer to the notation of function abstraction in lambda calculus, where the usual functionf(x) =M would be writtenx.M), and whereM is an expression that usesx. Compare to the Python syntax oflambdax:M.

The name "arrow function" refers to the mathematical "maps to" symbol,xM. Compare to the JavaScript syntax ofx=>M.[3]

Uses

edit
This sectiondoes notcite anysources. Please helpimprove this section byadding citations to reliable sources. Unsourced material may be challenged andremoved.(February 2018) (Learn how and when to remove this message)

Anonymous functions can be used for containing functionality that need not be named and possibly for short-term use. Some notable examples includeclosures andcurrying.

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 adescriptive 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 aDynamic programming language, more readable, and less error-prone than calling a named function.

The following examples are written in Python 3.

Sorting

edit

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 asort 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 thesort() 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 that11.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

edit

Closures are functions evaluated in an environment containingbound 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

edit
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 performsdivision 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 variabled.

Higher-order functions

edit

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

edit

The map function performs a function call on each element of a list. The following examplesquares 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]

Filter

edit

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]

Fold

edit

A fold function runs over all elements in a structure (for lists usually left-to-right, a "left fold", calledreduce 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

(((1×2)×3)×4)×5=120.{\displaystyle \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

edit

The following is a list ofprogramming 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 allstatically typed languages. However, statically typed languages can support anonymous functions. For example, theML languages are statically typed and fundamentally include anonymous functions, andDelphi, a dialect ofObject Pascal, has been extended to support anonymous functions, as hasC++ (by theC++11 standard). Second, the languages that treat functions asfirst-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.

This list isincomplete; you can help byadding missing items.(August 2008)
List of languages
LanguageSupportNotes
ActionScript Y
Ada YExpression functions are a part of Ada2012, access-to-subprogram[4]
ALGOL 68 Y
APL YDyalog, ngn and dzaima APL fully support both dfns and tacit functions. GNU APL has rather limited support for dfns.
Assembly languages N
AHK YSince AutoHotkey V2 anonymous functions are supported with a syntax similar to JavaScript.
Bash YA library has been made to support anonymous functions in Bash.[5]
C NSupport is provided inClang and along with theLLVM compiler-rt lib. GCC support is given for a macro implementation which enables the possibility of use. Seebelow for more details.
C# Y[6]
C++ YAs of theC++11 standard
CFML YAs ofRailo 4,[7]ColdFusion 10[8]
Clojure Y[9]
COBOL NMicro Focus's non-standard Managed COBOL dialect supports lambdas, which are called anonymous delegates/methods.[10]
Curl Y
D Y[11]
Dart Y[12]
Delphi Y[13]
Dylan Y[14]
Eiffel Y
Elm Y[15]
Elixir Y[16]
Erlang Y[17]
F# Y[18]
Excel YExcel worksheet function, 2021 beta release[19]
Factor Y"Quotations" support this[20]
Fortran N
Frink Y[21]
Go Y[22]
Gosu Y[23]
Groovy Y[24]
Haskell Y[25]
Haxe Y[26]
Java YSupported sinceJava 8.
JavaScript Y[27]
Julia Y[28]
Kotlin Y[29]
Lisp Y
Logtalk Y
Lua Y[30]
MUMPS N
Maple Y[31]
MATLAB Y[32]
Maxima Y[33]
Nim Y[34]
OCaml Y[35]
Octave Y[36]
Object Pascal YDelphi, a dialect of Object Pascal, supports anonymous functions (formally,anonymous methods) natively since Delphi 2009. TheOxygene Object Pascal dialect also supports them.
Objective-C (Mac OS X 10.6+) YCalledblocks; in addition to Objective-C, blocks can also be used on C and C++ when programming on Apple's platform.
OpenSCAD YFunction Literal support was introduced with version 2021.01.[37]
Pascal N
Perl Y[38]
PHP YAs 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 N
Python YPython supports anonymous functions through the lambda syntax,[40] which supports only expressions, not statements.
R Y
Racket Y[41]
Raku Y[42]
Rexx N
RPG N
Ruby YRuby's anonymous functions, inherited fromSmalltalk, are calledblocks.[43]
Rust Y[44]
Scala Y[45]
Scheme Y
Smalltalk YSmalltalk's anonymous functions are calledblocks.
Standard ML Y[46]
Swift YSwift's anonymous functions are called Closures.[47]
TypeScript Y[48]
Typst Y[49]
Tcl Y[50]
Vala Y[50]
Visual Basic .NET v9 Y[51]
Visual Prolog v 7.2 Y[52]
Wolfram Language Y[53]
Zig N[54]

Examples of anonymous functions

edit

See also

edit

References

edit
  1. ^"Higher order functions". learnyouahaskell.com. Retrieved3 December 2014.
  2. ^Fernandez, Maribel (2009),Models of Computation: An Introduction to Computability Theory, Undergraduate Topics in Computer Science, Springer Science & Business Media, p. 33,ISBN 9781848824348,The Lambda calculus ... was introduced by Alonzo Church in the 1930s as a precise notation for a theory of anonymous functions
  3. ^"Arrow function expressions - JavaScript".MDN. RetrievedAugust 21, 2019.
  4. ^"Access Types".www.adaic.org. Retrieved2024-06-27.
  5. ^"Bash lambda".GitHub. 2019-03-08.
  6. ^BillWagner."Lambda expressions - C# reference".docs.microsoft.com. Retrieved2020-11-24.
  7. ^"Closure support". Archived fromthe original on 2014-01-06. Retrieved2014-01-05.
  8. ^"Whats new in ColdFusion 10". Archived fromthe original on 2014-01-06. Retrieved2014-01-05.
  9. ^"Clojure - Higher Order Functions".clojure.org. Retrieved2022-01-14.
  10. ^"Managed COBOL Reference".Micro Focus Documentation.Micro Focus. Archived fromthe original on 25 February 2014. Retrieved25 February 2014.
  11. ^"Functions - D Programming Language".dlang.org. Retrieved2022-01-14.
  12. ^"A tour of the Dart language".dart.dev. Retrieved2020-11-24.
  13. ^"Anonymous Methods in Delphi - RAD Studio".docwiki.embarcadero.com. Retrieved2020-11-24.
  14. ^"Functions — Dylan Programming".opendylan.org. Retrieved2022-01-14.
  15. ^"docs/syntax".elm-lang.org. Retrieved2022-01-14.
  16. ^"Erlang/Elixir Syntax: A Crash Course".elixir-lang.github.com. Retrieved2020-11-24.
  17. ^"Erlang -- Funs".erlang.org. Retrieved2020-11-24.
  18. ^cartermp."Lambda Expressions: The fun Keyword - F#".docs.microsoft.com. Retrieved2020-11-24.
  19. ^"LAMBDA: The ultimate Excel worksheet function".microsoft.com. 25 January 2021. Retrieved2021-03-30.
  20. ^"Quotations - Factor Documentation". Retrieved26 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.
  21. ^"Frink".frinklang.org. Retrieved2020-11-24.
  22. ^"Anonymous Functions in GoLang".GoLang Docs. 9 January 2020. Retrieved2020-11-24.
  23. ^"Gosu Documentation"(PDF). Retrieved4 March 2013.
  24. ^"Groovy Documentation". Archived fromthe original on 22 May 2012. Retrieved29 May 2012.
  25. ^"Anonymous function - HaskellWiki".wiki.haskell.org. Retrieved2022-01-14.
  26. ^"Lambda".Haxe - The Cross-platform Toolkit. Retrieved2022-01-14.
  27. ^"Functions - JavaScript | MDN".developer.mozilla.org. Retrieved2022-01-14.
  28. ^"Functions · The Julia Language".docs.julialang.org. Retrieved2020-11-24.
  29. ^"Higher-Order Functions and Lambdas - Kotlin Programming Language".Kotlin. Retrieved2020-11-24.
  30. ^"Programming in Lua : 6".www.lua.org. Retrieved2020-11-24.
  31. ^"Maple Programming: 1.6: Anonymous functions and expressions - Application Center".www.maplesoft.com. Retrieved2020-11-24.
  32. ^"Anonymous Functions - MATLAB & Simulink".www.mathworks.com. Retrieved2022-01-14.
  33. ^"Maxima 5.17.1 Manual: 39. Function Definition".maths.cnam.fr. Retrieved2020-11-24.
  34. ^"Nim Manual".nim-lang.github.io.
  35. ^"Code Examples – OCaml".ocaml.org. Retrieved2020-11-24.
  36. ^"GNU Octave: Anonymous Functions".octave.org. Retrieved2020-11-24.
  37. ^"Function Literals".OpenSCAD User Manual. Wikibooks. Retrieved22 February 2021.
  38. ^"perlsub - Perl subroutines - Perldoc Browser".perldoc.perl.org. Retrieved2020-11-24.
  39. ^"PHP: Anonymous functions - Manual".www.php.net. Retrieved2020-11-24.
  40. ^"6. Expressions — Python 3.9.0 documentation".docs.python.org. Retrieved2020-11-24.
  41. ^"4.4 Functions: lambda".docs.racket-lang.org. Retrieved2020-11-24.
  42. ^"Functions".docs.raku.org. Retrieved2022-01-14.
  43. ^Sosinski, Robert (2008-12-21)."Understanding Ruby Blocks, Procs and Lambdas". Reactive.IO. Archived fromthe original on 2014-05-31. Retrieved2014-05-30.
  44. ^"Closures: Anonymous Functions that Can Capture Their Environment - The Rust Programming Language".doc.rust-lang.org. Retrieved2022-01-14.
  45. ^"Anonymous Functions".Scala Documentation. Retrieved2022-01-14.
  46. ^"Recitation 3: Higher order functions".www.cs.cornell.edu. Retrieved2022-01-14.
  47. ^"Closures — The Swift Programming Language (Swift 5.5)".docs.swift.org.
  48. ^"Documentation - Everyday Types".www.typescriptlang.org. Retrieved2022-01-14.
  49. ^"Function Type - Typst Documentation".typst.app. Retrieved2024-09-10.
  50. ^ab"Projects/Vala/Tutorial - GNOME Wiki!".wiki.gnome.org. Retrieved2020-11-24.
  51. ^KathleenDollard (15 September 2021)."Lambda Expressions - Visual Basic".docs.microsoft.com. Retrieved2022-01-14.
  52. ^"Language Reference/Terms/Anonymous Predicates - wiki.visual-prolog.com".wiki.visual-prolog.com. Retrieved2022-01-14.
  53. ^"Pure Anonymous Function: Elementary Introduction to the Wolfram Language".www.wolfram.com. Retrieved2022-01-14.
  54. ^"Lambdas, Closures and everything in between · Issue #1048 · ziglang/zig".GitHub. Retrieved2023-08-21.

External links

edit

[8]ページ先頭

©2009-2025 Movatter.jp