Component Programming in D

Martin Friesen mhfriesen at shaw.ca
Wed Oct 3 12:06:07 PDT 2012


On Wednesday, 3 October 2012 at 01:40:05 UTC, ixid wrote:
> 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.

Pernicious? Bug? I've never used D, but it looks obvious that 
arr.reduce does what it's compile time parameter promises with 
'a' as the "seed". It seems that using [0,1,2,3,4,5] or 
[0]~[1,2,3,4,5] or ([0]~arr).reduce! would have reflected a more 
general "sum of squares" idea simply enough.


More information about the Digitalmars-d-announce mailing list