[Issue 15722] std.algorithm sum should favour speed

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Fri Feb 26 13:09:48 PST 2016


https://issues.dlang.org/show_bug.cgi?id=15722

--- Comment #3 from Cédric Picard <cpicard at openmailbox.org> ---
(In reply to adamsibson from comment #2)
> (In reply to Cédric Picard from comment #1)
> > I would rather have a comment in the doc saying "Pairwise summation is
> > slower than naive one, for performance use reduce!((a, b) => a+b)", adding a
> > new function for that seems overkill.
> 
> Why? There seems to be a strong resistance to convenience functions in the
> library, one that is unnecessary. There is a significant difference between
> arr.sum and arr.reduce!((a, b) => a + b) in usability. In writing this post
> I initially forgot I have do put a, b in an additional set of brackets, it's
> complicated and not particularly user-friendly.

I don't feel like I'm blindly refusing something because it's a convenience
function. The thing is, how do you want to do it?

First of all, for comparison, what exists today:

    [1, 2, 3].reduce!"a+b";  // Not pairwise, considered bad code... meh.
    [1, 2, 3].reduce!((a, b) => a+b); // Not pairwise
    [1, 2, 3].reduce!sum; // Pairwise

Add a "sum" overload that takes a range? It would be feasible but ambiguous:

    [1, 2, 3].sum        // Not pairwise
    [1, 2, 3].reduce!sum // Pairwise, non obvious at all

Add a new function? "sum" is already taken and changing it would only break
code uselessly (and it would be hard to explain that "sum" now means something
slightly different and that the old meaning is now sumPairwise) so you'd have
to add something like "simpleSum"... Feasible but not so convenient for a
convenience function.

Add a flag in parameters that defaults to not-pairwise? Good for the default
but really complicated for pairwise summation:

    sum(1, 2);
    [1, 2, 3].reduce!sum;
    sum(1, 2, summation.pairwise);
    [1, 2, 3].reduce!((a, b) => sum(a, b, summation.pairwise));

Add a compile-time flag that defaults to not-pairwise? Not satisfying IMHO.

    sum(1, 2);
    [1, 2, 3].reduce!sum;
    sum!(summation.pairwise)(1, 2);
    [1, 2, 3].reduce!(sum!(summation.pairwise));

Quite frankly, given the other choices, I think the default isn't that bad. 
Otherwise my preference would go to the overload but I'm sure it would be
refused for being too ambiguous.

So this is a real question: how would you like to see it done?

--


More information about the Digitalmars-d-bugs mailing list