Inmathematics andcomputer science,currying is the technique of translating afunction that takes multiplearguments 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, such that for any in,.
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. Infunctional programminglanguages, and many others, it provides a way of automatically managing how arguments are passed to functions andexceptions. Intheoretical 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 theclosed monoidal categories, which underpins a vast generalization of theCurry–Howard correspondence of proofs and programs to a correspondence with many other structures, includingquantum mechanics,cobordisms, andstring theory.[3]
The concept of currying was introduced byGottlob Frege,[4][5] developed byMoses Schönfinkel,[6][5][7][8][9][10][11]and further developed byHaskell Curry.[8][10][12][13]
Uncurrying is thedual transformation to currying, and can be seen as a form ofdefunctionalization. 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.
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, someanalytical techniques can only be applied tofunctions 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 inmathematical analysis or incomputer programming can be curried. However, there are categories in which currying is not possible; the most general categories which allow currying are theclosed monoidal categories.
Someprogramming languages almost always use curried functions to achieve multiple arguments; notable examples areML andHaskell, where in both cases all functions have exactly one argument. This property is inherited fromlambda calculus, where multi-argument functions are usually represented in curried form.
Currying is related to, but not the same aspartial application.[1][2] In practice, the programming technique ofclosures can be used to perform partial application and a kind of currying, by hiding arguments in an environment that travels with the curried function.
The "Curry" in "Currying" is a reference to logicianHaskell Curry, who used the concept extensively, butMoses 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 byFrege.[4][5]
The originator of the word "currying" is not clear.David Turner says the word was coined byChristopher Strachey in his 1967 lecture notesFundamental 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]
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 allfunctions from to. If is such a function, we write. Let denote theordered pairs of the elements of and respectively, that is, theCartesian 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, thefunction
Inset theory, the notation is used to denote theset of functions from the set to the set. Currying is thenatural 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 theexponential notation for the set of functions. As is the case in all instances of currying, the formula above describes anadjoint pair of functors: for every fixed set, the functor is left adjoint to the functor.
In thecategory of sets, theobject is called theexponential object.
In the theory offunction spaces, such as infunctional analysis orhomotopy theory, one is commonly interested incontinuous functions betweentopological spaces. One writes (theHom functor) for the set ofall functions from to, and uses the notation to denote the subset of continuous functions. Here, is thebijection
while uncurrying is the inverse map. If the set of continuous functions from to is given thecompact-open topology, and if the space islocally compact Hausdorff, then
is ahomeomorphism. This is also the case when, and arecompactly generated,[17]: chapter 5 [18] although there are more cases.[19][20]
One useful corollary is that a function is continuousif and only if its curried form is continuous. Another important result is that theapplication map, usually called "evaluation" in this context, is continuous (note thateval 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 ofhomotopy, 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.
Inalgebraic topology, currying serves as an example ofEckmann–Hilton duality, and, as such, plays an important role in a variety of different settings. For example,loop space is adjoint toreduced suspensions; this is commonly written as
where is the set ofhomotopy classes of maps, and is thesuspension ofA, and is theloop space ofA. 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 theadjoint functor that maps suspensions to loop spaces, and uncurrying is the dual.[21]
The duality between themapping cone and the mapping fiber (cofibration andfibration)[17]: chapters 6,7 can be understood as a form of currying, which in turn leads to the duality of thelong exact and coexactPuppe sequences.
Inhomological algebra, the relationship between currying and uncurrying is known astensor-hom adjunction. Here, an interesting twist arises: theHom functor and thetensor product functor might notlift to anexact sequence; this leads to the definition of theExt functor and theTor functor.
Inorder theory, the theory oflattices ofpartially ordered sets, is acontinuous function when the lattice is given theScott topology.[22] Scott-continuous functions were first investigated in the attempt to provide a semantics forlambda calculus (as ordinary set theory is inadequate to do this). More generally, Scott-continuous functions are now studied indomain theory, which encompasses the study ofdenotational semantics of computer algorithms. Note that the Scott topology is quite different than many common topologies one might encounter in thecategory of topological spaces; the Scott topology is typicallyfiner, and is notsober.
The notion of continuity makes its appearance inhomotopy 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.
Intheoretical computer science, currying provides a way to study functions with multiple arguments in very simple theoretical models, such as thelambda 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 thatx must have the type,y must have the type, and the function itself returns the type. The curried form off 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
The → operator is often consideredright-associative, so the curried function type is often written as. Conversely,function application is considered to beleft-associative, so that is equivalent to
That is, the parenthesis are not required to disambiguate the order of the application.
Curried functions may be used in anyprogramming language that supportsclosures; 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.
Intype theory, the general idea of atype system in computer science is formalized into a specific algebra of types. For example, when writing, the intent is that and aretypes, while the arrow is atype constructor, specifically, thefunction type or arrow type. Similarly, the Cartesian product of types is constructed by theproduct type constructor.
The type-theoretical approach is expressed in programming languages such asML and the languages derived from and inspired by it:Caml,Haskell, andF#.
The type-theoretical approach provides a natural complement to the language ofcategory theory, as discussed below. This is because categories, and specifically,monoidal categories, have aninternal language, withsimply 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 (viaCurry–Howard correspondence), and as other types of mathematical systems, as explored further, below.
Under theCurry–Howard correspondence, the existence of currying and uncurrying is equivalent to the logical theorem (also known asexportation), astuples (product type) corresponds to conjunction in logic, and function type corresponds to implication.
Theexponential object in the category ofHeyting algebras is normally written asmaterial implication. Distributive Heyting algebras areBoolean algebras, and the exponential object has the explicit form, thus making it clear that the exponential object really ismaterial implication.[23]
The above notions of currying and uncurrying find their most general, abstract statement incategory theory. Currying is auniversal property of anexponential object, and gives rise to anadjunction incartesian closed categories. That is, there is anaturalisomorphism between themorphisms from abinary product and the morphisms to an exponential object.
This generalizes to a broader result inclosed monoidal categories: Currying is the statement that thetensor product and theinternal Hom areadjoint functors; that is, for every object there is anatural isomorphism:
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 thecategory 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 notclosed, 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 notmonoidal, 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 ofclassical logic; the more general setting of closed monoidal categories is suitable forquantum computation.[24]
The difference between these two is that theproduct for cartesian categories (such as thecategory of sets,complete partial orders orHeyting algebras) is just theCartesian product; it is interpreted as anordered pair of items (or a list).Simply typed lambda calculus is theinternal language of cartesian closed categories; and it is for this reason that pairs and lists are the primarytypes in thetype theory ofLISP,Scheme and manyfunctional programming languages.
By contrast, the product formonoidal categories (such asHilbert space and thevector spaces offunctional analysis) is thetensor product. The internal language of such categories islinear logic, a form ofquantum logic; the correspondingtype system is thelinear type system. Such categories are suitable for describingentangled quantum states, and, more generally, allow a vast generalization of theCurry–Howard correspondence toquantum mechanics, tocobordisms inalgebraic topology, and tostring theory.[3] Thelinear type system, andlinear logic are useful for describingsynchronization primitives, such as mutual exclusion locks, and the operation of vending machines.
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 whosearity 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 firstargument of the function, you get a function of the remaining arguments". For example, if functiondiv stands for the division operationx/y, thendiv with the parameterx fixed at 1 (i.e.,div 1) is another function: the same as the functioninv that returns the multiplicative inverse of its argument, defined byinv(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 toplus_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.
There is a device originated by Schönfinkel, for reducing operators with several operands to the successive application of single operand operators.
In the last line we have used a trick called Currying (after the logician H. Curry) to solve the problem of introducing a binary operation into a language where all functions must accept a single argument. (The referee comments that although "Currying" is tastier, "Schönfinkeling" might be more accurate.)Republished asReynolds, John C. (1998)."Definitional Interpreters for Higher-Order Programming Languages".Higher-Order and Symbolic Computation.11 (4). Boston: Kluwer Academic Publishers:363–397.doi:10.1023/A:1010027404223. 13 – via Syracuse University: College of Engineering and Computer Science - Former Departments, Centers, Institutes and Projects.
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.