functional way doing array stuff/ lambda functions

Xinok via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Dec 12 15:50:55 PST 2015


On Saturday, 12 December 2015 at 23:36:43 UTC, cym13 wrote:
> ...
> So, in your example:
>
> int product(const ref int[] arr) {
>     import std.array:     array;
>     import std.algorithm: reduce;
>
>     arr = arr.reduce!((p, i) => p*i).array;
> }

A good post overall but you got reduce wrong. In D, reduce 
computes and returns the result immediately, not a lazy range. 
The following code is correct:

int product(const ref int[] arr) {
     import std.array:     array;
     import std.algorithm: reduce;

     return arr.reduce!((p, i) => p*i)();
}

Example: http://dpaste.dzfl.pl/fc2c2eab2d02


More information about the Digitalmars-d-learn mailing list