challenge #2: implement the varargs_reduce metafunction

Chris Nicholson-Sauls ibisbasenji at gmail.com
Tue Jan 23 13:27:23 PST 2007


Andrei Alexandrescu (See Website For Email) wrote:
> Frits van Bommel wrote:
>> Andrei Alexandrescu (See Website For Email) wrote:
>>> janderson wrote:
>>>> Andrei Alexandrescu (See Website for Email) wrote:
>>>>> 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
>>>>
>>>>
>>>> While your at it.  What about a multi-threaded version?   ie Each 
>>>> function that is called is placed on one of 4 threads.
>>>
>>> That's a good point, and goes right to the core of my solution, which 
>>> (similarly to Bruno Medeiros') arranges operations in an optimal way 
>>> for superscalar evaluation, e.g. max(a, b, c, d) is expanded not to:
>>>
>>> max2(max2(max2(a, b), c), d)
>>>
>>> but instead to:
>>>
>>> max2(max2(a, b), max2(c, d))
>>
>> Assumes the operation is associative. That may not always be the case; 
>> it's not even necessarily true that the function takes arguments of 
>> identical types.
>>
>> Silly example:
>> char[] accumulate(char[] arr, char element) { return arr ~= element; }
> 
> I think this ia a good point. Probably varargs_reduce must be linear to 
> make the most conservative assumptions. There is always the chance of 
> defining varargs_reduce_parallel. Thanks!
> 
> 
> Andrei

I think that would be best (having a semi-seperate _parellel version).  I also wonder 
about applying this same "feature" to functions of 3 or 4 arguments (or even arbitrary! so 
long as none are themselves variadic), but that could come later.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list