Why can't static arrays be sorted?

Jon Degenhardt via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Oct 8 14:14:43 PDT 2016


On Thursday, 6 October 2016 at 20:11:17 UTC, ag0aep6g wrote:
> On 10/06/2016 09:54 PM, TheGag96 wrote:
>> Interestingly enough, I found that using .each() actually 
>> compiles
>> without the []
> [...]
>> why can the compiler consider it a range here but not
>> .sort()?
>
> each is not restricted to ranges. It accepts other 
> `foreach`-ables, too. The documentation says that it "also 
> supports opApply-based iterators", but it's really anything 
> that foreach accepts.
>   [snip]
> 
Thanks! Explains some things. I knew each! was callable in 
different circumstances than other functional operations, but 
hadn't quite figured it out. Looks like reduce! and fold! also 
take iterables.

There also appears to be a distinction between the iterator and 
range cases when a ref parameter is used. As it iterator, each! 
won't modify the reference. Example:

void main()
{
     import std.algorithm : each;

     int[] dynamicArray = [1, 2, 3, 4, 5];
     int[5] staticArray = [1, 2, 3, 4, 5];

     dynamicArray.each!((ref x) => x++);
     assert(dynamicArray == [2, 3, 4, 5, 6]); // modified

     staticArray.each!((ref x) => x++);
     assert(staticArray == [1, 2, 3, 4, 5]);  // not modified

     staticArray[].each!((ref x) => x++);
     assert(staticArray == [2, 3, 4, 5, 6]);  // modified
}

This distinction is a bit on the nuanced side. Is it behaving as 
it should?

--Jon


More information about the Digitalmars-d-learn mailing list