Anonymous function

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.

Names

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 lambda x: M.

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

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, ...: <operation on the arguments returning a value>

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

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

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

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

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

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

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 also

References

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

Read other articles:

Kamen Rider ReviceGenreTokusatsuFiksi pahlawan superFiksi ilmiahDramaKomediBerdasarkankonsep Kamen Rideroleh Shotaro IshinomoriPengembangIshimori ProductionsToei CompanyDitulis olehHanta KinoshitaSutradaraTakayuki ShibasakiPemeranKentaro MaedaWataru HyugaAyaka ImotoNoritaka HamaoYui AsakuraHayata SekiKurodo HachijoinJunya KomatsuKazuya TanabeKurara EmiShigeyuki TotsugiPengisi suaraSubaru KimuraMiku ItōKenjiro TsudaShinshu FujiKazuhiko InoueLagu pembukaliveDevil oleh Da-ice feat. Subaru Kimu...

 

Cipta Hunai adalah seorang birokrat Indonesia. Ia menjabat sebagai pelaksana jabatan bupati Gayo Lues dari 3 Maret sampai 25 September 2012. Ia meninggal dunia pada 1 Februari 2023.[1] Referensi ^ Innalillahi, Mantan Pj Bupati Gayo Lues Drs Cipta Hunai Meninggal Dunia di Banda Aceh. Tribungayo.com.  Artikel bertopik biografi Indonesia ini adalah sebuah rintisan. Anda dapat membantu Wikipedia dengan mengembangkannya.lbs

 

Kurva bicorn Dalam geometri, bicorn adalah sebuah kurva kuartik rasional yang didefinisikan dengan persamaan[1] y 2 ( a 2 − x 2 ) = ( x 2 + 2 a y − a 2 ) 2 . {\displaystyle y^{2}(a^{2}-x^{2})=(x^{2}+2ay-a^{2})^{2}.} Kurva ini mempunyai dua taring dalam simetrik mengenai sumbu- y {\displaystyle y} .[2] Kurva bicorn dikenal sebagai kurva topi berbentuk segitiga lantaran mempunyai kemiripannya dengan topi bicorne. Sejarah Pada tahun 1864, James Joseph Sylvester memp...

  لمعانٍ أخرى، طالع بولدر (توضيح). بولدر     الإحداثيات 40°01′10″N 105°17′34″W / 40.019444444444°N 105.29277777778°W / 40.019444444444; -105.29277777778  [1] تاريخ التأسيس 1858  تقسيم إداري  البلد الولايات المتحدة[2][3]  التقسيم الأعلى مقاطعة بولدر  عاصمة لـ مقاطعة بول�...

 

1952 natural disaster in the county of Devon, England The Lynmouth flood disaster Meteorological historyDurationNight of 15 and 16 August 1952Overall effectsFatalities34DamageSubstantialAreas affectedLynmouth, Simonsbath, Filleigh, Middleham (never rebuilt), Devon The Lynmouth Flood occurred on the night of the 15–16 August 1952, principally affecting the village of Lynmouth, in North Devon. A storm with heavy rainfall, combined with already saturated soil and flood debris, led to the flood...

 

保良局馬錦明夫人章馥仙中學Po Leung Kuk Mrs.Ma-Cheung Fook Sien College翻漆後的校舍東北面(2022年3月)地址 香港新界離島區大嶼山東涌富東邨类型津貼中學宗教背景無隶属保良局创办日期1997年学区香港離島區東涌校長柯玉琼女士副校长鄭健華先生,劉俊偉先生助理校长梁煥儀女士职员人数56人年级中一至中六学生人数約700人,24個班別校訓愛、敬、勤、誠校歌保良局屬下校歌�...

