Function take

Takes n elements from range.

auto take(R) (
  R range,
  size_t n
)
if (isInputRange!R);

If range doesn't have n elements, the resulting range spans all elements of range.

take is particulary useful with infinite ranges. You can take ` n elements from such range and pass the result to an algorithm which expects a finit range.

Parameters

NameDescription
R Type of the adapted range.
range The range to take the elements from.
n The number of elements to take.

Returns

A range containing maximum n first elements of range.

See Also

takeExactly.

Example

static struct InfiniteRange
{
    private size_t front_ = 1;

    enum bool empty = false;

    @property size_t front() @nogc nothrow pure @safe
    {
        return this.front_;
    }

    @property void front(size_t i) @nogc nothrow pure @safe
    {
        this.front_ = i;
    }

    void popFront() @nogc nothrow pure @safe
    {
        ++this.front_;
    }

    size_t opIndex(size_t i) @nogc nothrow pure @safe
    {
        return this.front_ + i;
    }

    void opIndexAssign(size_t value, size_t i) @nogc nothrow pure @safe
    {
        this.front = i + value;
    }

    InfiniteRange save() @nogc nothrow pure @safe
    {
        return this;
    }
}

auto t = InfiniteRange().take(3);
assert(t.length == 3);
assert(t.front == 1);
assert(t.back == 3);

t.popFront();
assert(t.front == 2);
assert(t.back == 3);

t.popBack();
assert(t.front == 2);
assert(t.back == 2);

t.popFront();
assert(t.empty);