std.algorithm.reduce on an array of structs
Daniel Kozak via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Sep 11 06:27:38 PDT 2014
On Thursday, 11 September 2014 at 13:06:05 UTC, Colin wrote:
> I have this test code:
>
> struct Thing {
> uint x;
> }
>
> void main(){
> uint[] ar1 = [1, 2, 3, 4, 5];
> auto min1 = ar1.reduce!((a,b) => a < b);
> writefln("%s", min1); // prints 1 as expected
>
> Thing[] ar2 = [Thing(1), Thing(2), Thing(4)];
> auto min2 = ar2.reduce!((a,b) => a.x < b.x); // <- Wont
> Compile
> writefln("%s", min2);
> }
>
> The line with "Wont Compile" on it has this error message:
> /usr/include/dmd/phobos/std/algorithm.d(770): Error: cannot
> implicitly convert expression (__lambda2(result,
> front(_param_1))) of type bool to Thing
> /usr/include/dmd/phobos/std/algorithm.d(791): Error: template
> instance t.main.reduce!((a, b) => a.x < b.x).reduce!(Thing,
> Thing[]) error instantiating
> t.d(16): instantiated from here: reduce!(Thing[])
>
>
> Any idea what I'm doing wrong here?
> To me, the operation on ar2 should be pretty much identical to
> ar1, except for the use of the struct.
You are try to put uint to Thing. This is corect version:
import std.stdio;
import std.algorithm;
struct Thing {
uint x;
}
void main(){
uint[] ar1 = [1, 2, 3, 4, 5];
auto min1 = ar1.reduce!((a,b) => a < b);
writefln("%s", min1); // prints 1 as expected
Thing[] ar2 = [Thing(1), Thing(2), Thing(4)];
auto min2 = ar2.reduce!((a,b) => a.x < b.x ? a : b); // <-
Wont Compile
writefln("%s", min2);
}
More information about the Digitalmars-d-learn
mailing list