protocol for using InputRanges

Marco Leise Marco.Leise at gmx.de
Sun Mar 23 02:02:12 PDT 2014


Am Sat, 22 Mar 2014 17:50:34 -0700
schrieb Walter Bright <newshound2 at digitalmars.com>:

> It's become clear to me that we've underspecified what an InputRange is. The 
> normal way to use it is:
> 
>      while (!r.empty) {
>          auto e = r.front;
>          ... do something with e ...
>          r.popFront();
>      }
> 
> no argument there. But there are two issues:
> 
> 1. If you know the range is not empty, is it allowed to call r.front without 
> calling r.empty first?
> 
> If this is true, extra logic will need to be added to r.front in many cases.

Looking at ranges as a user with all the subjectivity it
entails, I'd expect .empty to be a read-only property, a
@safe-const-pure-nothrow candidate.

Actions that are not logically const are commonly encapsulated
in methods (as opposed to read-only properties like .empty) and
often also carry a verb in their name like "create", "update"
or "append".

> 2. Can r.front be called n times in a row? I.e. is calling front() destructive?
> 
> If true, this means that r.front will have to cache a copy in many cases.

On the other side of it were (IIRC) there are use cases for
return-by-ref on .front:

o .front gives access to a large struct. Return-by-ref can
  avoid a copy on the call site, but may result in
  several .front calls.
o .front is a view into some struct which holds system
  resources and providing a copy requires internals as in
  the File struct.

I both cases you deal with a range over value types that are
costly to copy and where "auto e = r.front;" is to be avoided.

I'm 100% unsure how to deal with this.

-- 
Marco



More information about the Digitalmars-d mailing list