|
|
On 7/2/2011 0:19, Warp wrote:
> It's a bit like the magical term "currying". There seems to be something
> very special about it, but I just fail to understand what it is.
Currying isn't particularly magical, especially if you understand lambdas.
What currying means is that a function that takes 4 arguments is really a
function that takes 1 argument and returns a lambda that takes 3 arguments.
*That* returned lambda is really a lambda that takes one argument and
returns a lambda that takes two arguments. *That* returned lambda is really
in turn a lambda that takes 1 argument and returns a function that takes one
argument. Currying just means you can write f(a, b, c, d) and the "returns a
lambda that takes N-1 arguments" is handled automatically by the language.
The original reason for inventing the concept was to make it easier to
formalize computation, i.e., for the same reason one invents Turing machines
and lambda calculus and such. Currying let you build an entire language out
of functions that only take one argument and only yield one result, while
still letting you program (so to speak) as if you had multiple arguments and
multiple return values. It's just mathematically easier to not have to deal
with variable length argument lists.
You get the same benefits as if you had, in C++, a definition like
int abc(int x, int y) {
return x + y;
}
and that the call abc(5) would return a lambda that took one integer
argument and added 5 to it.
In practice, unless your language defines a function as "a lambda with a
name" (instead of vice versa), they're not all that useful. You just don't
use them a lot in a language that has multiple arguments to functions,
overloaded functions, virtual dispatch, etc.
Currying probably seems "magic" because in a language where you have only
single-argument functions, currying "magically" gives you multiple-argument
functions that are more powerful than regular multi-argument functions. But
if your language already has lambdas, the extra power is already easily
available when you want it, so the answer is along the lines "Yeah, so?"
Oh, it also lets you deal with variable length argument lists (a la printf,
say), because each call can return a lambda that can consume any number of
arguments. But again, if your language already supports passing variable
number of arguments (either in the C# style of packaging them into "really"
being an array or the C style of iterating thru the list on the stack), it's
really not impressive or "magical".
So, currying is really a way to unify various kinds of multiple-argument
functions (multiple arguments, overloads, variable # arguments) in one
syntactical mechanism that the other languages just handle as different things.
--
Darren New, San Diego CA, USA (PST)
"Coding without comments is like
driving without turn signals."
Post a reply to this message
|
|