Functional vs simple code

ixid nuaccount at gmail.com
Tue Oct 2 22:07:11 PDT 2012


>A typical use case is to find the maximum of a range (there is 
>an example of this in the documentation at 
>http://dlang.org/phobos/std_algorithm.html#reduce). If you don't 
>know the highest possible value of elements, then you couldn't 
>come up with an appropriate seed for this case.

Fixing unseeded reduce would not remove that use case though, it 
just happens to be a case that's not broken by the way unseeded 
reduce works, why couldn't unseeded reduce compare a (the first 
datum) to itself? That would discover a isn't greater than a so 
leave a in position 0 and compare with all of the other elements. 
It would also avoid breaking uses like "a + b + 2" and "a + b * 
2" as well as a raft of more complex uses that reduce should be 
able to do but requires map and then reduce at present.

Walter Bright has a subtle bug in his code (the combined sum and 
square reduce) in his latest Dr Dobbs due to the behaviour of 
unseeded reduce. I'd call that more broken than unintuitive.

int[] arr = [1,2,3,4,5];
auto r = arr.reduce!((a,b) => a + b, (a,b) => a + b * b);
writefln("sum = %s, sum of squares = %s", r[0], r[1]);

If you change the value of the first number to 2 the square sum 
is an incorrect 56 when it should be 58.


More information about the Digitalmars-d-learn mailing list