Why aren't Ranges Interfaces?

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 26 11:46:01 PDT 2015


On Friday, 26 June 2015 at 18:37:51 UTC, Jack Stouffer wrote:
> The only reason I can think of to not do it this way is the 
> weird distinction between structs and classes in D.

If anything, C++ is the weird one in having two keywords that 
mean the same thing...


But the reason comes down to three things:

1) They are! http://dlang.org/phobos/std_range_interfaces.html

That works in some cases, but not all. They aren't typically used 
though because of the other reasons:

2) interfaces have an associated runtime cost, which ranges 
wanted to avoid. They come with hidden function pointers and if 
you actually use it through them, you can get a performance hit.

In theory, the compiler could optimize that in some cases, making 
the interface syntax sugar for the isInputRange thing, but that 
still doesn't solve...

3) Ranges don't just meet an interface, they can also have other 
optional elements, like infiniteness or additional methods, that 
aren't expressible through inherited methods.

Some of that could be solved by having many interfaces together, 
but not all of it. Infiniteness, for example, is seen by the fact 
that empty is a constant false rather than a method. Perhaps you 
could reengineer this too, but then the interfaces don't look as 
clean as they otherwise would. (Look at how many variants there 
are in that std.range.interfaces, and it still doesn't actually 
cover everything!)


These two items together mean ranges typically don't fit the 
interface model well. If you're looking at a case where it is a 
good fit though, you can use the provided interfaces and wrappers.


More information about the Digitalmars-d-learn mailing list