I wrote a function that accepts input ranges, and I get compile errors when passing an array

Seb via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 28 13:49:03 PDT 2016


On Saturday, 28 May 2016 at 20:43:00 UTC, pineapple wrote:
> On Saturday, 28 May 2016 at 16:25:02 UTC, Seb wrote:
>> If you are interested how it works under the hood - it's 
>> pretty simple & elegant:
>
> I checked up on the phobos implementation and found that arrays 
> are mutated when iterated over as ranges, which didn't rest 
> well with me. Nor did the idea of importing some module having 
> such a significant side-effect as whether some type can act as 
> a range or not. So I ended up making a sort of factory that 
> turns arbitrary objects into ranges, including arrays. Seems to 
> work pretty well.

Arrays in D work differently to other languages. That's why we 
call them Slices ;-)

See: https://dlang.org/d-array-article.html

Phobos just modifies the pointer - so `a = a[1 .. $];` is nothing 
more than creating a new pointer.

> are mutated when iterated over as ranges,

Btw all ranges are modified during iteration, they have a state 
and with every popFront you change that. If you want to save the 
state before, you can call `.save` if it's at least a ForwardRange


More information about the Digitalmars-d-learn mailing list