On Mon, Feb 13, 2023 at 06:04:40PM +0000, Matt via Digitalmars-d-learn wrote:
> Obviously, there is no "set" object in D,

Actually, bool[T] could be used as a set object of sorts. Or even
void[0][T], though that's a little more verbose to type. But this can be
aliased to something nicer (see below).


> but I was wondering what the quickest way to remove duplicates from an
> array would be. I was convinced I'd seen a "unique" method somewhere,
> but I've looked through the documentation for std.array, std.algorithm
> AND std.range, and I've either missed it, or my memory is playing
> tricks on me. That, or I'm looking in the wrong place entirely, of
> course

Try this:

-------------------------snip-------------------------
import std;
auto deduplicate(R)(R input)
        if (isInputRange!R)
{
        alias Unit = void[0];
        enum unit = Unit.init;
        Unit[ElementType!R] seen;
        return input.filter!((e) {
                if (e in seen) return false;
                seen[e] = unit;
                return true;
        });
}
unittest {
        assert([ 1, 2, 3, 4, 2, 5, 6, 4, 7 ].deduplicate.array ==
                [ 1, 2, 3, 4, 5, 6, 7 ]);
        assert([ "abc", "def", "def", "ghi", "abc", "jkl" ].deduplicate.array ==
                [ "abc", "def", "ghi", "jkl" ]);
}
-------------------------snip-------------------------


T

-- 
Маленькие детки - маленькие бедки.

Reply via email to