Component Programming in D

ixid nuaccount at gmail.com
Tue Oct 2 18:40:17 PDT 2012


On Tuesday, 2 October 2012 at 21:27:42 UTC, Andrei Alexandrescu 
wrote:
> http://www.reddit.com/r/programming/comments/10u6sk/component_programming_in_d/
>
> Andrei

The article contains a bug due to the pernicious behaviour of 
seedless reduce.

This section:

"Just to show how flexible algorithms can be, reduce can also 
compute multiple values with one pass through the data (which is 
pretty useful for streaming data and would be expensive to save 
for a second pass through it). Multiple lambdas produce a tuple 
result, here the sum and sum of squares is computed:

     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]);

Which prints: sum = 15, sum of squares = 55"

That is the correct answer for the squares sum but only because 
1*1 is 1, what it's really doing here is 1 + (2 * 2) + (3 * 3) + 
(4 * 4) + (5 * 5) which happens to work in this case and for "a + 
b" and "a - b" but is otherwise broken. The first element of a 
seedless reduce does not have any operation carried out on it.

If we change the array to [2,2,2,2,2] we would expect the squares 
sum to be 20. It's 18 because the seed element at arr[0] has no 
operation carried out on it other than the addition of the other 
elements to it.


More information about the Digitalmars-d-announce mailing list