Bug 12173 – Optional start value for std.algorithm.sum

Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2014-02-15T02:29:00Z
Last change time
2014-03-20T01:08:38Z
Assigned to
nobody
Creator
bearophile_hugs

Comments

Comment #0 by bearophile_hugs — 2014-02-15T02:29:57Z
The built-in Python sum() function supports a second optional argument that is the start, it's useful when you want to sum an iterable of values starting from a seed of another type (of different from zero): >>> sum([1, 2, 3]) 6 >>> sum([1, 2, 3], 2) 8 >>> sum([1, 2, 3], 0.0) 6.0 >>> sum([[1, 2], [3]], []) [1, 2, 3] This shows one use case for the same functionality in D: import std.algorithm: sum, reduce; import std.functional: curry; struct Foo { ubyte x; alias x this; } alias mySum = curry!(reduce!q{a + b}, 0); void main() { Foo[] arr; arr.mySum; // OK arr.sum; // Error //arr.sum(0); // Not supported } dmd 2.065beta3 gives: ..\dmd2\src\phobos\std\algorithm.d(1087,19): Error: cannot implicitly convert expression (0) of type int to Foo
Comment #1 by andrei — 2014-02-15T06:20:03Z
Doesn't an add outside the sum call do the same?
Comment #2 by bearophile_hugs — 2014-02-15T06:29:14Z
(In reply to comment #1) > Doesn't an add outside the sum call do the same? An add outside the sum doesn't solve the problem with Foo. Another example: long[] data = [...]; immutable total = data.sum(0.BigInt); If the longs are large enough this gives the correct result, unlike summing with longs.
Comment #3 by monarchdodra — 2014-03-20T01:08:38Z
This should be resolved. @bearophile_hugs: Do you want to stress test it?