Issue 10024 - product function
Summary: product function
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2013-05-03 16:41 UTC by bearophile_hugs
Modified: 2024-12-01 16:17 UTC (History)
0 users

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2013-05-03 16:41:41 UTC
I suggest to add a product() function to Phobos, similar to sum().

This benchnarking code shows an algorithm better than the naive one when it's used on bigints:


import std.stdio, std.bigint, std.algorithm, std.random;

T product1(T)(T[] seq) {
    typeof(return) result = 1;
    foreach (s; seq)
        result *= s;
    return result;
}

T product2(T)(T[] seq) { // faster
    if (seq.length < 50) {
        typeof(return) result = 1;
        foreach (s; seq)
            result *= s;
        return result;
    } else {
        immutable mid = seq.length / 2;
        return product2(seq[0 .. mid]) * product2(seq[mid .. $]);
    }
}

void main() {
    BigInt[2 ^^ 16] items;
    foreach (i, ref b; items)
        b = i + 1;
    items[].randomShuffle;

    //auto r = items.product1;
    auto r = items.product2;
    //r.writeln;
}


What about T == InputRange?
Comment 1 dlangBugzillaToGithub 2024-12-01 16:17:27 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/phobos/issues/9971

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB