Search⌘ K

Infinite Ranges and Functions that Return Ranges

Learn how to create infinite ranges in D programming using lazy evaluation to produce elements on demand. Understand functions that return range objects to simplify code and enhance flexibility, including examples like the Fibonacci series and the take function. This lesson helps you apply these concepts for efficient and practical data processing.

Infinite ranges

Another benefit of not storing elements as actual members is the ability to create infinite ranges.

Making an infinite range is as simple as having empty always return false. Since it is constant, empty need not even be a function and can be defined as an enum value:

enum empty = false; // ← infinite range

Another option is to use an immutable static member:

static immutable empty = false; // same as above

As an example of this, let’s design a range that represents the Fibonacci series. Despite having only two int members, the following range can be used as the infinite Fibonacci series:

D
struct FibonacciSeries
{
int current = 0;
int next = 1;
enum empty = false; // ← infinite range
int front() const {
return current;
}
void popFront() {
const nextNext = current + next; current = next;
next = nextNext;
}
}
void main() {}

Note: Although it is infinite, because the members are of type int, the elements of this Fibonacci series ...