How to sort a range
Edwin van Leeuwen via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Mar 9 01:15:01 PST 2016
On Wednesday, 9 March 2016 at 03:05:52 UTC, rcorre wrote:
> I was in a situation where I wanted to remove duplicates from
> an OnlyResult.
> To do this with uniq, I needed to sort it. OnlyResult doesn't
> satisfy the template constraints of sort, but this seems easy
> enough to fix. I made front, back, and opIndex return by ref.
> With this, the following compiles:
>
> assert(only(3,1,2).sort.equal(only(1,2,3)));
>
> However, it fails with:
>
> core.exception.AssertError at std/algorithm/sorting.d(1052):
> Failed to sort range of type OnlyResult!(int, 3LU)
>
> So, if you have a range for which sort compiles, what does it
> take to make sorting actually work?
>
> For reference, my two attempts were:
>
> https://github.com/rcorre/phobos/commit/d89b3cfab7a0938e178a506b4ceb8faae6ecbfe2
>
> https://github.com/rcorre/phobos/commit/512d9b8db6f311db6a9b6ccb077a691cec66ce70
I'm not sure why your fix didn't work, but generally I work
around this by converting the OnlyResult into an array:
import std.array : array;
assert(only(3,1,2).array.sort.equal(only(1,2,3)));
If you are looking for a lazy uniq that works on non sorted
ranges, I implemented one not to long ago:
http://github.com/BlackEdder/ggplotd/blob/master/source/ggplotd/range.d
More information about the Digitalmars-d-learn
mailing list