October 06, 2018 Re: Is there a function for this? | ||||
---|---|---|---|---|
| ||||
Posted in reply to bauss | On 10/06/2018 01:07 PM, bauss wrote: > uniq will not work with, say a class and the class will require you to > implement opCmp, which you can't always do for classes you don't have > access to. Remembering that uniq works with a custom predicate, which should be sufficient in most of those case. > to use ..sort > and it requires opCmp again. Same for sort: works with a custom predicate. > Things like .group and .uniq should work without sorted > ranges. You can't always expect a range to be sorted to perform such > algorithms. Yes, it can be inconvenient but I'm under the impression that making algorithmic complexity a property of a function is agreed by most people. (For D, algorithmic complexity is in the documentations of functions; alas, uniq lacks it.) So, it's a good thing that we know that uniq is always O(N). Ali |
October 08, 2018 Re: Is there a function for this? | ||||
---|---|---|---|---|
| ||||
Posted in reply to bauss | On Saturday, 6 October 2018 at 13:17:22 UTC, bauss wrote: > Let's say you have a range with struct, but some of the struct are duplicates of each other. > > Is there a standard function in Phobos to remove duplicates? > > My first thought was "uniq", but it can't really do it like that, but it doesn't work. > > See: https://run.dlang.io/is/IcFEtw > > Is there another function in Phobos that perhaps would work? > > I can of course write my own function, but if there is a standard function that can do it, then I'd rather use that. Unless you want to implement opCmp() and do the .sort.uniq then, you may find this one-liner helpful: randomAccessRange.fold!((arr, elem) => arr.canFind(elem) ? arr : (arr ~= elem))((ElementType!(typeof(randomAccessRange))[]).init) Applied in your example: https://run.dlang.io/is/3KjRvY But yes, it is de facto a custom function. I don't think that there is a function in Phobos that will perfectly deduplicate your range without having it sorted before. |
Copyright © 1999-2021 by the D Language Foundation