Information About

Currying




Uncurrying is the reverse transformation.

Intuitively, currying says "if you fix some Argument s, you get a function of the remaining arguments". So if you take the function in two variables y^x, and fix y=2, then you get the function in one variable 2^x.

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 Language s have Syntactic Sugar for currying, notably ML and Haskell . Any language that supports functions as First-class Object s, including Lisp , Perl , Ruby , Python , R , S and JavaScript can be used to write curried functions. Python 2.5 will include a standard library module implementing partial function application .


EXAMPLES

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.

When declaring functions in the strictly-typed OCaml Programming Language , the type returned by a function shows the Curried form of the function. Typing the function into the OCaml Interpreter displays the type immediately:

# let plus x y = x + y ;;
val plus : int -> int -> int =


C++

Currying may be achieved in C++ using the Standard Template Library function object adapters (binder1st and binder2nd), and more generically using the Boost bind mechanism.

Here is another way to do currying in C++ (from this comment on codepost.org):

The plus function:

int plus(int x, int y) {
return x + y;
}

The curried version of plus:

class curried_plus {
private:
int x;
public:
curried_plus(int _x) : x(_x) {}
int operator () (int y) const {
return plus(x, y);
}
};

and the usage:

curried_plus plus_one(1);

now plus_one(2) returns 3.


MATHEMATICAL VIEW

When viewed in a set-theoretic light, currying becomes the Theorem that the set
A^{B imes C} of functions from
B imes C to A, and the set (A^B)^C of functions from
C to the set of functions from B to A,
are Isomorphic .

In other words, currying is the statement that product and Hom are Adjoint Functors ;
this is the key property of being a Cartesian Closed Category .


SEE ALSO