Adapting foreign iterators to D ranges

cc cc at nevernet.com
Tue Apr 23 06:02:18 UTC 2024


On Monday, 22 April 2024 at 11:36:43 UTC, Chloé wrote:
> I wish to adapt this interface to a forward range for use with 
> foreach and Phobos' range utilities. This amounts to 
> implementing empty, front, and popFront, in terms of next and 
> some state. But there is a choice to be made regarding the 
> first call to next.

Just to offer an alternative solution (since it sometimes gets 
overlooked), there is also the `opApply` approach.  You don't get 
full forward range status, and checking whether it's empty 
essentially requires doing something like std.algorithm 
`walkLength`, but if all you need is basic iteration, it can be a 
simpler solution:

```d
struct Range {
	private I iter;
	this(I iter) { this.iter = iter; }
	int opApply(scope int delegate(T* t) dg) {
		while (auto current = next(iter)) {
			if (auto r = dg(current))
				return r;
		}
		return 0;
	}
}
void main() {
	I someIter; // = ...
	auto range = Range(someIter);
	foreach (const t; range) {
		writeln(*t);
	}
}
```


More information about the Digitalmars-d-learn mailing list