Currying

From Wikipedia, the free encyclopedia

In mathematics, computer science and linguistics (semantics), currying or Schönfinkelisation[1] is the technique of transforming a function that takes multiple arguments into a function that takes a single argument (the other arguments having been specified by the curry). The technique was named by Christopher Strachey after logician Haskell Curry, though it was invented by Moses Schönfinkel and Gottlob Frege.

Simply put, currying is the transformation of an input into a new function, the new function requiring another input of course. For example f(x) = gx(y), where gx(y) = x + y. Therefore you can say that f(x)(y) = x + y, which means that instead of using a 2 dimensional cartesian input, ie f(x,y), you are using a 1 dimensional input and giving the output another input which will finally produce the result sought.

If a function f has the type f : (X × Y) → Z, and g is f after currying, then g has the type g : X → (YZ) . Uncurrying is the reverse transformation.

Intuitively, currying says "if you fix some arguments, you get a function of the remaining arguments". For example, if function div stands for the curried form of the division operation /, then 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.

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. In category theory, currying can be found in the universal property of an exponential object, which gives rise to the following adjunction in cartesian closed categories : There is a natural isomorphism between the morphisms from a binary product f : X × YZ and the morphisms to an exponential object g: XZ Y.

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 built-in syntactic support for currying, where certain multi-argument functions are expanded to their curried form; notable examples are ML and Haskell. Any language that supports closures, including Lisp, Scheme, Eiffel, Perl, Ruby, Python, R, S, Groovy, Smalltalk and JavaScript, can be used to write curried functions. As of version 2.5, Python includes a standard library module implementing partial function application, which is more generic than its previous approach based on its lambda operator.

Contents

Eiffel has direct support for lambda expressions and hence currying through "inline agents". If f is a function with two arguments, of signature (X × Y) → Z then its curried version is obtained by simply writing

   g (x: X): FUNCTION [ANY, TUPLE [Y], Z]
       do
           Result := agent (closed_x: X; y: Y): Z 
              do 
                 Result := f (closed_x, y) 
              end (x, ?)
       end

where FUNCTION [ANY, TUPLE [Y], Z] denotes the type YZ (agents taking as argument a tuple with a single argument of type Y and returning a result of type Z), which is indeed the type of the agent expression used on the next-to-last line to define the "Result" of g.

Likewise in Haskell, function type signatures show the currying-based structure of functions (note: "\ ->" is Haskell's syntax for anonymous functions, in which the sign \ has been chosen for its resemblance to the Greek letter λ (lambda); it is followed by a list of space-separated arguments, and the arrow -> separates the arguments list from the function body)

   Prelude> let plus = \x y -> x + y
   Prelude> :type plus
   plus :: Integer -> Integer -> Integer
   Prelude> plus 3 5
   8

and currying functions is trivial

   Prelude> let plus5 = plus 5
   Prelude> :type plus5
   plus5 :: Integer -> Integer
   Prelude> plus5 3
   8

In fact, the Haskell definition \x y -> x + y is merely syntactic sugar for \x -> \y -> x + y, which has exactly the same type signature:

   Prelude> let nested_plus = \x -> \y -> x + y
   Prelude> :type nested_plus
   nested_plus :: Integer -> Integer -> Integer

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 = 

This is a simple general currying function written in Scheme:

;curry:function,args->(function)
;Adding using currying 

(define (curry f . args) (lambda x (apply f (append args x))))

This is an example of applying a curried function:

>((curry + 10) 10)
20

This shows how to create syntactically natural currying functions in C#.


public delegate int Plus(int y); 
public delegate Plus CurriedPlus(int x);
public static CurriedPlus plus = 
      delegate(int x) {return delegate(int y) {return x + y;};};
static void Main()
{
    int sum = plus(3)(4); // sum = 7
    int sum2= plus(2)(plus(3)(4)) // sum2 = 9
}

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.

JavaScript code.

function plus(a,b){return a+b}

function curry(f,x){
 return function(){
  var arg=[x].concat(Array.prototype.slice.apply(arguments));
  return f.apply({},arg);
 };
}
alert(curry(plus,2)(3));

This is a Perl 5 example of a general curry function and curried plus using closures:

sub curry{
  my ($func, @args) = @_;

  sub {
    #This @_ is later
    &$func(@args, @_);
  }
}

sub plusXY{
  $_[0] + $_[1];
}

my $plusXOne = curry(\&plusXY, 1);
print &$plusXOne(3), "\n";

Java programming language code.

   public class Currier {
       public interface CurriableFunctor {
           RET evaluate(ARG1 arg1, ARG2 arg2);
       }
   
       public interface CurriedFunctor {
           RET evaluate(ARG2 arg);
       }
   
       final CurriableFunctor functor;
   
       public Currier(CurriableFunctor fn) { functor = fn; }
       
       public CurriedFunctor curry(final ARG1 arg1) {
           return new CurriedFunctor() {
               public RET evaluate(ARG2 arg2) {
                   return functor.evaluate(arg1, arg2);
               }
           };
       }
   
       public static void main(String[] args) {
           Currier.CurriableFunctor add
               = new Currier.CurriableFunctor() {
                   public Integer evaluate(Integer arg1, Integer arg2) {
                       return new Integer(arg1.intValue() + arg2.intValue());
                   }
           };
           
           Currier currier
               = new Currier(add);
           
           Currier.CurriedFunctor add5
               = currier.curry(new Integer(5));
           
           System.out.println(add5.evaluate(new Integer(2)));
       }
   }

A general currying function written in the Io programming language:

curry := method(fn,
        a := call evalArgs slice(1)
        block(
                b := a clone appendSeq(call evalArgs)
                performWithArgList("fn", b)
        )
)

// example:
increment := curry( method(a,b,a+b), 1 )
increment call(5)
// result => 6

When viewed in a set-theoretic light, currying becomes the theorem that the set A^{B\times C} of functions from B\times C to A, and the set (AB)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.

Look up currying in Wiktionary, the free dictionary.

  1. ^ I. Heim and A. Kratzer (1998). Semantics in Generative Grammar. Blackwell.
Advanced Search
Included Web Search Engines


Safe Search

close

Top Matching Results

Occasionally Search.com will highlight specialized results that are based on the context of your query. Examples of specialized results include specific links to news, images, or video.

Top Matching Results may highlight information from other Search.com pages, content from the CNET Network of sites, or third party content. The listings are based purely on relevance. Search.com does not receive payment for listings in this section but our partners that provide this data may get paid for listing these products.

Sponsored Links

This section contains paid listings which have been purchased by companies that want to have their sites appear for specific search terms and related content. These listings are administered, sorted and maintained by a third party and are not endorsed by Search.com.

Search Results

Search.com sends your search query to several search engines at one time and integrates the results into one list which has been sorted by relevance using Search.com's proprietary algorithm. You can customize the list of search engines included in your metasearch from the preferences.

The search engines that are used in your metasearch may allow companies to pay to have their Web sites included within the results. To view the Paid Inclusion policy for a specific search engine, please visit their Web site. Search.com does not accept payment or share revenue with any search engine partner for listings in this section.