InputRange for data structure without order?

monkyyy crazymonkyyy at gmail.com
Tue Jun 3 18:53:24 UTC 2025


On Tuesday, 3 June 2025 at 16:03:15 UTC, Andy Valencia wrote:
> I have a Set data structure which has no concept of order; its 
> members are stored and can be searched efficiently based on 
> their hash.
>
> I have a situation where chain()'ing them together would be 
> convenient, but InputRange requires front() and popFront().  
> There really _isn't_ a front, and creating a new Set with an 
> element removed would be unpleasant.
>
> What would be the best way to iterate across a list of such 
> Set's?  For now I'm just going to write the explicit loop.
>
> Thanks!
> Andy

```d
import std;
struct myset{
	bool has3;
	bool has5;
	auto opBinary(string s:"+")(typeof(this) a){
		return myset(has3||a.has3,has5||a.has5);
	}
	alias chain=opBinary!"+";
	int front(){
		if(has3){ return 3;}
		if(has5){ return 5;}
		assert(0);
	}
	void popFront(){
		if(has3){has3=false; return;}
		has5=false;
	}
	bool empty()=>( ! has3) && ( ! has5);
}
myset toset(R)(R r){
	myset o;
	foreach(i;r){
		if(i==3){o.has3=true;}
		if(i==5){o.has5=true;}
	}
	return o;
}
unittest{
	myset a,b;
	a.has3=true;
	b.has5=true;
	(a+b).writeln;
	
	a.chain(a).chain(a).writeln;
	b.chain(b).chain(b).writeln;
	a.chain(b).writeln;
	
	auto c=a+b;
	c.map!(a=>a*2).writeln;
	iota(10).filter!(a=>a==3).toset.chain(
		iota(10).filter!(a=>a!=3).toset)
		.writeln;
}
```

You can overload the names inside the datastructure and eagerly 
lower it as needed
if you need it in something nested I have some more workarounds, 
but they start to suck.


More information about the Digitalmars-d-learn mailing list