chain

Spans multiple ranges in sequence. The function chain takes any number of ranges and returns a Chain!(R1, R2,...) object. The ranges may be different, but they must have the same element type. The result is a range that offers the front, popFront, and empty primitives. If all input ranges offer random access and length, Chain offers them as well.

If only one range is offered to Chain or chain, the Chain type exits the picture by aliasing itself directly to that range's type.

chain
(
Ranges...
)
(
Ranges rs
)
if (
Ranges.length > 0 &&
&&
)

Parameters

rs Ranges

the input ranges to chain together

Return Value

Type: auto

An input range at minimum. If all of the ranges in rs provide a range primitive, the returned range will also provide that range primitive.

Examples

import std.algorithm.comparison : equal;

int[] arr1 = [ 1, 2, 3, 4 ];
int[] arr2 = [ 5, 6 ];
int[] arr3 = [ 7 ];
auto s = chain(arr1, arr2, arr3);
assert(s.length == 7);
assert(s[5] == 6);
assert(equal(s, [1, 2, 3, 4, 5, 6, 7][]));

Range primitives are carried over to the returned range if all of the ranges provide them

import std.algorithm.comparison : equal;
import std.algorithm.sorting : sort;

int[] arr1 = [5, 2, 8];
int[] arr2 = [3, 7, 9];
int[] arr3 = [1, 4, 6];

// in-place sorting across all of the arrays
auto s = arr1.chain(arr2, arr3).sort;

assert(s.equal([1, 2, 3, 4, 5, 6, 7, 8, 9]));
assert(arr1.equal([1, 2, 3]));
assert(arr2.equal([4, 5, 6]));
assert(arr3.equal([7, 8, 9]));

Due to safe type promotion in D, chaining together different character ranges results in a uint range.

Use byChar, byWchar, and byDchar on the ranges to get the type you need.

1 import std.utf : byChar, byCodeUnit;
2 
3 auto s1 = "string one";
4 auto s2 = "string two";
5 // s1 and s2 front is dchar because of auto-decoding
6 static assert(is(typeof(s1.front) == dchar) && is(typeof(s2.front) == dchar));
7 
8 auto r1 = s1.chain(s2);
9 // chains of ranges of the same character type give that same type
10 static assert(is(typeof(r1.front) == dchar));
11 
12 auto s3 = "string three".byCodeUnit;
13 static assert(is(typeof(s3.front) == immutable char));
14 auto r2 = s1.chain(s3);
15 // chaining ranges of mixed character types gives `dchar`
16 static assert(is(typeof(r2.front) == dchar));
17 
18 // use byChar on character ranges to correctly convert them to UTF-8
19 auto r3 = s1.byChar.chain(s3);
20 static assert(is(typeof(r3.front) == immutable char));

See Also

only to chain values to a range

Meta

Suggestion Box / Bug Report