Search
View source code
Display the source code in std/algorithm/iteration.d from which this page was generated on github.
Report a bug
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

# Function `std.algorithm.iteration.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 `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.

``` auto uniq(alias pred, Range) (   Range r ) if (isInputRange!Range && is(typeof(binaryFun!pred(r.front, r.front)) == bool)); ```

## Parameters

NameDescription
pred Predicate for determining equivalence between range elements.
r An input range of elements to filter.

## Returns

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.

## Example

``````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;
writeln(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]));
``````