uniq and array of enum members (That are all strings)

bauss jj_1337 at live.dk
Wed Jan 16 16:52:50 UTC 2019


On Wednesday, 16 January 2019 at 16:40:34 UTC, Alex wrote:
> On Wednesday, 16 January 2019 at 16:21:12 UTC, bauss wrote:
>> On Wednesday, 16 January 2019 at 16:12:28 UTC, H. S. Teoh 
>> wrote:
>>> On Wed, Jan 16, 2019 at 03:57:49PM +0000, bauss via 
>>> Digitalmars-d-learn wrote:
>>>> Is there a way to achieve the following:
>>> [...]
>>>> enum Foo : string
>>>> {
>>>>     a = "aa",
>>>>     b = "bb",
>>>>     c = "cc"
>>>> }
>>>> 
>>>> void main()
>>>> {
>>>>     auto a = [Foo.a, Foo.b, Foo.a, Foo.b, Foo.c];
>>>> 
>>>>     auto b = a.uniq;
>>>> 
>>>>     writeln(b);
>>>>     // Expected output: [a, b, c]
>>>>     // Outputs: [a, b, a, b, c]
>>>> }
>>>
>>> .uniq only works on adjacent identical elements.  You should 
>>> sort your array first.
>>>
>>> If you need to preserve the original order but eliminate 
>>> duplicates, then you could use an AA to keep track of what 
>>> has been seen. E.g.:
>>>
>>> 	bool[string] seen;
>>> 	auto b = a.filter!((e) {
>>> 			if (e in seen) return false;
>>> 			seen[e] = true;
>>> 			return true;
>>> 		});
>>>
>>>
>>> T
>>
>> Sorting will not work in my case though because it's an enum 
>> of strings that are not sorted alphabetically.
>>
>> Right now I'm doing it manually by a foreach in similar way 
>> you're using filter.
>>
>> I just feel like that's an overkill for something so trivial.
>
> yeah... searching by hand is somewhat inefficient.
> but this would work also with an enum, wouldn't it?
>
> ´´´
> import std.stdio;
>
> import std.algorithm : uniq;
> import std.array : array;
> import std.algorithm.sorting : sort;
>
> enum Foo : string
> {
>     a = "aa",
>     b = "bb",
>     c = "cc"
> }
>
> void main()
> {
>     enum a = [Foo.a, Foo.b, Foo.a, Foo.b, Foo.c];
>
>     auto b = a.sort.uniq;
>
>     writeln(b);
> }
> ´´´
>
> And if you have something like immutable, dup would help, maybe?

The problem with sorting is that the following:

[3,5,6,6,2,1,2,5,3]

will then become

[1,2,3,5,6]

or

[6,5,3,2,1]

and not:

[3,5,6,2,1]

which would be what you'd wanna use in some situations.

The important thing to know here is that the numbers are not a 
sequence, they're a set of numbers.

It's important the set doesn't have a change of order.

The filter example works and that's what I already did.

But something that is a bit better would be appreciated.

Sorting really makes no sense to make something unique.

It makes sense for the most "trivial" implementation, but not the 
most trivial usages.


More information about the Digitalmars-d-learn mailing list