Using "reduce" with user types

Rikki Cattermole via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 7 05:05:08 PST 2015


On 8/02/2015 1:47 a.m., Kadir Erdem Demir wrote:
> I can use filter algorithm with my types easily.
>
> struct A
> {
>      string value;
>      int count;
> }
>
>
> void main(  string[] args )
> {
>      A[] aArr;
>      aArr  ~= A("HTTP", 3);
>      aArr  ~= A("HTTPS", 2);
>      aArr  ~= A("UNKNOWN_TCP", 4);
>      aArr.filter!( a => a.count == 2);
>
> But I couldn't compile when I want to use reduce algorithm. I simply
> want to get the sum of "count" variables inside of A[].
>
>      auto sum = aArr.reduce!((a,b) => a.count + b.count);
>
> The line above gives
>
> C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm.d(770): Error:
> cannot implicitly convert expression (__lambda3(result,
> front(_param_1))) of type int to A
> C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm.d(791): Error:
> template instance app.main.reduce!((a, b) => a.count +
> b.count).reduce!(A, A[]) error instantiating
> source\app.d(363):        instantiated from here: reduce!(A[])
>
> How can I achieve summing count variables inside A[]?
>
> Best Regards
> Kadir Erdem Demir
>
> Ps: The problem caused by my lack of D basics I admit, the reason I
> can't look up references more  before ask question I am in a bit tight
> schedule. Sorry for my dummy questions.

auto sum = aArr.map!`a.count`.reduce!((a,b) => a + b);

Not much difference.
I tried sum instead of reduce, but it didn't work. Wouldn't matter much 
as it is the same thing pretty much anyway.


More information about the Digitalmars-d-learn mailing list