std.algorithm sort() and reverse() confusion

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 30 09:55:20 PST 2015


On Friday, January 30, 2015 18:42:57 FG via Digitalmars-d-learn wrote:
> On 2015-01-30 at 17:07, Paul wrote:
> > writeln("Sorted, reversed: ", reverse(myVals));
> >
> > Gives me...
> >
> > Error: template std.stdio.writeln cannot deduce function from argument types !()(string, void)
>
> As it should, because reverse returns nothing, void.
> But you may wonder what the design choice behind that was that reverse doesn't return the range itself while sort does (a SortedRange, specifically).

sort returns a different type rather than the original type, and that type
indicates that its sorted, and some algoritms are able to take advantage of
that. No algorithm is going to care that the data was reversed at some
point, so there's no benefit it returning a new range type from reverse. And
it's arguably better that a function that mutates something in place does
not return it - especially with ranges - because that very easily gives the
impression that the original is not mutated (since most range-based
functions don't alter their arguments - they just wrap them in a new range
type or return a portion of the original range).

Regardless, I think that the difference between sort and reverse comes down
to the fact that there's a definite benefit in returning a new type from
sort, whereas there is no such benefit with reverse, so there's no need to
return anything. So, whether it _should_ return anything is then a very
different question than it is with sort.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list