Transforming a function in such a way that it only takes a single argument
This article is about the mathematical technique. For the cooking process of this name, see Curry. For the leather finishing process, see Currier. For horse grooming, see Currycomb.
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 function that takes two arguments, one from and one from and produces objects in The curried form of this function treats the first argument as a parameter, so as to create a family of functions The family is arranged so that for each object in there is exactly one function
In this example, itself becomes a function, that takes as an argument, and returns a function that maps each to The proper notation for expressing this is verbose. The function belongs to the set of functions Meanwhile, belongs to the set of functions Thus, something that maps to will be of the type With this notation, is a function that takes objects from the first set, and returns objects in the second set, and so one writes This is a somewhat informal example; more precise definitions of what is meant by "object" and "function" are given below. These definitions vary from context to context, and take different forms, depending on the theory that one is working in.
Currying is related to, but not the same as, partial application.[1][2] The example above can be used to illustrate partial application; it is quite similar. Partial application is the function that takes the pair and together as arguments, and returns Using the same notation as above, partial application has the signature Written this way, application can be seen to be adjoint to currying.
The currying of a function with more than two arguments can be defined by induction.
Currying is useful in both practical and theoretical settings. In functional programminglanguages, and many others, it provides a way of automatically managing how arguments are passed to functions and exceptions. In theoretical computer science, it provides a way to study functions with multiple arguments in simpler theoretical models which provide only one argument. The most general setting for the strict notion of currying and uncurrying is in the closed monoidal categories, which underpins a vast generalization of the Curry–Howard correspondence of proofs and programs to a correspondence with many other structures, including quantum mechanics, cobordisms and string theory.[3]
Uncurrying is the dual transformation to currying, and can be seen as a form of defunctionalization. It takes a function whose return value is another function , and yields a new function that takes as parameters the arguments for both and , and returns, as a result, the application of and subsequently, , to those arguments. The process can be iterated.
Motivation
Currying provides a way for working with functions that take multiple arguments, and using them in frameworks where functions might take only one argument. For example, some analytical techniques can only be applied to functions with a single argument. Practical functions frequently take more arguments than this. Frege showed that it was sufficient to provide solutions for the single argument case, as it was possible to transform a function with multiple arguments into a chain of single-argument functions instead. This transformation is the process now known as currying.[14] All "ordinary" functions that might typically be encountered in mathematical analysis or in computer programming can be curried. However, there are categories in which currying is not possible; the most general categories which allow currying are the closed monoidal categories.
Some programming languages almost always use curried functions to achieve multiple arguments; notable examples are ML and Haskell, where in both cases all functions have exactly one argument. This property is inherited from lambda calculus, where multi-argument functions are usually represented in curried form.
Currying is related to, but not the same as partial application.[1][2] In practice, the programming technique of closures can be used to perform partial application and a kind of currying, by hiding arguments in an environment that travels with the curried function.
History
The "Curry" in "Currying" is a reference to logician Haskell Curry, who used the concept extensively, but Moses Schönfinkel had the idea six years before Curry.[10] The alternative name "Schönfinkelisation" has been proposed.[15] In the mathematical context, the principle can be traced back to work in 1893 by Frege.[4][5]
The originator of the word "currying" is not clear. David Turner says the word was coined by Christopher Strachey in his 1967 lecture notes Fundamental Concepts in Programming Languages,[16] but that source introduces the concept as "a device originated by Schönfinkel", and the term "currying" is not used, while Curry is mentioned later in the context of higher-order functions.[7]John C. Reynolds defined "currying" in a 1972 paper, but did not claim to have coined the term.[8]
Definition
Currying is most easily understood by starting with an informal definition, which can then be molded to fit many different domains. First, there is some notation to be established. The notation denotes all functions from to . If is such a function, we write . Let denote the ordered pairs of the elements of and respectively, that is, the Cartesian product of and . Here, and may be sets, or they may be types, or they may be other kinds of objects, as explored below.
Given a function
,
currying constructs a new function
.
That is, takes an argument of type and returns a function of type . It is defined by
for of type and of type . We then also write
Uncurrying is the reverse transformation, and is most easily understood in terms of its right adjoint, the function
Set theory
In set theory, the notation is used to denote the set of functions from the set to the set . Currying is the natural bijection between the set of functions from to , and the set of functions from to the set of functions from to . In symbols:
Indeed, it is this natural bijection that justifies the exponential notation for the set of functions. As is the case in all instances of currying, the formula above describes an adjoint pair of functors: for every fixed set , the functor is left adjoint to the functor .
One useful corollary is that a function is continuous if and only if its curried form is continuous. Another important result is that the application map, usually called "evaluation" in this context, is continuous (note that eval is a strictly different concept in computer science.) That is,
is continuous when is compact-open and locally compact Hausdorff.[21] These two results are central for establishing the continuity of homotopy, i.e. when is the unit interval , so that can be thought of as either a homotopy of two functions from to , or, equivalently, a single (continuous) path in .
where is the set of homotopy classes of maps , and is the suspension of A, and is the loop space of A. In essence, the suspension can be seen as the cartesian product of with the unit interval, modulo an equivalence relation to turn the interval into a loop. The curried form then maps the space to the space of functions from loops into , that is, from into .[21] Then is the adjoint functor that maps suspensions to loop spaces, and uncurrying is the dual.[21]
The notion of continuity makes its appearance in homotopy type theory, where, roughly speaking, two computer programs can be considered to be homotopic, i.e. compute the same results, if they can be "continuously" refactored from one to the other.
Lambda calculi
In theoretical computer science, currying provides a way to study functions with multiple arguments in very simple theoretical models, such as the lambda calculus, in which functions only take a single argument. Consider a function taking two arguments, and having the type , which should be understood to mean that x must have the type , y must have the type , and the function itself returns the type . The curried form of f is defined as
where is the abstractor of lambda calculus. Since curry takes, as input, functions with the type , one concludes that the type of curry itself is
That is, the parenthesis are not required to disambiguate the order of the application.
Curried functions may be used in any programming language that supports closures; however, uncurried functions are generally preferred for efficiency reasons, since the overhead of partial application and closure creation can then be avoided for most function calls.
Type theory
In type theory, the general idea of a type system in computer science is formalized into a specific algebra of types. For example, when writing , the intent is that and are types, while the arrow is a type constructor, specifically, the function type or arrow type. Similarly, the Cartesian product of types is constructed by the product type constructor .
The type-theoretical approach is expressed in programming languages such as ML and the languages derived from and inspired by it: Caml, Haskell, and F#.
The type-theoretical approach provides a natural complement to the language of category theory, as discussed below. This is because categories, and specifically, monoidal categories, have an internal language, with simply-typed lambda calculus being the most prominent example of such a language. It is important in this context, because it can be built from a single type constructor, the arrow type. Currying then endows the language with a natural product type. The correspondence between objects in categories and types then allows programming languages to be re-interpreted as logics (via Curry–Howard correspondence), and as other types of mathematical systems, as explored further, below.
Logic
Under the Curry–Howard correspondence, the existence of currying and uncurrying is equivalent to the logical theorem (also known as exportation), as tuples (product type) corresponds to conjunction in logic, and function type corresponds to implication.
Here, Hom denotes the (external) Hom-functor of all morphisms in the category, while denotes the internal hom functor in the closed monoidal category. For the category of sets, the two are the same. When the product is the cartesian product, then the internal hom becomes the exponential object .
Currying can break down in one of two ways. One is if a category is not closed, and thus lacks an internal hom functor (possibly because there is more than one choice for such a functor). Another way is if it is not monoidal, and thus lacks a product (that is, lacks a way of writing down pairs of objects). Categories that do have both products and internal homs are exactly the closed monoidal categories.
The setting of cartesian closed categories is sufficient for the discussion of classical logic; the more general setting of closed monoidal categories is suitable for quantum computation.[24]
Currying and partial function application are often conflated.[1][2] One of the significant differences between the two is that a call to a partially applied function returns the result right away, not another function down the currying chain; this distinction can be illustrated clearly for functions whose arity is greater than two.[25]
Given a function of type , currying produces . That is, while an evaluation of the first function might be represented as , evaluation of the curried function would be represented as , applying each argument in turn to a single-argument function returned by the previous invocation. Note that after calling , we are left with a function that takes a single argument and returns another function, not a function that takes two arguments.
In contrast, partial function application refers to the process of fixing a number of arguments to a function, producing another function of smaller arity. Given the definition of above, we might fix (or 'bind') the first argument, producing a function of type . Evaluation of this function might be represented as . Note that the result of partial function application in this case is a function that takes two arguments.
Intuitively, partial function application says "if you fix the first argument of the function, you get a function of the remaining arguments". For example, if function div stands for the division operation x/y, then div with the parameter x fixed at 1 (i.e., div 1) is another function: the same as the function inv that returns the multiplicative inverse of its argument, defined by inv(y) = 1/y.
The practical motivation for partial application is that very often the functions obtained by supplying some but not all of the arguments to a function are useful; for example, many languages have a function or operator similar to plus_one. Partial application makes it easy to define these functions, for example by creating a function that represents the addition operator with 1 bound as its first argument.
Partial application can be seen as evaluating a curried function at a fixed point, e.g. given and then or simply where curries f's first parameter.
Thus, partial application is reduced to a curried function at a fixed point. Further, a curried function at a fixed point is (trivially), a partial application. For further evidence, note that, given any function , a function may be defined such that . Thus, any partial application may be reduced to a single curry operation. As such, curry is more suitably defined as an operation which, in many theoretical cases, is often applied recursively, but which is theoretically indistinguishable (when considered as an operation) from a partial application.
So, a partial application can be defined as the objective result of a single application of the curry operator on some ordering of the inputs of some function.
^ abFrege, Gottlob (1893). "§ 36". Grundgesetze der arithmetik (in German). Book from the collections of University of Wisconsin - Madison, digitized by Google on 26 August 2008. Jena: Hermann Pohle. pp. 54–55.
^ abcQuine, W. V. (1967). "Introduction to Moses Schönfinkel's 1924 "On the building blocks of mathematical logic"". In van Heijenoort, Jean (ed.). From Frege to Gödel: A Source Book in Mathematical Logic, 1879-1931. Harvard University Press. pp. 355–357. ISBN9780674324497.
^ abcCurry, Haskell B. (1980). Barwise, Jon; Keisler, H. Jerome; Kunen, Kenneth (eds.). "Some Philosophical Aspects of Combinatory Logic". The Kleene Symposium: Proceedings of the Symposium Held June 18-24, 1978 at Madison, Wisconsin, U.S.A. (Studies in Logic and the Foundations of Mathematics). Studies in Logic and the Foundations of Mathematics. 101. North-Holland Publishing Company, imprint of Elsevier: 85–101. doi:10.1016/S0049-237X(08)71254-0. ISBN9780444853455. ISSN0049-237X. S2CID117179133. Some contemporary logicians call this way of looking at a function "currying", because I made extensive use of it; but Schönfinkel had the idea some 6 years before I did.
^Barendregt, Hendrik Pieter (1984). "Theorems 1.2.13, 1.2.14". The lambda calculus: its syntax and semantics. Studies in logic and the foundations of mathematics. Vol. 103 (Rev. ed.). North-Holland, an imprint of Elsevier. ISBN978-0-444-87508-2.
Liga 3 Banten 2021Liga 3 MS Glow For Men 2021Negara IndonesiaTanggal penyelenggaraan30 Oktober–1 Desember 2021Tempat penyelenggaraan2 stadionJumlah peserta22 tim sepak bolaJuara bertahanPersikota TangerangJuaraPersikota Tangerang(gelar ke-3)Tempat keduaFarmel FCTempat ketigaSerpong City FCTempat keempatMatrix Putra Brother's FCKualifikasi untukLiga 3 2021 Putaran Nasional← 2019 2022 → Seluruh statistik akurat per 1 Desember 2021. Liga 3 Banten 2021 atau Liga 3 MS Glow For Men PSSI ...
Rangkong Rangkong Papan Klasifikasi ilmiah Kerajaan: Animalia Filum: Chordata Kelas: Aves Ordo: Bucerotiformes Famili: 'BucerotidaeRafinesque, 1815 Genus: 13 genus Lihat teks Spesies: 59 spesies Lihat teks Distribusi burung rangkong Rangkong Sulawesi (Rhyticeros cassidix) di Cagar Alam Gunung Tangkoko Batuangus, Sulawesi Utara. Rangkong, Enggang, Julang, Kangkareng (bahasa Inggris: Hornbill) adalah sejenis burung yang mempunyai paruh berbentuk tanduk sapi tetapi tanpa lingkaran. Biasanya par...
Untuk kegunaan lain, lihat Saturnus (disambiguasi). Saturnus Saturnus dalam warna alaminya saat ekuinoks, diabadikan oleh Cassini pada Juli 2008; titik di sudut kiri bawah adalah TitanPenamaanAsal namaSaturnusNama alternatifZohal (زحل)Ciri-ciri orbit[2]Epos J2000,0Aphelion1.514,50 juta km(10,832 sa)Perihelion1.352,55 juta km(9,0412 sa)Sumbu semimayor1.433,53 juta km(9,5826 sa)Eksentrisitas0,0565Periode orbit 29,4571 tahun 10.759,22 hari 24.49...
Gambar lintasan Grand Prix Sepeda Motor Ceko (Inggris Czech Republic motorcycle Grand Prix) adalah acara balap motor yang menjadi bagian dari Grand Prix Sepeda Motor. Sebelum tahun 1993, balapan ini dikenal dengan nama Czechoslovakian motorcycle Grand Prix. Sejak tahun 1963 menjadi bagian dari MotoGP (antara tahun 1982 dan 1987 lomba hanya diadakan seri European Grand Prix). Kombinasi sirkuit Masaryk (Sirkuit Brno) antara 1930 dan sekarang Sejak tahun 1987 lomba dilangsungkan di sirkuit baru ...
Pour les articles homonymes, voir Lady (homonymie). Cet article est une ébauche concernant la société et le Royaume-Uni. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. La Jeune Reine Victoria, Franz Xaver Winterhalter, 1842, Osborne House, Île de Wight. Lady est un titre emprunté de l'anglais signifiant littéralement « Dame »[Note 1]. Significations Le sens du mot peut varier selon le contexte...
Passo del San BernardinoPasso del San BernardinoStato Svizzera Regione Grigioni Località collegateMesoccoNufenen Altitudine2 065 m s.l.m. Coordinate46°29′45.24″N 9°10′14.16″E / 46.4959°N 9.1706°E46.4959; 9.1706Coordinate: 46°29′45.24″N 9°10′14.16″E / 46.4959°N 9.1706°E46.4959; 9.1706 Altri nomi e significatiSan-Bernardino-Pass (DE) InfrastrutturaStrada asfaltata Pendenza massima10% Lunghezza60 km Chiusura i...
Linux distribution Gentoo LinuxGentoo LogoGentoo Linux Live USB running KDEDeveloperGentoo FoundationWritten inC, sh, and PythonOS familyLinux (Unix-like)Working stateCurrentSource modelOpen sourceInitial release31 March 2002; 22 years ago (2002-03-31)[1][2]Repositorygitweb.gentoo.org/repo/gentoo.git Update methodRolling releasePackage managerPortagePlatformsIA-32, x86-64, IA-64, PA-RISC (HPPA), PowerPC 32/64, SPARC 64-bit, DEC Alpha, ARM 32/64, MIPSKernel ty...
Joseph SifakisJoseph Sifakis en 2008.FonctionDirecteur de recherche au CNRSBiographieNaissance 26 décembre 1946 (77 ans)HéraklionNom dans la langue maternelle Ιωσήφ ΣηφάκηςNationalités grecquefrançaiseFormation Université polytechnique nationale d'AthènesActivités Informaticien, ingénieur, chercheurAutres informationsA travaillé pour Centre national de la recherche scientifiqueÉcole polytechnique fédérale de LausanneMembre de Academia Europaea (2008)Académie amé...
دوري إستونيا الممتاز 2005 تفاصيل الموسم دوري إستونيا الممتاز النسخة 15 البلد إستونيا التاريخ بداية:6 مارس 2005 نهاية:6 نوفمبر 2005 المنظم اتحاد إستونيا لكرة القدم مباريات ملعوبة 180 عدد المشاركين 10 أهداف مسجلة 669 دوري إستونيا الممتاز 2004 دوري إستون...
Operación al-Anfal Conflicto kurdo-iraquí y la Guerra Irán-IrakParte de conflicto kurdo-iraquí Tumbas familiares de las víctimas del ataque químico de 1988 en Halabja, en el Kurdistán iraquí.Fecha 1986-1989(En sentido estricto del 23 de febrero al 6 de septiembre de 1988)Lugar Norte de IrakCasus belli Insurgencia kurda en el norte de Irak y apoyo de esta etnia a IránResultado Insurgencia debilitada pero no sofocada Destrucción de 4 500 aldeas y masacre de población civilBelige...
Former flying squadron of the Royal Air Force No. 293 Squadron RAFActive28 Nov 1943 – 5 Apr 1946Country United KingdomBranch Royal Air ForceRoleair-sea rescuePart ofMediterranean Air Command[1]Motto(s)Latin: Ex aere salus(Translation: Safety from the air)[2]InsigniaSquadron Badge heraldryOver waves of the sea, a dexter hand couped at the wrist in bend sinister[2]Squadron CodesZE (Nov 1943 - Apr 1946)[3][4]Military unit No. 293 Squadron was a Roya...
Nicolás MaduroMaduro pada tahun 2013 Presiden VenezuelaPetahanaMulai menjabat 19 April 2013Penjabat: 5 Maret 2013 – 19 April 2013Wakil PresidenJorge Arreaza (2013–16) Aristóbulo Istúriz (sejak 2016)PendahuluHugo ChávezPenggantiPetahanaSeekretaris Jenderal Gerakan Non-BlokMasa jabatan17 September 2016 – 2019PendahuluHassan RouhaniPenggantiilham aliyevPresiden pro tempore Uni Negara Amerika SelatanPetahanaMulai menjabat 23 April 2016PendahuluTabaré VázquezPenggantiP...
This article's lead section may be too short to adequately summarize the key points. Please consider expanding the lead to provide an accessible overview of all important aspects of the article. (January 2022) Motor vehicle Daihatsu Zebra2005 Daihatsu Zebra ZL9 (S91, Indonesia)OverviewManufacturerDaihatsuProductionAugust 1986 – October 2007Body and chassisClassLight commercial vehicleBody style2-door pickup4 or 5-door vanLayoutFront mid-engine, rear-wheel-driveRelatedDaihatsu HijetChro...
Disambiguazione – Felice I rimanda qui. Se stai cercando l'omonimo vescovo franco, vedi Felice I di Metz. Papa Felice I26º papa della Chiesa cattolicaElezione5 gennaio 269 Fine pontificato30 dicembre 274 Predecessorepapa Dionisio Successorepapa Eutichiano NascitaRoma, ? MorteRoma, 30 dicembre 274 SepolturaCatacombe di San Callisto Manuale San Felice I Papa NascitaRoma, ? MorteRoma, 30 dicembre 274 Venerato daChiesa cattolica Santuario principaleCatacombe...
Two propositions or events that cannot both be true This article is about logical exclusivity of events and propositions. For the concept in concurrent computing, see Mutual exclusion. For the concept in developmental psychology, see Mutual exclusivity (psychology). This article includes a list of general references, but it lacks sufficient corresponding inline citations. Please help to improve this article by introducing more precise citations. (October 2009) (Learn how and when to remove th...
Финал Гран-при по фигурному катанию 2011-2012 Тип соревнования Международный турнир под эгидой ИСУ Дата 8 декабря— 11 декабря 2011 года Сезон 2011—2012 Место проведения Квебек Арена Pavillon de la Jeunesse Соревнования Предыдущее Финал Гран-при 2010—2011 Последующее Финал Гран-при 2012—2013 Финал ...