www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 6835] New: Code pattern: uniq on an array

reply d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=6835

           Summary: Code pattern: uniq on an array
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: Phobos
        AssignedTo: nobody puremagic.com
        ReportedBy: bearophile_hugs eml.cc



"Given an unsorted array, remove the duplicate items" is a common need. In
std.algorithm there are tools to perform this task with a very limited amount
of code:


import std.algorithm;
void main() {
    auto items = [3, 1, 5, 2, 3, 1];
    items.length -= copy(uniq(items.sort()), items).length;
    assert(items == [1, 2, 3, 5]);
}


(If you see better solutions feel free to add a comment.)

It's a single line of code, but in my opinion it's not obvious code, and it
repeats the name "items" three times (this makes it a bit bug prone).

Removing the duplicated items from an unsorted array is a common operation, so
maybe it's worth adding this pattern as a function, named like
std.array.sortedUnique or something similar.

(Other ways to create an array of unique items is to use hashing, but this is
better left to other functions.)

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Oct 20 2011
parent d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=6835




I meant something like this:

T[] unique(T)(T[] items) /*pure nothrow*/ {
    items.length -= items.sort().uniq().copy(items).length;
    return items;
}

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Nov 28 2012