On Monday, 12 September 2022 at 16:26:01 UTC, Paul Backus wrote:
>On Monday, 12 September 2022 at 15:27:25 UTC, Steven Schveighoffer wrote:
>This isn't that crazy though. Checking against an absolute minimum or maximum has a cost, one which you may not want to incur.
For instance, uint.min is 0, this might be a common occurrence in some ranges. But int.min is -2billion. That might never occur in some ranges. Why waste time checking for something that will never occur in the name of "performance"? For many types and data sets, this is a net pessimization.
And there's not a way to do this shortcut via type wrapping. The only option is to alter the algorithm. Making it opt-in isn't a bad idea, but of course, the API could be badly designed.
It seems like maybe what's desired here is a version of fold
that allows for early termination. Like, instead of just returning the next accumulator value, the callback could return a tuple of the next value and a bool continue
, or something.
Could build it like this (not sure performance is great).
import std;
auto stoppingFold(alias stopCond, alias op, R)(R r) {
return r.cumulativeFold!op.until!(stopCond)(No.openRight).fold!((a,b)=>b);
}
void main() {
auto x = [1,2,4,3];
assert(x.stoppingFold!(x=>x==0,(a,b)=>min(a,b))==1);
x = [1,0,4,3];
assert(x.stoppingFold!(x=>x==0,(a,b)=>min(a,b))==1);
}