challenge #2: implement the varargs_reduce metafunction

Andrei Alexandrescu (See Website For Email) SeeWebsiteForEmail at erdani.org
Tue Jan 23 11:04:16 PST 2007


Kevin Bealer wrote:
> == Quote from Andrei Alexandrescu (See Website for Email)
> (SeeWebsiteForEmail at erdani.org)'s article
>> My previous post defines max by availing itself of a metafunction called
>> varargs_reduce. Your challenge is to define it. varargs_reduce takes an
>> alias which it assumes is a function of two arguments, and it defines a
>> vararg function that applies that alias repeatedly, similarly to the
>> reduce primitive that is present in functional languages. Again, for
>> background on functional reduce, see e.g.:
>>
>> http://www.joelonsoftware.com/items/2006/08/01.html
>>
>> Define varargs_reduce to deduce the result type properly, and to
>> generate code as efficient as possible.
>>
>> Andrei
> 
> There is a really simple solution, but I'm not sure if it does the right thing
> with respect to your wording above.  What exactly is meant by deducing the result
> type properly?  Specifically, if the input types are different kinds of objects,
> is the result expected to have the same type as a linear sequence of operations?
> 
> 1. Can we assume the type conversions are non-cyclic?
> 2. Should we assume that the delegate looks like: T dg(T, T), or like: T dg(U, V)
> 3. If the signature is T dg(U, V), can we assume that type conversions are non-cyclic?
> 
>  Cyclic types: (requires more template logic than actually shown here)
> 
>   Rock add(Paper x, Scissors y);
>   Paper add(Scissors x, Rock x);
>   Scissors add(Rock x, Paper y);
> 
>  If this kind of stuff is permitted, the solution is possible but a lot messier.

Interesting point. I think varargs_reduce can safely assume that linear 
reduction always works f(f(f(f(...f(a1, a2), a3), a4), ...). My solution 
optimizes more aggressively by assuming that reduction can be performed 
in any order.

Your solution is less optimal because it uses a delegate. Ideally you 
just use an alias and deduce the result type by simply using the alias.


Andrei



More information about the Digitalmars-d mailing list