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

deed none at none.none
Mon Mar 4 15:55:04 PST 2013


> 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

Meaning sortable ranges are actually a narrow subset of random 
access ranges? Why aren't the constraints listed in the docs? Are 
the source files and error messages the only way to get this info?


> 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

Could be helpful.
Example of error message where source has to be investigated:
...\phobos\std\algorithm.d(7946): Error: r[j] is not an lvalue
from this file compiled with dmd 2.061:

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

void main() {

     long[] slice = [2, -1, -3];

     auto mappedSortedSumOfFirstTwo =
         slice.map!("a ^^ 2").
         sort.                         // causes the error message
         take(2).
         reduce!("a + b");
}





More information about the Digitalmars-d-learn mailing list