www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 12173] New: Optional start value for std.algorithm.sum

reply d-bugmail puremagic.com writes:
https://d.puremagic.com/issues/show_bug.cgi?id=12173

           Summary: Optional start value for std.algorithm.sum
           Product: D
           Version: D2
          Platform: x86
        OS/Version: Windows
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: Phobos
        AssignedTo: nobody puremagic.com
        ReportedBy: bearophile_hugs eml.cc


--- Comment #0 from bearophile_hugs eml.cc 2014-02-15 02:29:57 PST ---
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])



 sum([1, 2, 3], 2)



 sum([1, 2, 3], 0.0)



 sum([[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 -- Configure issuemail: https://d.puremagic.com/issues/userprefs.cgi?tab=email ------- You are receiving this mail because: -------
Feb 15 2014
next sibling parent d-bugmail puremagic.com writes:
https://d.puremagic.com/issues/show_bug.cgi?id=12173


Andrei Alexandrescu <andrei erdani.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |andrei erdani.com


--- Comment #1 from Andrei Alexandrescu <andrei erdani.com> 2014-02-15 06:20:03
PST ---
Doesn't an add outside the sum call do the same?

-- 
Configure issuemail: https://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Feb 15 2014
prev sibling parent d-bugmail puremagic.com writes:
https://d.puremagic.com/issues/show_bug.cgi?id=12173



--- Comment #2 from bearophile_hugs eml.cc 2014-02-15 06:29:14 PST ---
(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. -- Configure issuemail: https://d.puremagic.com/issues/userprefs.cgi?tab=email ------- You are receiving this mail because: -------
Feb 15 2014