Boost logo

Boost :

Subject: Re: [boost] painless currying
From: Eric Niebler (eric_at_[hidden])
Date: 2011-08-24 11:13:24


On 8/24/2011 1:58 AM, Roman Perepelitsa wrote:
> 2011/8/23 Eric Niebler <eric_at_[hidden]>
>
>> After playing around with functional languages, I've come to envy how
>> easy they make it to curry functions. Call a 2-argument function with 1
>> argument and you get a function that takes 1 argument. Pass another
>> argument and it evaluates the function. Simple. In contrast, C++ users
>> have to use binders, which are not as nice.
>>
>> On a lark, I implemented a wrapper that turns any TR1-style function
>> object into a "curryable" function object (attached). Successive
>> function call invocations bind arguments until enough arguments are
>> bound to invoke the wrapped function. With it you can do the following:
>>
>> curryable<std::plus<int> > p;
>> auto curried = p(1);
>> int i = curried(2);
>> assert(i == 3);
>>
>> Is there any interest in such a thing?
>
>
> I think it's a very useful thing to have!
>
> curryable should probably be renamed to curried (this is the term
> http://en.wikipedia.org/wiki/Currying uses). A generator for curried objects
> named curry would be a nice addition too, as would be the reverse - uncurry.

Thanks. It's important to get the terminology right. But I thought
uncurry had to do with tuples holding arguments.

> By the way, don't you need to manually pass arity in the general case? What
> if the underlying functor is callable with one argument, but also with two?

As soon as enough arguments are collected to make a valid call of the
curried function, it gets called. This seems reasonable to me.

> I think this is the case with functors generated by bind -- they appear to
> be callable with any number of arguments.

Ouch. :-(

One option, which I don't like, is to "fix" bind to disable any
operator() overloads that result in an invalid invocation of the bound
function. That can be done easily with the is_callable_with metafunction
in my curryable implementation, but would reduce portability somewhat.

> FWIW, Egg<http://p-stade.sourceforge.net/egg/doc/html/egg/function_adaptors.html>has
> curryN (where N is a number literal) and uncurry.

Of course, I'd prefer it if it just worked without needing to be told
the arity. That's what I was aiming for.

-- 
Eric Niebler
BoostPro Computing
http://www.boostpro.com

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk