Function Currying

Bill Baxter dnewsgroup at billbaxter.com
Tue Nov 14 21:48:28 PST 2006


Hasan Aljudy wrote:
> 
> 
> Brad Roberts wrote:
>> The net is a truly wonderful resource:
>>
>> http://en.wikipedia.org/wiki/Curried_function
> 
> I've read that a while ago, but it doesn't make much of a sense. Why 
> would anyone need such a thing?
> My original question was, is it something that everyone is supposed to 
> already know its meaning and uses?

Yes, if you've been through a decent CS undergrad program you should 
probably at least have a vague idea what it is.  It's more common in 
functional languages (which should also be part of a decent undergrad 
curriculum).

Although apparently confusion over what's "currying" and what's "partial 
function evaluation" abounds.

The difference as I understand it is that 'currying' is supposed to 
create a new function that takes one parameter and returns a function of 
one less parameter.  So curried_add, a curried version of add(a,b,c), 
could be called like curried_add(a)(b)(c).  So the thing that 'curries' 
add() should just take 'add' as a paramter:  curried_add = curry(add). 
The key is that when you're currying, nothing is actually evaluated. 
curried_add still does everything the original function did.

Partial evaluation is when you actually reduce the number of arguments 
by one or more, by 'baking them in'.  Like in Walter's examples.  So the 
examples are actually showing partial evaluation, not currying.

As for usefulness... one use case is similar to delegates.  If you have 
some function like do_something(Object, argument), with partial 
evaluation you can create a new function 
do_something_to_object(argument), where the object doesn't have to be 
supplied.  And since you can repeat the process for any number of 
arguments you can have something like a delegate that contains N 
implicit .ptr values rather than just one.

Functional language folks are crazy about it.  ML doesn't actually even 
have multi-argument functions.  Every function is always fully curried, 
so every function takes at most 1 argument.  If it appears to take 2 
arguments like "add a b", it's a disguise.  'add' really takes 1 
argument, and returns another function of 1 argument, which then takes 
the second argument, and finally returns a value.

It would be interesting to see if you could actually make a real 'curry' 
function.  One that takes a function, foo(a,b,c,d) of N arguments and 
returns a cascaded set of functions with 1 argument each that you can 
call like curried_foo(a)(b)(c)(d).  It should be doable with some sort 
of recursive template.


--bb



More information about the Digitalmars-d mailing list