std.algorithm.reduce on an array of structs

via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 11 06:30:03 PDT 2014


On Thursday, 11 September 2014 at 13:28:37 UTC, Marc Schütz wrote:
> 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.
>
> I think you want to use `filter()` (for both Thing and uint), 
> not `reduce()`.

Scratch that, `filter()` doesn't make sense here, of course. The 
rest is still valid:

> The former produces a range with only the elements that match 
> the predicate, while the latter produces _one_ element 
> according to the given rules, e.g.
>
>     my_int_array.reduce!((result,a) => result+a);
>
> produces the sum of all elements. In your example, the first 
> use only compiles because `bool` happens to be implicitly 
> convertible to `uint`.


More information about the Digitalmars-d-learn mailing list