Jamie Dixon
Jamie Dixon

Reputation: 54001

Is branching a required feature of currying?

When writing an implementation of a curry function, is it a requirement to be able to branch?

Usage example in Javascript:

var foo = function (a, b) { console.log(a, b); },
x = curry(foo),
y = x('bar'); // An example of branching

x('baz'); // -> 'bar baz'
y('qux'); // - > 'bar qux'

The example here is showing that we call our curried function the first time with the value bar and store the resulting function in variable y.

My question then is: Should we be able to operate on y (passing new arguments) independently from further operations applied to x (in this case passing baz as the next argument).

If you're unsure what currying is, here's what Wikipedia has to say:

In mathematics and computer science, currying is the technique of translating the evaluation of a function that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions, each with a single argument (partial application).

http://en.wikipedia.org/wiki/Currying

Update:

Another way of asking this question is to say: Should a curried function simply maintain it's current state and return no value other than when the final argument is applied, or should each call result in the return of a new function encapsulating all previously applied arguments?

Upvotes: 1

Views: 61

Answers (1)

6502
6502

Reputation: 114481

What is normally meant with currying is that calling a function with less than the expected number of parameters will return a function that expects the remaining missing parameters.

It should not accumulate state on the function object...

f = curry(function(x, y, z) { return x+y+z; });

g = f(1)  // --> <func>
h = g(2)  // --> <func>
h(3)      // --> 6  (computed from 1+2+3)
g(10, 20) // --> 31 (computed from 1+10+20)

currying is even used in pure functional languages where you don't actually have the concept of mutable state.

Upvotes: 3

Related Questions