Currying Explained

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

f:(X x Y)\toZ

that takes two arguments, one from

X

and one from

Y,

and produces objects in

Z.

The curried form of this function treats the first argument as a parameter, so as to create a family of functions

fx:Y\toZ.

The family is arranged so that for each object

x

in

X,

there is exactly one function

fx.

In this example,

curry

itself becomes a function, that takes

f

as an argument, and returns a function that maps each

x

to

fx.

The proper notation for expressing this is verbose. The function

f

belongs to the set of functions

(X x Y)\toZ.

Meanwhile,

fx

belongs to the set of functions

Y\toZ.

Thus, something that maps

x

to

fx

will be of the type

X\to[Y\toZ].

With this notation,

curry

is a function that takes objects from the first set, and returns objects in the second set, and so one writes

curry:[(X x Y)\toZ]\to(X\to[Y\toZ]).

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] The example above can be used to illustrate partial application; it is quite similar. Partial application is the function

apply

that takes the pair

f

and

x

together as arguments, and returns

fx.

Using the same notation as above, partial application has the signature

apply:([(X x Y)\toZ] x X)\to[Y\toZ].

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 programming languages, 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.

The concept of currying was introduced by Gottlob Frege,[2] [3] developed by Moses Schönfinkel,[4] [3] [5] [6] [7] [8] and further developed by Haskell Curry.[9] [10]

f

whose return value is another function

g

, and yields a new function

f'

that takes as parameters the arguments for both

f

and

g

, and returns, as a result, the application of

f

and subsequently,

g

, 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.[11] 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. 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.[12] The alternative name "Schönfinkelisation" has been proposed.[13] In the mathematical context, the principle can be traced back to work in 1893 by Frege.[2] [3]

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,[14] 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.[5] John C. Reynolds defined "currying" in a 1972 paper, but did not claim to have coined the term.[6]

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

X\toY

denotes all functions from

X

to

Y

. If

f

is such a function, we write

f\colonX\toY

. Let

X x Y

denote the ordered pairs of the elements of

X

and

Y

respectively, that is, the Cartesian product of

X

and

Y

. Here,

X

and

Y

may be sets, or they may be types, or they may be other kinds of objects, as explored below.

Given a function

f\colon(X x Y)\toZ

,

currying constructs a new function

g\colonX\to(Y\toZ)

.

That is,

g

takes an argument of type

X

and returns a function of type

Y\toZ

. It is defined by

g(x)(y)=f(x,y)

for

x

of type

X

and

y

of type

Y

. We then also write

curry(f)=g.

Uncurrying is the reverse transformation, and is most easily understood in terms of its right adjoint, the function

\operatorname{apply}.

Set theory

In set theory, the notation

YX

is used to denote the set of functions from the set

X

to the set

Y

. Currying is the natural bijection between the set

AB x

of functions from

B x C

to

A

, and the set

(AC)B

of functions from

B

to the set of functions from

C

to

A

. In symbols:

AB x \cong(AC)B

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

C

, the functor

B\mapstoB x C

is left adjoint to the functor

A\mapstoAC

.

YX

is called the exponential object.

Function spaces

In the theory of function spaces, such as in functional analysis or homotopy theory, one is commonly interested in continuous functions between topological spaces. One writes

Hom(X,Y)

(the Hom functor) for the set of all functions from

X

to

Y

, and uses the notation

YX

to denote the subset of continuous functions. Here,

curry

is the bijection

curry:Hom(X x Y,Z)\toHom(X,Hom(Y,Z)),

while uncurrying is the inverse map. If the set

YX

of continuous functions from

X

to

Y

is given the compact-open topology, and if the space

Y

is locally compact Hausdorff, then

curry:ZX x \to(ZY)X

is a homeomorphism. This is also the case when

X

,

Y

and

YX

are compactly generated,[15] [16] although there are more cases.[17] [18]

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,

\begin{align}&&eval:YX x X\toY\\ &&(f,x)\mapstof(x)\end{align}

is continuous when

YX

is compact-open and

Y

locally compact Hausdorff.[19] These two results are central for establishing the continuity of homotopy, i.e. when

X

is the unit interval

I

, so that

ZI x \cong(ZY)I

can be thought of as either a homotopy of two functions from

Y

to

Z

, or, equivalently, a single (continuous) path in

ZY

.

Algebraic topology

