protocol for using InputRanges

Steven Schveighoffer schveiguy at yahoo.com
Mon Mar 24 04:52:39 PDT 2014


On Sun, 23 Mar 2014 05:34:26 -0400, Szymon Gatner <noemail at gmail.com>  
wrote:

> On Sunday, 23 March 2014 at 00:50:34 UTC, Walter Bright wrote:
>>
>> 1. If you know the range is not empty, is it allowed to call r.front  
>> without calling r.empty first?
>
> IMO: yes. Logic of empty() sould be const and not have side effects.

Here is the crux of the issue. I think aside from Walter's question, we  
have situations where it is expensive to construct each value of a range.  
For a range that is never used, that is an expense that you don't have to  
pay.

There was a post a little while ago about how File.byLine reads the first  
line on construction. Consider the case where stdin.byLine needs to be  
constructed, but not *iterated* before writing some information to stdout.  
This gives us a predicament that the first line has to be available before  
you can output any instructions. As we all know, stdin will block on first  
read, unless you piped in a file or something. This makes an interactive  
program simply incorrect.

 From the library point of view, caching the first line on construction is  
the most sensible thing -- This allows empty, front, and popFront to all  
be consistent across the entire iteration. Making empty or front do  
something different on the first access requires awkward machinery (a  
boolean indicating it should do so, plus a check every call thereafter).  
But from the user's point of view, sometimes you want lazy access to the  
first element, for logical reasons.

I think in light of such possibilities, empty and front should not have to  
be const or pure. Logically, it can be viewed that way, but not  
technically.

-Steve


More information about the Digitalmars-d mailing list