Range Redesign: Empty Ranges

H. S. Teoh hsteoh at qfbox.info
Wed Mar 6 18:07:22 UTC 2024


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

-- 
It's bad luck to be superstitious. -- YHL


More information about the Digitalmars-d mailing list