Function which returns a sorted array without duplicates

dan dan.hitt at gmail.com
Sun Jan 22 04:42:09 UTC 2023


I would like to write a function which takes an array as input, 
and returns a sorted array without duplicates.

In fact, i have a function which does this, but i think it may 
have some extra unnecessary steps.

```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[]`
       //
       // You also cannot just return cast( S[] ) z;
       //
       // Nor can you do:
       //  import std.conv;
       //  return to!( S[] )( z );
       typeof( x ) w;
       foreach ( v ; z ) w ~= v;
       return w;
     }
```

My only constraint is that i really want to keep the same 
signature (i.e., return an array, not sharing structure or 
storage with the input).

Here's the usage:

```d
     void main( ) {
       uint[] nums = [1, 3, 2, 5, 1, 4, 2, 8];
       auto sorted = _sort_array( nums );
       import std.stdio;
       writeln( "Input:  ", nums );
       writeln( "Output: ", sorted );
     }
```

Thanks in advance for any info!

dan


More information about the Digitalmars-d-learn mailing list