From 6123ca33713ddd0dfcded8a46bcbef5c3e8e8a50 Mon Sep 17 00:00:00 2001 From: monarchdodra Date: Sun, 6 Apr 2014 19:33:33 +0200 Subject: [PATCH] Fix Issue 12434 - std.algorithm.sum of immutable array too https://d.puremagic.com/issues/show_bug.cgi?id=12434 Simply uses the inference's `Unqual` type as a seed, rather than the straight up result. Also add some unittesting while at it. --- std/algorithm.d | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/std/algorithm.d b/std/algorithm.d index 354ec4611a4..9e58d1e0f50 100644 --- a/std/algorithm.d +++ b/std/algorithm.d @@ -1090,10 +1090,10 @@ if (isInputRange!R && !isInfinite!R && is(typeof(r.front + r.front))) { alias E = Unqual!(ElementType!R); static if (isFloatingPoint!E) - typeof(E.init + 0.0) seed = 0; //biggest of double/real + alias Seed = typeof(E.init + 0.0); //biggest of double/real else - typeof(r.front + r.front) seed = 0; - return sum(r, seed); + alias Seed = typeof(r.front + r.front); + return sum(r, Unqual!Seed(0)); } /// ditto auto sum(R, E)(R r, E seed) @@ -1216,6 +1216,24 @@ unittest assert(sum(SList!double(1, 2, 3, 4)[]) == 10); } +unittest // 12434 +{ + immutable a = [10, 20]; + auto s1 = sum(a); // Error + auto s2 = a.map!(x => x).sum; // Error +} + +unittest +{ + import std.bigint; + immutable BigInt[] a = BigInt("1_000_000_000_000_000_000").repeat(10).array(); + immutable ulong[] b = (ulong.max/2).repeat(10).array(); + auto sa = a.sum(); + auto sb = b.sum(BigInt(0)); //reduce ulongs into bigint + assert(sa == BigInt("10_000_000_000_000_000_000")); + assert(sb == (BigInt(ulong.max/2) * 10)); +} + /** Fills $(D range) with a $(D filler). */