Proposal for SentinelInputRange
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Thu Feb 28 22:19:17 PST 2013
A use case that comes immediately to mind: a sentinal range that,
yes wraps, an infinite (but predictable!) range, effectively
allowing you to take a head-slice of the infinite range.
auto foo = infiniteRangeOfEvenNumbers();
auto upto1000 = GenericSentinalInputRange!1000( foo );
Yes, in this contrived example, one could use take(), but what
about an infinite range that can be predicted to always hit
certain points, but is not restricted to those points?
As for other cases of sentinal ranges wrapping others, in
particular arrays, there seems to be no mention of what I expect
would be the most common use case: wherein the code which
instantiates the sentinal range can guarantee that the sentinal
already exists in the source data/range, because it *put* it
there -- the lexer remains a fine example, as it tacks the
terminating \0 on. There is no need for extra checks, because
there is no need to *replace* the source data with the sentinel.
It is naturally reduced to it through normal processing.
Other apparent use cases: list processing (Andrei has mentioned
this already, for singly-linked lists); protocol processing with
a terminate-transaction message, or similar; state sequences
(which can include lexers and parsers, as it happens). This is
just off the top of my head.
Can we do it now, without a special type? Yes. Is there any
gain from introducing the special type, versus what can be done
now? Yes, sometimes. Is there any harm in introducing the
special type? No. Is there significant cost in adding it? No.
Should this just be handled by compiler optimization? Yes and no
-- yes in that a great compiler should be able to optimize *many*
(but not neccessarily all!) cases; but no in that including
implementation details in a language spec is usually bad mojo.
Of course, any compiler that could optimize the common cases,
could at least as readily optimize the use of a sentinal range --
in fact, I'd expect it to open optimization paths for some of the
corner cases that might otherwise not have been optimized.
So... I could live without a standard sentinal range concept
(have so far, using sentinal injection with input ranges, which
as Walter pointed out is really an incorrect use (abuse?) of
input ranges), but I also know I'd be using it if it existed (and
thereby cleaning up some code versus how I do it now).
More information about the Digitalmars-d
mailing list