uniq

Lazily iterates unique consecutive elements of the given range (functionality akin to the _uniq system utility). Equivalence of elements is assessed by using the predicate pred, by default "a == b". The predicate is passed to std.functional.binaryFun, and can either accept a string, or any callable that can be executed via pred(element, element). If the given range is bidirectional, uniq also yields a bidirectional range.

uniq
(
alias pred = "a == b"
Range
)
(
Range r
)
if (
isInputRange!Range &&
is(typeof(binaryFun!pred(r.front, r.front)) == bool)
)

Parameters

pred

Predicate for determining equivalence between range elements.

r
Type: Range

An input range of elements to filter.

Return Value

Type: auto

An input range of consecutively unique elements in the original range. If r is also a forward range or bidirectional range, the returned range will be likewise.

Examples

1 import std.algorithm.comparison : equal;
2 import std.algorithm.mutation : copy;
3 
4 int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ];
5 assert(equal(uniq(arr), [ 1, 2, 3, 4, 5 ][]));
6 
7 // Filter duplicates in-place using copy
8 arr.length -= arr.uniq().copy(arr).length;
9 assert(arr == [ 1, 2, 3, 4, 5 ]);
10 
11 // Note that uniqueness is only determined consecutively; duplicated
12 // elements separated by an intervening different element will not be
13 // eliminated:
14 assert(equal(uniq([ 1, 1, 2, 1, 1, 3, 1]), [1, 2, 1, 3, 1]));

Meta