www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - liittle question about reduce

reply bioinfornatics <bioinfornatics fedoraproject.org> writes:
hi,


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

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

but by this way that is ok:
reduce!( (a,b) =3D> a + b )( 0, list ); // sum all elements
Sep 29 2012
parent reply Timon Gehr <timon.gehr gmx.ch> writes:
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
Sep 29 2012
parent "monarch_dodra" <monarchdodra gmail.com> writes:
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)
Sep 30 2012