Saturday, February 15, 2014

currying



In computer languages where functions are values (C#, JavaScript, etc.), and we can manipulate function values in interesting ways. Currying allows us to produce a new function by combining a function and an argument. The curry method works by creating a closure [twotw] that holds that original function and the arguments to curry. It returns a function that, when invoked, returns the result of calling that original function, passing it all of the arguments from the invocation of curry and the current invocation.

// non-curried function
function f(a, b) {
return a * a + b;
}

// partial function application by currying
function f2(a) {
     var a2 = a * a;
     return function (b) {
           return a2 + b;
     }
}

Partial function application and currying may have some difference among the academic community, but in either case the concepts are closely related.
Since I couldn’t find a good definition, let me take a stab using plain language.

Currying is when a function captures some arguments in a closure and returns a function that accepts more arguments.

Some reasons to curry come to mind:
  1. Timing. Some arguments are available early during code execution, but not later, while other arguments are only available later.
  2. Efficiency. If a function is called many times with some arguments of the same value, then those common arguments can be used to calculate intermediate values.
  3. Convenience. If a function is called many times with some arguments of the same value, then those common arguments can be curried and don’t need to be passed every call.
This week, I used currying to remember an argument that wouldn’t be available later when needed. This is perhaps more common in JavaScript where server-side code and client-side code execute in different environments than they would be in a stand-alone application.


Other definitions for curry
·         to clean the coat of (as a horse)
·         to treat (tanned leather) especially by incorporating oil or grease
·         a food, dish, or sauce in Indian cuisine seasoned with a mixture of pungent spices
·         curry favor to ingratiate oneself, especially with superiors

So how did the software definition of curry get its name? According to Wikipedia, “The name "currying", coined by Christopher Strachey in 1967, is a reference to logician Haskell Curry. The alternative name "Schönfinkelisation" has been proposed as a reference to Moses Schönfinkel.” Personally, I’m glad Chris chose “Curry”. BTW, does Curry’s first name look familiar? The popular programming language Haskell is named after him (wiki).

So how did Haskell Curry get his name? From his parents, of course, “Curry was born on September 12, 1900, in Millis, Massachusetts, to Samuel Silas Curry and Anna Baright Curry”.

No comments:

Post a Comment