In algebraic topology, currying serves as an example of Eckmann–Hilton duality, and, as such, plays an important role in a variety of different settings. For example, loop space is adjoint to reduced suspensions; this is commonly written as

[\SigmaX,Z]eq[X,\OmegaZ]

where

[A,B]

is the set of homotopy classes of maps

AB

, and

\SigmaA

is the suspension of A, and

\OmegaA

is the loop space of A. In essence, the suspension

\SigmaX

can be seen as the cartesian product of

X

with the unit interval, modulo an equivalence relation to turn the interval into a loop. The curried form then maps the space

X

to the space of functions from loops into

Z

, that is, from

X

into

\OmegaZ

.[19] Then

curry

is the adjoint functor that maps suspensions to loop spaces, and uncurrying is the dual.[19]

The duality between the mapping cone and the mapping fiber (cofibration and fibration)[15] can be understood as a form of currying, which in turn leads to the duality of the long exact and coexact Puppe sequences.

In homological algebra, the relationship between currying and uncurrying is known as tensor-hom adjunction. Here, an interesting twist arises: the Hom functor and the tensor product functor might not lift to an exact sequence; this leads to the definition of the Ext functor and the Tor functor.

Domain theory

In order theory, that is, the theory of lattices of partially ordered sets,

curry

is a continuous function when the lattice is given the Scott topology.[20] Scott-continuous functions were first investigated in the attempt to provide a semantics for lambda calculus (as ordinary set theory is inadequate to do this). More generally, Scott-continuous functions are now studied in domain theory, which encompasses the study of denotational semantics of computer algorithms. Note that the Scott topology is quite different than many common topologies one might encounter in the category of topological spaces; the Scott topology is typically finer, and is not sober.

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

f(x,y)

taking two arguments, and having the type

(X x Y)\toZ

, which should be understood to mean that x must have the type

X

, y must have the type

Y

, and the function itself returns the type

Z

. The curried form of f is defined as

curry(f)=λx.(λy.(f(x,y)))

where

λ

is the abstractor of lambda calculus. Since curry takes, as input, functions with the type

(X x Y)\toZ

, one concludes that the type of curry itself is

curry:((X x Y)\toZ)\to(X\to(Y\toZ))

The → operator is often considered right-associative, so the curried function type

X\to(Y\toZ)

is often written as

X\toY\toZ

. Conversely, function application is considered to be left-associative, so that

f(x,y)

is equivalent to

((curry(f)x)y)=curry(f)xy

.

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

f\colonX\toY

, the intent is that

X

and

Y

are types, while the arrow

\to

is a type constructor, specifically, the function type or arrow type. Similarly, the Cartesian product

X x Y

of types is constructed by the product type constructor

x

.

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

((A\landB)\toC)\Leftrightarrow(A\to(B\toC))

(also known as exportation), as tuples (product type) corresponds to conjunction in logic, and function type corresponds to implication.

QP

in the category of Heyting algebras is normally written as material implication

P\toQ

. Distributive Heyting algebras are Boolean algebras, and the exponential object has the explicit form

\negP\lorQ

, thus making it clear that the exponential object really is material implication.[21]

Category theory

f\colon(X x Y)\toZ

and the morphisms to an exponential object

g\colonX\toZY

.

This generalizes to a broader result in closed monoidal categories: Currying is the statement that the tensor product and the internal Hom are adjoint functors; that is, for every object

B

there is a natural isomorphism:

Hom(AB,C)\congHom(A,BC).

Here, Hom denotes the (external) Hom-functor of all morphisms in the category, while

BC

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

BC

becomes the exponential object

CB

.

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.[22]

The difference between these two is that the product for cartesian categories (such as the category of sets, complete partial orders or Heyting algebras) is just the Cartesian product; it is interpreted as an ordered pair of items (or a list). Simply typed lambda calculus is the internal language of cartesian closed categories; and it is for this reason that pairs and lists are the primary types in the type theory of LISP, Scheme and many functional programming languages.

By contrast, the product for monoidal categories (such as Hilbert space and the vector spaces of functional analysis) is the tensor product. The internal language of such categories is linear logic, a form of quantum logic; the corresponding type system is the linear type system. Such categories are suitable for describing entangled quantum states, and, more generally, allow a vast generalization of the Curry–Howard correspondence to quantum mechanics, to cobordisms in algebraic topology, and to string theory.[23] The linear type system, and linear logic are useful for describing synchronization primitives, such as mutual exclusion locks, and the operation of vending machines.

