to compose or hack?

Dennis dkorpel at gmail.com
Fri Jul 9 13:23:18 UTC 2021


On Wednesday, 7 July 2021 at 01:44:20 UTC, Steven Schveighoffer 
wrote:
> But it got me thinking, how often do people roll their own vs. 
> trying to compose using existing Phobos nuggets?

When there's not an obvious/simple way to do something by 
composing ranges, I tend to just give up and write procedural 
code instead. Yes, the resulting code is longer and more prone to 
logic bugs, but there's no limit to what you can do and it's 
easier to see what's going on at a lower level. I also don't tend 
to let composed ranges leave the function they were created in, I 
rather pass simple arrays around than complex objects depending 
on multiple inputs from different sources.

I don't know what the destination of your range is so this might 
not be applicable, but I'd probably end up writing a function 
with an OutputRange like this:
```D
void putRangeInterleaved(O, R, E)(ref O sink, R range, E 
separator) {
     import std.range.primitives: put;
     if (!range.empty) {
         put(sink, range.front);
         range.popFront();
     }
     foreach(ref elem; range) {
         put(sink, separator);
         put(sink, elem);
     }
}
```

I'm not trying to discourage anyone from writing range code, I'm 
just presenting this as an alternative in case it's useful.


More information about the Digitalmars-d-learn mailing list