uniq

Lazily iterates unique consecutive elements of the given range, which is assumed to be sorted (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 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

import std.algorithm.comparison : equal;
import std.algorithm.mutation : copy;

int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ];
assert(equal(uniq(arr), [ 1, 2, 3, 4, 5 ][]));

// Filter duplicates in-place using copy
arr.length -= arr.uniq().copy(arr).length;
assert(arr == [ 1, 2, 3, 4, 5 ]);

// Note that uniqueness is only determined consecutively; duplicated
// elements separated by an intervening different element will not be
// eliminated:
assert(equal(uniq([ 1, 1, 2, 1, 1, 3, 1]), [1, 2, 1, 3, 1]));

Meta