この記事は検証可能な参考文献や出典が全く示されていないか、不十分です。出典を追加して記事の信頼性向上にご協力ください。(このテンプレートの使い方)出典検索?: コルク – ニュース · 書籍 · スカラー · CiNii · J-STAGE · NDL · dlib.jp · ジャパンサーチ · TWL(2017年4月) コルクを打ち抜いて作った瓶の栓 コルク(木栓、�...

 

Genus of fishes ScorpaenaTemporal range: Middle Eocene–recent PreꞒ Ꞓ O S D C P T J K Pg N [1] Scorpaena porcus Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Chordata Class: Actinopterygii Order: Scorpaeniformes Family: Scorpaenidae Tribe: Scorpaenini Genus: ScorpaenaLinnaeus, 1758 Type species Scorpaena porcusLinnaeus, 1758[2] Synonyms[2] Holoscorpaena Fowler, 1944 Kantapus J. L. B. Smith, 1947 Osorioia Fowler, 1938 Ruboralga Whitley, 1931...

 

Local board of Auckland Council in New ZealandWaitākere Ranges Local BoardLocal board of Auckland CouncilCountryNew ZealandRegionAucklandTerritorial authorityAuckland CouncilWardWaitākere WardLegislated2010Government • Board chairGreg PreslandArea[1] • Land305.73 km2 (118.04 sq mi)Population (June 2023)[2] • Total55,600 Local Board Members[3]StructureFuture West4 / 6WestWards/WestWards-Independent2 / 6Elections...

En este artículo se detectaron varios problemas. Por favor, edítalo y/o discute los problemas en la discusión para mejorarlo: No tiene una redacción neutral. Por favor, modifica los párrafos o secciones que muestran un punto de vista parcial en concordancia con lo esperado en una enciclopedia. Carece de fuentes o referencias que aparezcan en una fuente acreditada. Este aviso fue puesto el 17 de diciembre de 2009. Para otros usos de este término, véase Gobierno Mundial (desambigua...

 

Cistercian monastery in Cumbria, UK Holme Cultram AbbeyHolmcultram Abbey 2017Monastery informationFull nameHolmcultram AbbeyOrderCistercianEstablished1150Disestablished1538Diocese CarlisleSiteLocationAbbeytown, CumbriaVisible remainsNave; now a parish churchPublic accessYes Holmcultram Abbey (alternatively Holm Cultram Abbey or Holme Cultram Abbey) was a Cistercian monastery in what is now the village of Abbeytown in Cumbria, United Kingdom. Founded in 1150, the abbey was suppressed in 1538 d...

 

County in Florida, United States County in FloridaMartin CountyCountyMartin County Courthouse SealLocation within the U.S. state of FloridaFlorida's location within the U.S.Coordinates: 27°05′N 80°24′W / 27.08°N 80.4°W / 27.08; -80.4Country United StatesState FloridaFoundedMay 30, 1925Named forJohn W. MartinSeatStuartLargest communityPalm CityArea • Total753 sq mi (1,950 km2) • Land543 sq mi (1,410 ...

1547–1721 Russian state Tsardom of RussiaРусское царствоRusskoye tsarstvo1547–1721 Flag(1693–1721) Coat of arms(1667–1721) Seal of Tsar Ivan IV (c. 1539):Territory of Russia in     1500      1600 and      1700CapitalMoscow(1547–1712)Saint Petersburg(1712–1721)Common languagesRussian (official)Religion Russian Orthodox (official)[1]Demonym(s)RussianGovernmentAbsolute monarchyTsar&#...

 

Humanistik adalah salah satu pendekatan atau aliran dari psikologi yang menekankan kehendak bebas, pertumbuhan pribadi, kegembiraan, kemampuan untuk pulih kembali setelah mengalami ketidakbahagiaan, serta keberhasilan dalam merealisasikan potensi manusia.[1] Tujuan humanistik adalah membantu manusia mengekspresikan dirinya secara kreatif dan merealisasikan potensinya secara utuh.[1] Salah satu pencetus psikologi humanistik adalah Abraham Maslow.[2] Sejarah Humanistik a...

 

White Hart LaneThe Lane Informasi stadionNama lengkapWhite Hart LaneLokasiLokasi748 High Rd, TottenhamLondon N17 0AP InggrisKoordinat51°36′12″N 0°03′57″W / 51.60333°N 0.06583°W / 51.60333; -0.06583Koordinat: 51°36′12″N 0°03′57″W / 51.60333°N 0.06583°W / 51.60333; -0.06583KonstruksiDibuat1899Dibuka4 September 1899Ditutup14 Mei 2017Biaya pembuatan£100,050 (1934)ArsitekArchibald Leitch (1909)Data teknisPermukaanRumputK...

Connecticut gubernatorial election 1797 Connecticut gubernatorial election ← 1796 13 April 1797 1798 →   Nominee Oliver Wolcott Party Federalist Popular vote 1 Percentage 100.00% Governor before election Oliver Wolcott Federalist Elected Governor Oliver Wolcott Federalist Elections in Connecticut Federal government U.S President 1788–89 1792 1796 1800 1804 1808 1812 1816 1820 1824 1828 1832 1836 1840 1844 1848 1852 1856 1860 1864 1868 1872 1876 1880 1884 1888...

 

9.4–9.6 magnitude earthquake in Chile 1960 Valdivia earthquakeCollapsed buildings in ValdiviaIquiqueSantiagoTemucoPunta ArenasUTC time1960-05-22 19:11:14ISC event879136USGS-ANSSComCatLocal date22 May 1960 (1960-05-22)Local time15:11:14Duration10 minutesMagnitude9.4–9.6 Mw[1]Depth33 km (21 mi)Epicenter38°14′S 73°03′W / 38.24°S 73.05°W / -38.24; -73.05TypeMegathrustAreas affectedChile, Pacific RimMax. inten...

 

9th Boat RaceDate29 March 1849 (1849-03-29)WinnerCambridgeMargin of victoryEasilyWinning time22 minutes 0 secondsOverall record (Cambridge–Oxford)7–2UmpireJ. C. Fellowes ← 1846 1849 (December) → Oxford versus Cambridge rowing race The 9th Boat Race took place on the River Thames on 29 March 1849. Typically held annually, the event is a side-by-side rowing race between crews from the Universities of Oxford and Cambridge. The race was won by Cambridge who tri...

Dalam artikel ini, nama keluarganya adalah Zhang. Zhang Ming'enLahir06 Mei 1995 (umur 29)Heilongjiang, TiongkokKebangsaanTiongkokAlmamaterCentral Academy of DramaPekerjaanPemeranTahun aktif2010–sekarangAgenZhang Ming'en Studio (dibawah Linghe Culture 灵河文化) Zhang Ming'en Hanzi sederhana: 张铭恩 Alih aksara Zhang Ming'en (lahir 6 Mei 1995) adalah seorang pemeran asal Tiongkok. Ia merupakan lulusan dari Departemen Akting dari Central Academy of Drama pada 2013. Ia debu...

 

Tô Xuân BốnChức vụPhó Tổng cục trưởng Tổng cục Cảnh sát Thi hành án hình sự và Hỗ trợ Tư pháp, Bộ Công an (Việt Nam)Nhiệm kỳtháng 2 năm 2015 – tháng 8 năm 2018Tổng cục trưởngNguyễn Ngọc Bằng Cục trưởng Chính trị, Tổng cục VIII, Bộ Công anNhiệm kỳ – 2014 Thông tin cá nhânSinh1 tháng 3, 1959 (65 tuổi)Nghề nghiệpsĩ quan công anĐảng chính trịĐảng Cộng sản V...