Currying

From CS 61A Wiki
(Redirected from Curry)
Jump to: navigation, search

Currying is the transformation of a multi-argument function into a chain of single-argument functions. Given a function that takes n arguments, currying creates a function that accepts the first argument and returns a function that accepts the second argument, and so on. For example, given a function f(x, y), we can define a function g such that g(x)(y) == f(x, y). g is the curried version of f; it is also a higher-order function.

Code

The following function curries a two-argument function:

curry = lambda f: lambda x: lambda y: f(x, y)

Examples:

>>> from operator import add
>>> curry(add)(1)(2)
3
>>> list(curry(map)(lambda x: x * x)([1, 2, 3]))
[1, 4, 9]

Motivation

Currying uses single-argument functions to simulate multi-argument functions. Some programming languages, such as Haskell, only allow single-argument functions, so the programmer must curry all multi-argument functions.

In languages like Python, currying is useful when we require a function that takes in only a single argument. For example, map applies a single-argument function to a sequence of values. If we want to add a constant to each element of a sequence, we need to curry add and pass in the constant before map can use it:

>>> from operator import add
>>> add5 = curry(add)(5)
>>> list(map(add5, [1, 2, 3])) # add 5 to each element
[6, 7, 8]

Sources