www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - bool empty() const for ranges

reply Salih Dincer <salihdb hotmail.com> writes:
Hi All;

I have two questions that make each other redundant. Please 
answer one of them. I'm implementing ```bool empty() const``` for 
ranges as below:

```d
   bool empty() // const
   {
     bool result;

     if(!head)
     {
       result = true;
       fastRewind();
     }
     return result; // head ? false : true;
   }
```
* Is the const essential for ranges?
* Is it possible to rewind the pointer (```Node * head;```) when 
my head is empty by the const?

Thanks...
Nov 26 2021
next sibling parent Stanislav Blinov <stanislav.blinov gmail.com> writes:
On Friday, 26 November 2021 at 10:44:10 UTC, Salih Dincer wrote:

 * Is the const essential for ranges?
 * Is it possible to rewind the pointer (```Node * head;```) 
 when my head is empty by the const?
`empty` is not required to be `const`, but it is required to yield the same result if called multiple times without mutating the range (see https://dlang.org/phobos/std_range_primitives.html#.isInputRange). In other words, you really ought not to mutate the range in implementation of `empty`, or at least not to the extent you seem to want to.
Nov 26 2021
prev sibling parent Steven Schveighoffer <schveiguy gmail.com> writes:
On 11/26/21 5:44 AM, Salih Dincer wrote:
 Hi All;
 
 I have two questions that make each other redundant. Please answer one 
 of them. I'm implementing ```bool empty() const``` for ranges as below:
 
 ```d
    bool empty() // const
    {
      bool result;
 
      if(!head)
      {
        result = true;
        fastRewind();
      }
      return result; // head ? false : true;
    }
 ```
 * Is the const essential for ranges?
No, there is no specification of whether any range methods have to be const. As Stanislav says, it is only a requirement that subsequent calls return the same value as long as popFront has not been called.
 * Is it possible to rewind the pointer (```Node * head;```) when my head 
 is empty by the const?
If const is set, then any members are treated as const, and anything they point to are treated as const. So no. That being said, if `fastRewind` changes `empty` from true to false, the method is invalid. -Steve
Nov 26 2021