randomAccessRange.sort() vs randomAccessRange.array.sort()

bearophile bearophileHUGS at lycos.com
Mon Mar 4 14:59:00 PST 2013


deed:

> auto mappedThenSorted = mapped.sort();           // Error
> auto mappedThenSorted = mapped.array.sort();     // Works (and 
> used in examples)
>
>
> What am I missing in the documentation?

When you try to sort mapped, the D compiler spits out a error 
message that shows the complex template constraint of sort. You 
are calling sort using the default unstable algorithm.

Here I show the requirements for the unstable sort:


import std.algorithm, std.array, std.range;

void main() {
     int[] data = [2, 0, 1];

     auto mapped = data.map!q{a * 10};
     alias R = typeof(mapped);

     pragma(msg, hasSwappableElements!R);
     pragma(msg, hasAssignableElements!R);
     pragma(msg, isRandomAccessRange!R);
     pragma(msg, hasSlicing!R);
     pragma(msg, hasLength!R);

//    auto r1 = mapped.sort();       // Error
//    auto r2 = mapped.array.sort(); // OK
}


It prints:

false
false
true
true
true

Elements generated by a map can't be back-assigned.


To help D programmers understand such situations I have asked for 
this:
http://d.puremagic.com/issues/show_bug.cgi?id=9626

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list