protocol for using InputRanges

Walter Bright newshound2 at digitalmars.com
Thu Mar 27 16:52:52 PDT 2014


On 3/27/2014 2:46 PM, Steven Schveighoffer wrote:
> In the cases where you know there is input, that's not true.

The range doesn't know what you know.

> What I am protesting is the idea that you *know* input exists, you must still call empty.
> Front is enough in that case.

You can't use that on generic code, because generic code cannot assume that 
front will not fail.


>> What is wrong with following the protocol? Why must we introduce all these
>> caveats for ranges, like streams not working, front that can fail, can't do C#
>> style LINQ, etc.? For what gain?
>
> There is no gain to requiring empty on ranges where you logically prove they are
> not empty. It's a wasted call. For things where you're not sure if they are
> empty or not (e.g. an input file), of course empty is required to be called, and
> of course it may do some processing to determine that. But I would only expect
> that on the first call. Subsequent checks would already be done by popFront.

I know that you want to get rid of empty. But getting rid of empty means that 
front may fail. This is why there is an empty, and any generic code MUST respect 
that.

What you can do is, in your range:

     enum empty = true;

and then it won't cost anything to call it.


> I mean, if you are calling empty regularly, because you aren't sure whether the
> elements are there. That's not always the case, sometimes you are sure the
> elements are there.

Then use an adapter range that has:

    enum empty = true;

and forwards the front and popFront() calls to its parameter. You'll get the 
optimization you want, and won't violate protocol.


> Requiring a call to empty to do anything other than to check
> whether a range is empty, is just plain wrong.

There are solid reasons to require it (i.e. streams), and you've responded that 
ranges needn't even support streams. If I have interpreted your position 
correctly, I cannot agree with it.



More information about the Digitalmars-d mailing list