Currying
|
In computer science, currying is the technique of transforming a function taking multiple arguments into a function that takes a single argument (the first of the arguments to the original function) and returns a new function that takes the remainder of the arguments and returns the result. The technique was named by Christopher Strachey after logician Haskell Curry, though it was invented by Moses Schönfinkel and Gottlob Frege.
An example should make this clear. Suppose that plus is a function taking two arguments x and y and returning x + y. In the ML programming language we would define it as follows:
plus = fn(x, y) => x + y
and plus(1, 2) returns 3 as we expect.
The curried version of plus takes a single argument x and returns a new function which takes a single argument y and returns x + y. In ML we would define it as follows:
curried_plus = fn(x) => fn(y) => x + y
and now when we call curried_plus(1) we get a new function that adds 1 to its argument:
plus_one = curried_plus(1)
and now plus_one(2) returns 3 and plus_one(7) returns 8.
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.
The practical motivation for currying is that very often the functions you get by supplying some but not all of the arguments to a curried function are useful; for example, many languages have a function or operator similar to plus_one. Currying makes it easy to define these functions.
Some programming languages have syntactic sugar for currying, notably ML and Haskell. Any language that supports functions as first-class objects, including Lisp, Perl, boo, Ruby, Python and JavaScript can be used to write curried functions.
Mathematical view
When viewed in a set-theoretic light, currying becomes the theorem that the sets <math>A^{B\times C}<math> and <math>(A^B)^C<math> are isomorphic.