to compose or hack?
Steven Schveighoffer
schveiguy at gmail.com
Wed Jul 7 01:44:20 UTC 2021
So I have this situation where I need to split a string, then where the
splits are, insert a string to go between the elements making a new
range, all without allocating (hopefully).
Looking around phobos I found inside the documentation of
[roundRobin](https://dlang.org/phobos/std_range.html#.roundRobin)
something that does *exactly* what I'm looking for.
Except... the provided `interleave` function iterates the original range
twice, which means 2x the searching calls for splitter. Why does it do
this? Because `roundRobin` will keep going as long as ANY range still
has data left, so you need to make the "interleaving" range stop when
the first one stops.
After struggling to think up ways to compose this (hm.., can I make the
ranges share a stopping point?) without the 2x penalty, I just decided
to write my own interleave range which does exactly what I am looking for:
```d
auto interleave(R, U)(R src, U middles) if (isInputRange!R && is(U ==
ElementType!R))
{
static struct Result
{
R src;
U middles;
bool between = false;
auto front() {
assert(!empty);
return between ? middles : src.front;
}
void popFront() {
assert(!empty);
if(between)
between = false;
else
{
src.popFront;
between = true;
}
}
bool empty()
{
return src.empty;
}
}
return Result(src, middles);
}
```
This is pretty minimal, but does what I want it to do. Is it ready for
inclusion in Phobos? Not by a longshot! A truly generic interleave would
properly forward everything else that the range supports (like `length`,
`save`, etc).
But it got me thinking, how often do people roll their own vs. trying to
compose using existing Phobos nuggets? I found this pretty satisfying,
even if I didn't test it to death and maybe I use it only in one place.
Do you find it difficult to use Phobos in a lot of situations to compose
your specialized ranges?
Oh, and if you do know of a better way to compose the range that doesn't
require the double iteration, I'd be interested in seeing it.
-Steve
More information about the Digitalmars-d-learn
mailing list