D Language Ranges Making a new Input Range type


Example

The InputRange concept has three functions, example:

struct InputRange(T) {
    @property bool empty();
    @property T front();
    void popFront();
}

In short, a way to

  1. check if the range is empty
  2. get the current element
  3. move to the next element

To make our own type a InputRange, we must implement these three functions. Let's take a look at the infinite sequence of squares.

struct SquaresRange {
    int cur = 1;

    @property bool empty() {
        return false;
    }

    @property int front() {
        return cur^^2;
    }

    void popFront() {
        cur++;
    }
}

See the D tour for an example with Fibonacci.