Using "reduce" with user types

Kadir Erdem Demir via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 7 04:47:45 PST 2015


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.


More information about the Digitalmars-d-learn mailing list