.sort vs sort(): std.algorithm not up to the task?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jun 7 20:40:08 PDT 2017


On Thursday, June 08, 2017 03:15:11 Andrew Edwards via Digitalmars-d-learn 
wrote:
> On Thursday, 8 June 2017 at 02:31:43 UTC, Stanislav Blinov wrote:
> > On Thursday, 8 June 2017 at 02:25:17 UTC, Jonathan M Davis
> > wrote:
> >
> > Oh I see, the was error related to iteration, not sorting.
> >
> >> Ranges do not support iterating with an index. The workaround
> >> if you want to have an index with ranges and foreach, then you
> >> should use lockstep:
> >>
> >> http://dlang.org/phobos/std_range.html#lockstep
> >>
> >> e.g.
> >>
> >> foreach(i, v; lockstep(iota!size_t(0), s))
> >> {}
> >>
> >> or
> >>
> >> foreach(i, v; lockstep(iota(0), s))
> >> {}
> >
> > There's an enumerate():
> > https://dlang.org/phobos/std_range.html#enumerate
> >
> > import std.algorithm : sort;
> > import std.range : enumerate;
> >
> > foreach(i, k; aa.keys.sort().enumerate) {
> >
> >     /* ... */
> >
> > }
>
> Note that I already demonstrated the same functionality by
> importing "std.array: array" to get the job done. Neither
> lockstep nor enumerate gets me more benefit in this particular
> situation that array doesn't already get me. My question here is
> not whether the job can get done or not, it's simply why the
> extra work? I still have to import two modules, when before I
> didn't have to import any.
>
> I completely understand the differences between ranges and
> arrays... the thing is, I wasn't working with ranges but arrays
> instead. If sort understands a string or array as a sort of
> range, then given one of those entities, it should manipulate it
> internally and return it in it's original flavor. Given an array,
> return an array unless specifically told to do otherwise.

sort() returns a SortedRange so that other algorithms can know that the
range is sorted and take advantage of that. If sort() returned the original
range type, it would be detrimental for other algorithms. But you can just
use the array directly again after calling sort or call release() on the
SortedRange to get the array out of it.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list