Function which returns a sorted array without duplicates
evilrat
evilrat666 at gmail.com
Sun Jan 22 07:33:01 UTC 2023
On Sunday, 22 January 2023 at 04:42:09 UTC, dan wrote:
> I would like to write a function which takes an array as input,
> and returns a sorted array without duplicates.
>
>
> ```d
> private S[] _sort_array( S )( S[] x ) {
> import std.algorithm;
> auto y = x.dup;
> y.sort;
> auto z = y.uniq;
> // Cannot just return z; this gives:
> // Error: cannot implicitly convert expression `z` of type
> // `UniqResult!(binaryFun, uint[])` to `uint[]`
uniq and other algorithms often returns a lazy range, you can
build an array by using `std.array.array()`
https://dlang.org/phobos/std_array.html#array
try something like this or just `return array(y.uniq);`
```d
private S[] _sort_array( S )( S[] x ) {
import std.algorithm;
import std.array;
return x.dup
.sort
.uniq
.array();
}
```
And IIRC you probably don't need `dup` as sort produces a lazy
range.
More information about the Digitalmars-d-learn
mailing list