On Friday, 2 August 2019 at 21:44:28 UTC, Jordan Wilson wrote:
Hello,
I don't quite understand why isEven is called twice in the 2nd
example?
auto isEven(int n) {
n.writeln;
return (n % 2) == 0;
}
void main() {
auto z = [1,2,3];
// outputs 1 2 3
z.map!(a => tuple!("number")(a))
.filter!(a => a.number.isEven)
.array;
// outputs 1 2 2 3
z.map!(a => tuple!("number","iseven")(a, a.isEven))
.filter!(a => a.iseven)
.array;
return;
}
Thanks,
Jordan
The way map is designed is to call its predicate on each front
call and filter calls it twice with the number 2.
https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d#L604
You can use "cache" to avoid the double front call on any range.
z.map!(a => tuple!("number","iseven")(a, a.isEven))
.cache
.filter!(a => a.iseven)
.array;