Function which returns a sorted array without duplicates

dan dan.hitt at gmail.com
Sun Jan 22 23:26:45 UTC 2023


On Sunday, 22 January 2023 at 07:33:01 UTC, evilrat wrote:
> 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.

Thanks evilrat, this works perfectly, and is just the right style 
too (imvho).

So what i was missing was std.array.

Thanks also Ali for your subsequent clarifying remarks.

(Probably what i need to do is read a good book on the std 
library for d.)

dan

Thanks also Ali for your subsequent remarks


More information about the Digitalmars-d-learn mailing list