Add these to Phobos?
Jonathan M Davis
jmdavisProg at gmx.com
Mon Oct 15 18:47:43 PDT 2012
On Tuesday, October 16, 2012 03:29:17 Mehrdad wrote:
> On Tuesday, 16 October 2012 at 00:42:55 UTC, Jonathan M Davis
>
> wrote:
> > On Monday, October 15, 2012 23:35:59 Mehrdad wrote:
> >> auto sorted(alias F = q{a < b}, SwapStrategy S =
> >> SwapStrategy.unstable, R)(R range)
> >> {
> >> auto arr = range.array();
> >> arr.sort!(F, S)();
> >> return arr;
> >> }
> >
> > What does this gain over sort? If you use sort
> >
> > auto result = sort(range);
> >
> > you get a SortedRange, which functions like find can take
> > advantage of, and
> > it's one line just like your sorted function. If you need a new
> > array for it,
> > then just call array.
> >
> > auto result = sort(array(range));
>
> Hmm, I didn't know 'sort' returns a value. That's very confusing
> since now I have no idea if it's mutating or not. Python has both
> sort and sorted, with clear meanings. (The goal was to make a
> non-mutating version that I could call functional.) Maybe we
> should clarify what sort exactly does and doesn't do...
It sorts the range that's passed in and then returns a SortedRange which wraps
the original range. The advantage of the SortedRange is that functions like
find will then know that it's sorted and can take advantage of that, but if you
just want to sort it, then just ignore the return value.
The documentation could be clearer about the return type, but it _is_ listed
as part of the signature. It should probably explain the rationale behind
returning SortedRange so that it's much clearer as to why you'd want to use
the return value rather than the original (now sorted) range.
Regardless, if you want to sort a copy of a range but keep the same type, then
all you have to do is
auto newRange = array(range);
sort(newRange);
And if SortedRange is changed to provide access to its underlying range via a
member named source (it was recently suggested by Andrei that we should
standardize on doing that where appropriate), then it could become a one-
liner:
auto result = sort(array(range)).source;
- Jonathan M Davis
More information about the Digitalmars-d
mailing list