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.

take
(
R
)
(,
size_t n
)
if (
isInputRange!(Unqual!R)
)

Parameters

input R

an input range to iterate over up to n times

n size_t

the number of elements to take

Return Value

Type: Take!R

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