Seed Value for reduce function
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Sun Dec 10 01:42:46 UTC 2017
On Sunday, December 10, 2017 00:39:07 Vino via Digitalmars-d-learn wrote:
> Hi All,
>
> Request you help on how to add the seed value for the reduce
> function, below is the scnerio
>
> Program 1 : Works
>
> import std.algorithm;
> void main () {
> int[] ara = [1,2 ,3];
> auto sum1 = ara.reduce!((a,b) => a + b);
> writeln(sum1);
> }
>
> Program 2: Works
> void main () {
> int[] arrb = [];
> auto sum1 = reduce!((a,b) => a + b)(0 , arb);
> writeln(sum1);
> }
>
> So how to add seed value for the below code as same as program 1
> without calling the seed value and array at the end rather than
> calling it as arc.reduce!((a,b) => a + b);
>
> void main () {
> int[] arc = [];
> auto sum1 = arc.reduce!((a,b) => a + b);
> writeln(sum1);
> }
So, basically, you're trying to use reduce with UFCS, and that doesn't work
in the case where you want to provide an explicit seed value? In that's the
case, then use fold:
https://dlang.org/phobos/std_algorithm_iteration.html#fold
reduce predates UFCS in the language, so there wasn't really a reason to
prefer having the range as the first argument at the time. fold has since
been added to fix that problem. They're identical except for the order of
arguments (in fact, fold just calls reduce internally).
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list