algorithm's .filter!() by range key
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Feb 9 12:48:01 PST 2016
On 2/9/16 3:40 PM, Charles wrote:
> This seems to be true of any range function really... is there a way to
> access the key within my range?
>
> Example of what I want to do:
>
> auto x = [1,2,3,4,5];
> x.filter( x_key % 2 == 1 ).sum(); // sum odd elements in array
An array is not an indexed range. It only works with foreach by key
because of special foreach behavior.
What you want is std.range.enumerate:
import std.range;
import std.algorithm;
import std.stdio;
void main()
{
auto x = [1, 2, 3, 4, 5];
writeln(x.enumerate.filter!(a => a[0] % 2 == 1).map!(a =>
a[1]).sum); // 6
}
-Steve
More information about the Digitalmars-d-learn
mailing list