chunkBy implementation
Steven Schveighoffer
schveiguy at gmail.com
Tue Sep 29 21:33:35 UTC 2020
Here is the chunkBy implementation for an array:
https://github.com/dlang/phobos/blob/4d7e5829cb60946fefad84d066de948e813eb6f5/std/algorithm/iteration.d#L2057
Complete with RefCounted allocations and everything. The whole works!
Warning, do not pass this into std.array.array, it really isn't what you
want to do.
Here's a simple range that slices an array according to a predicate:
struct SliceBy(alias pred, R)
{
R remaining;
size_t nextIdx;
auto front() { return remaining[0 .. nextIdx]; }
void popFront() {
remaining = remaining[nextIdx .. $];
if(remaining.length == 0)
return;
nextIdx = 1;
while(nextIdx < remaining.length && pred(remaining[nextIdx -
1], remaining[nextIdx]))
++nextIdx;
}
bool empty() { return remaining.empty; }
}
No allocations, no RefCounted. The range elements have the same
properties as the original (random access, etc.). I can squash this into
std.array.array and it works as expected (i.e. I get an R[]). I can add
forward and bidirectional range primitives if I wanted to (and all the
other machinery that would be required to get it phobos-ready), but I
don't need all that for my purposes, I just need a foreachable thingy.
But why is this not something that is already in there? Is there a
reason we want to call the predicate all over again if you process a
group multiple times? Is there a reason we aren't taking advantage of
slicing when available?
Just trying to figure out the reasoning behind the complexity.
-Steve
More information about the Digitalmars-d
mailing list