[Issue 12169] sum(int[]) should return a int

d-bugmail at puremagic.com d-bugmail at puremagic.com
Wed Feb 19 13:52:12 PST 2014


https://d.puremagic.com/issues/show_bug.cgi?id=12169


monarchdodra at gmail.com changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |monarchdodra at gmail.com


--- Comment #7 from monarchdodra at gmail.com 2014-02-19 13:51:58 PST ---
(In reply to comment #0)
> import std.algorithm: sum;
> void main() {
>     int[] arr1;
>     auto arr2 = new int[arr1.sum];
> }
> 
> 
> With dmd 2.065beta3 gives:
> 
> test3.d(4,25): Error: cannot implicitly convert expression (sum(arr1)) of type
> long to uint
> 
> It seems a sum(int[]) gives a long. 99% of the cases this is not what I need.

Looks like I missed this when pulling. I even suggested this change:
https://github.com/D-Programming-Language/phobos/pull/1205/files#r9175954

I didn't realize the wordy code was actually doing something different. I would
have disagreed with it had I seen it.

(In reply to comment #2)
> If sum returned int for ranges of int, it would be 100% identical to
> std.algorithm.reduce. It's worth returning a 64-bit quantity because (a) 64-bit
> summing is about as fast as 32-bit summing, (b) the result can be cast to int
> if needed.
> 
> I propose we close this.

Wasn't the *point* for sum to be a specialization of reduce though? To be a
more convenient and more accurate/efficient result? I don't think doing minor
deviations as such is worth it.


(In reply to comment #3)
> This is OK, but an alternative (and in my opinion better) solution is in Issue
> 12173:
> 
> long sum2 = xs.sum(0L);

I think this is a nice and simple solution. It perfectly fits with the idea
that sum is reduce but specialized for numeric "+".

(In reply to comment #5)
> (In reply to comment #1)
> > I actually agree with you though. I'd expect sum!(int[]) to return int. In
> > general, I'd expect sum!(T[]) to return typeof(T.init + T.init), and respect
> > the language integral promotions.
> > ...
> 
> +1.
> 
> (In reply to comment #2)
> > It's worth returning a 64-bit quantity because
> > (a) 64-bit summing is about as fast as 32-bit summing,
> > (b) the result can be cast to int if needed.
> > 
> 
> IMO it's not worth the special casing. (Another thing I find questionable:
> extending range capabilities can reduce precision.) Allowing specification of
> the summation type is enough.

+1
+1

-- 
Configure issuemail: https://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list