Take

Lazily takes only up to n elements of a range. This is particularly useful when using with infinite ranges.

Unlike takeExactly, take does not require that there are n or more elements in input. As a consequence, length information is not applied to the result unless input also has length information.

  1. struct Take(Range)
  2. template Take(R)
    template Take (
    R
    ) if (
    isInputRange!(Unqual!R) &&
    (
    (
    !isInfinite!(Unqual!R) &&
    hasSlicing!(Unqual!R)
    )
    ||
    is(R T == Take!T)
    )
    ) {}

Return Value

At minimum, an input range. If the range offers random access and length, take offers them as well.

Examples

import std.algorithm.comparison : equal;

int[] arr1 = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
auto s = take(arr1, 5);
assert(s.length == 5);
assert(s[4] == 5);
assert(equal(s, [ 1, 2, 3, 4, 5 ][]));

If the range runs out before n elements, take simply returns the entire range (unlike takeExactly, which will cause an assertion failure if the range ends prematurely):

import std.algorithm.comparison : equal;

int[] arr2 = [ 1, 2, 3 ];
auto t = take(arr2, 5);
assert(t.length == 3);
assert(equal(t, [ 1, 2, 3 ]));

Meta