Contrast with partial function application

See main article: article and Partial application. Currying and partial function application are often conflated.[24] 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

f\colon(X x Y x Z)\toN

, currying produces

curry(f)\colonX\to(Y\to(Z\toN))

. That is, while an evaluation of the first function might be represented as

f(1,2,3)

, evaluation of the curried function would be represented as

fcurried(1)(2)(3)

, applying each argument in turn to a single-argument function returned by the previous invocation. Note that after calling

fcurried(1)

, 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

f

above, we might fix (or 'bind') the first argument, producing a function of type

partial(f)\colon(Y x Z)\toN

. Evaluation of this function might be represented as

fpartial(2,3)

. 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

f\colon(X x Y x Z)\toN

and

a\inX

then

curry(partial(f)a)(y)(z)=curry(f)(a)(y)(z)

or simply

partial(f)a=curry1(f)(a)

where

curry1

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

f(x,y)

, a function

g(y,x)

may be defined such that

g(y,x)=f(x,y)

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

See also

Notes and References

  1. Web site: cdiggins . 24 May 2007 . Currying != Generalized Partial Application?! . Lambda the Ultimate: The Programming Languages Weblog.
  2. Book: Frege, Gottlob . Grundgesetze der arithmetik . Hermann Pohle . Book from the collections of University of Wisconsin - Madison, digitized by Google on 26 August 2008 . 1893 . Jena . 54–55 . de . § 36 . Gottlob Frege . https://archive.org/details/bub_gb_LZ5tAAAAMAAJ/page/n89.
  3. Book: Quine, W. V. . From Frege to Gödel: A Source Book in Mathematical Logic, 1879-1931 . Harvard University Press . 1967 . 9780674324497 . van Heijenoort . Jean . 355–357 . Introduction to Moses Schönfinkel's 1924 "On the building blocks of mathematical logic" . Willard Van Orman Quine.
  4. Schönfinkel . Moses . September 1924 . Presented at the Mathematischen Gesellschaft (Mathematical Society) in Göttingen on 7 December 1920. Received by Mathematische Annalen on 15 March 1924. . Über die Bausteine der mathematischen Logik . On the building blocks of mathematical logic . . Moskau . Springer . Berlin? . 92 . 3–4 . 305–316 . 10.1007/BF01448013 . 118507515.
  5. Strachey . Christopher . April 2000 . This paper forms the substance of a course of lectures given at the International Summer School in Computer Programming at Copenhagen in August, 1967. . Fundamental Concepts in Programming Languages . Higher-Order and Symbolic Computation . en . 13 . 11–49 . 10.1.1.332.3161 . 10.1023/A:1010000313106 . 1573-0557 . 14124601 . There is a device originated by Schönfinkel, for reducing operators with several operands to the successive application of single operand operators..
  6. Originally published as Book: Reynolds, John C. . Proceedings of the ACM annual conference - ACM '72 . Definitional interpreters for higher-order programming languages . John C. Reynolds . 1 August 1972 . http://portal.acm.org/citation.cfm?doid=800194.805852 . Rosemary Shields . en . ACM Press . 2 . 717–740 . 10.1145/800194.805852 . 9781450374927 . 163294 . 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 as Reynolds . John C. . John C. Reynolds . 1998 . Definitional Interpreters for Higher-Order Programming Languages . Higher-Order and Symbolic Computation . Kluwer Academic Publishers . Boston . 11 . 4 . 363–397 . 10.1023/A:1010027404223 . 13 . Syracuse University: College of Engineering and Computer Science - Former Departments, Centers, Institutes and Projects.

  7. Book: Slonneger . Kenneth . Formal Syntax and Semantics of Programming Languages: A Laboratory Based Approach . Kurtz . Barry L. . Addison-Wesley Publishing Company . 1995 . 0-201-65697-3 . 144 . Curried Functions, 5.1: Concepts and Examples, Chapter 5: The Lambda Calculus.
  8. Web site: 6 May 2012 . Currying Schonfinkelling . Portland Pattern Repository's Wiki . Cunningham & Cunningham, Inc..
  9. Book: Barendregt . Henk . Introduction to Lambda Calculus . Barendsen . Erik . March 2000 . Revised . 8 . December 1998.
  10. Book: Curry, Haskell. Feys, Robert. Combinatory logic. North-Holland Publishing Company . I. 2. 1958. Amsterdam, Netherlands.
  11. Web site: November 2002 . Hutton . Graham . Jones . Mark P. . Frequently Asked Questions for comp.lang.functional, 3. Technical topics, 3.2. Currying . University of Nottingham Computer Science.
  12. Curry . Haskell B. . 1980 . Barwise . Jon . Keisler . H. Jerome . Kunen . Kenneth . 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 . North-Holland Publishing Company, imprint of Elsevier . 101 . 85–101 . 10.1016/S0049-237X(08)71254-0 . 9780444853455 . 0049-237X . 117179133 . 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..
  13. Book: Heim . Irene . Semantics in Generative Grammar . Kratzer . Angelika . January 2, 1998 . Blackwell Publishers, an imprint of Wiley . 1998 . 0-631-19712-5 . Malden, Massachusetts . en.
  14. Web site: Turner . David . 1 Jun 1997 . Programming language, Currying, or Schonfinkeling?, #9 / 14 . live . https://web.archive.org/web/20220303194614/http://computer-programming-forum.com/26-programming-language/976f118bb90d8b15.htm . 3 March 2022 . 3 March 2022 . Computer Programming Language Forum.
  15. Book: May, Jon Peter . A concise course in algebraic topology . 1999 . University of Chicago Press . 0-226-51183-9 . Chicago lectures in mathematics . Chicago, Ill. . 39–55 . 41266205.
  16. Web site: 28 May 2023 . compactly generated topological space . nLab.
  17. Tillotson . J. . Booth . Peter I. . Received 2 October 1978, revised 29 June 1979, published 1 May 1980 . Monoidal closed, Cartesian closed and convenient categories of topological spaces . Pacific Journal of Mathematics . Memorial University of Newfoundland . Mathematical Sciences Publishers . Berkeley, California . March 1980 . 88 . 1 . 35–53 . 10.2140/pjm.1980.88.35 . 0030-8730 . 1945-5844.
  18. Web site: 11 August 2023 . convenient category of topological spaces . nLab.
  19. Book: Rotman, Joseph Jonah . An introduction to algebraic topology . 1988 . Springer-Verlag . 978-0-387-96678-6 . Graduate texts in mathematics; 119 . New York . Chapter 11 . 17383909.
  20. Book: Barendregt, Hendrik Pieter . The lambda calculus: its syntax and semantics . 1984 . North-Holland, an imprint of Elsevier . 978-0-444-87508-2 . Rev. . Studies in logic and the foundations of mathematics . 103 . Theorems 1.2.13, 1.2.14.
  21. Book: Mac Lane . Saunders . Moerdijk . Ieke . 1992 . Springer-Verlag, part of Springer Science & Business Media . 978-0-387-97710-2 . New York . 48–57 . en . Chapter I. Categories of Functors; sections 7. Propositional Calculus, 8. Heyting Algebras, and 9. Quantifiers as Adjoints . https://books.google.com/books?id=SGwwDerbEowC&pg=PA48.
  22. Abramsky . Samson . Coecke . Bob . 5 March 2007 . A categorical semantics of quantum protocols . 10.1109/LICS.2004.1319636 . Logic in Computer Science (LICS 2004): Proceedings, 19th Annual IEEE Symposium, Turku, Finland, 2004] . en . IEEE Computer Society Press . quant-ph/0402130.
  23. Book: Baez . John C. . Stay . Mike . New Structures for Physics . Physics, Topology, Logic and Computation: A Rosetta Stone . 6 June 2009 . Coecke . Bob . Lecture Notes in Physics . Springer . Berlin, Heidelberg . 5 July 2010 . 813: New Structures for Physics . 95–172 . 0903.0340 . 10.1007/978-3-642-12821-9_2 . 978-3-642-12821-9 . 115169297 . https://web.archive.org/web/20221205124044/https://math.ucr.edu/home/baez/rosetta/rose3.pdf . 5 December 2022.
  24. Web site: 7 August 2020 . Partial Function Application is not Currying . live . https://web.archive.org/web/20161023205431/http://www.uncarved.com/articles/not_currying . 23 October 2016 . The Uncarved Block.
  25. Web site: Lee . G. Kay . 15 May 2013 . Functional Programming in 5 Minutes . Slides.