Thread overview
liittle question about reduce
Sep 29, 2012
bioinfornatics
Sep 29, 2012
Timon Gehr
Sep 30, 2012
monarch_dodra
September 29, 2012
hi,


int[] list = [ 0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];

why this do not works ?
list.reduce!( (a,b) => a + b )( 0 ); // sum all elements

but by this way that is ok:
reduce!( (a,b) => a + b )( 0, list ); // sum all elements


September 29, 2012
On 09/30/2012 01:04 AM, bioinfornatics wrote:
> hi,
>
>
> int[] list = [ 0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
>
> why this do not works ?
> list.reduce!( (a,b) => a + b )( 0 ); // sum all elements
>
> but by this way that is ok:
> reduce!( (a,b) => a + b )( 0, list ); // sum all elements
>
>


Because of the parameter order.

0.reduce!((a,b)=>a+b)(list); // works
September 30, 2012
On Saturday, 29 September 2012 at 23:07:30 UTC, Timon Gehr wrote:
> On 09/30/2012 01:04 AM, bioinfornatics wrote:
>> hi,
>>
>>
>> int[] list = [ 0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
>>
>> why this do not works ?
>> list.reduce!( (a,b) => a + b )( 0 ); // sum all elements
>>
>> but by this way that is ok:
>> reduce!( (a,b) => a + b )( 0, list ); // sum all elements
>>
>>
>
>
> Because of the parameter order.
>
> 0.reduce!((a,b)=>a+b)(list); // works

Yeah... UFCS sometimes doesn't lend itself all that well to certain functions.

This because UFCS was invented later in D's life cycle. It would have been better if reduce's range was defined as the "first" argument, rather than the "last".

This is especially true, because you don't have to specify the seed:
reduce!( (a,b) => a + b )( list ); //OK
reduce!( (a,b) => a + b )( 0, list ); //OK

This reads very odly to me. I know this is not a case of "default argument", but I don't like the change of usual behavior. I'd have expected this as valid syntax:
reduce!( (a,b) => a + b )( list, 0 ); //Should be the valid syntax.

Too late to change it now I guess! (unless we create a duplicate function called accumulate or something, but won't happen).

Anywhoo, if you don't specify the seed (which you don't have to here), then you can just use:

    int[] list = [ 0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
    list.reduce!( (a,b) => a + b )(); // sum all elements

If you wanted the sum of the 10 first integrals, this also works:

    iota(0,10).reduce!"a+b"().writeln();

I really like the trailing writeln() :D UFCS is BY FAR one of the things I enjoy the most in D (not the most important feature, but the most enjoyable)