digitalmars.D.bugs - [Issue 6835] New: Code pattern: uniq on an array
- d-bugmail puremagic.com (33/33) Oct 20 2011 http://d.puremagic.com/issues/show_bug.cgi?id=6835
- d-bugmail puremagic.com (10/10) Nov 28 2012 http://d.puremagic.com/issues/show_bug.cgi?id=6835
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 --- Comment #0 from bearophile_hugs eml.cc 2011-10-20 18:32:34 PDT --- "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
http://d.puremagic.com/issues/show_bug.cgi?id=6835 --- Comment #1 from bearophile_hugs eml.cc 2012-11-28 17:33:25 PST --- 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