Range Redesign: Empty Ranges

Meta jared771 at gmail.com
Wed Mar 6 20:23:52 UTC 2024


On Wednesday, 6 March 2024 at 18:07:22 UTC, H. S. Teoh wrote:
> On Wed, Mar 06, 2024 at 05:51:11PM +0000, Meta via 
> Digitalmars-d wrote:
>> On Wednesday, 6 March 2024 at 17:32:17 UTC, H. S. Teoh wrote:
>> > Every time this topic comes up, class-based ranges become 
>> > the whipping boy of range design woes.  Actually, they serve 
>> > an extremely important role: type erasure, which is critical 
>> > when you have code like this: ...etc.
>> 
>> This would be a complete non-issue if we had language-level 
>> sumtypes:
>> 
>> ```
>> 	sumtype { R, S } myRangeFunc(R,S)(R range1, S range2) {
>> 		if (runtimeDecision()) {
>> 			return range1;
>> 		} else {
>> 			return range2;
>> 		}
>> 	}
>> ```
>> 
>> std.sumtype can also do this, the ergonomics just aren't as 
>> nice.
>
> No, it doesn't work the way you think it would. The returned 
> range must behave like an input range (forward, etc.), as a 
> single entity, because the caller doesn't and shouldn't know or 
> care whether the returned value is a sumtype or not.  It must 
> be able to just call .front, .empty, .popFront on the result 
> without any explicit unwrapping.
>
> You can't do that with a sumtype, because you need to unwrap 
> first. And even if you make unwrapping implicit, so that a 
> sumtype allows operations common to all underlying types, there 
> are implementational difficulties.  Calling e.g.  .front on a 
> sumtype potentially accessing two completely incompatible 
> functions. For example, if R.empty is a function but S.empty is 
> a field, there is no sane way to implement the sumtype in such 
> a way that the caller could just access .empty without 
> introducing a runtime switch into every range API call. (And 
> even if you were to implement things in this convoluted way, 
> there are unaddressed difficulties of what .empty on a sumtype 
> might mean if it refers to two completely incompatible things, 
> like a 3-parameter function in R and an alias to a symbol in S. 
> What would mySumtype.empty actually compile to in that case?)
>
>
> T

Ah, you're right. There is really no way to do this in a 
completely flexible way in current D, if you also want to have 
value range semantics. Couldn't we somehow fit RefRange into the 
current range hierarchy somewhere, and provide primitives to make 
it more difficult to shoot yourself in the foot?


More information about the Digitalmars-d mailing list