protocol for using InputRanges
Steven Schveighoffer
schveiguy at yahoo.com
Wed Mar 26 19:55:11 PDT 2014
On Wed, 26 Mar 2014 22:48:16 -0400, Walter Bright
<newshound2 at digitalmars.com> wrote:
> On 3/26/2014 7:19 PM, Steven Schveighoffer wrote:
>> if(!r.empty)
>> {
>> auto r2 = map!(x => x * 2)(r);
>> do
>> {
>> auto x = r2.front;
>> ...
>> } while(!r2.empty);
>> }
>>
>> Should we be required to re-verify that r2 is not empty before using
>> it? It
>> clearly is not, and would be an artificial requirement (one that map
>> likely
>> would not enforce!).
>>
>> This sounds so much like a convention that simply won't be followed,
>> and the
>> result will be perfectly valid code.
>
> The idea is that there are three functions: empty, front, and popFront.
> The functionality of the range will be distributed between these 3
> functions. Different things being ranged over will naturally split their
> operations into the 3 functions in different ways.
>
> If the 3 functions can be called in any order, then extra logic has to
> be added to them to signal to each other. This slows things down.
>
> To write generic code calling ranges, it's necessary to stop assuming
> what is happening under the hood of empty, front, and popFront, and
> stick to the protocol.
OK, but it's logical to assume you *can* avoid a call to empty if you know
what's going on under the hood, no? Then at that point, you have lost the
requirement -- people will avoid calling empty because they can get away
with it, and then altering the under-the-hood requirements cause code
breakage later.
Case in point, the pull request I referenced, the author originally tried
to just use empty to lazily initialize filter, but it failed due to
existing code in phobos that did not call empty on filtered data before
processing. He had to instrument all 3 calls.
-Steve
More information about the Digitalmars-d
mailing list