[Issue 6835] New: Code pattern: uniq on an array
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Thu Oct 20 18:33:36 PDT 2011
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 at puremagic.com
ReportedBy: bearophile_hugs at eml.cc
--- Comment #0 from bearophile_hugs at 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: -------
More information about the Digitalmars-d-bugs
mailing list