.array changes the order

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 12 05:52:13 PDT 2016


On 5/12/16 6:17 AM, xtreak wrote:
> On Thursday, 12 May 2016 at 10:02:46 UTC, thedeemon wrote:
>> On Thursday, 12 May 2016 at 09:44:39 UTC, xtreak wrote:
>>> I came across the issue where using .array after .joiner caused the
>>> changes to the output. The program is at
>>> https://dpaste.dzfl.pl/0885ba2eddb4 . I tried to debug through the
>>> output but I couldn't get the exact issue. It will be helpful if
>>> someone confirms this as a bug.
>>
>> It's not a bug per se, just probably documentation being not clear
>> enough. Essentially it's the same issue as with File.byLine: a range
>> that mutates its state, so it's ok to consume lazily but if you just
>> store references (as array() does) you get references to the same
>> mutated value as result.
>>
>> Quick fix:
>>
>>   r.chunks(2).map!permutations.joiner.map!array.array.writeln;
>>
>> i.e. copy each permutation to separate array before it's gone.
>
> Thanks a lot. Can you kindly elaborate a little more on File.byLine with
> an example of the scenario so that I don't get bitten by it.
> File.byLine.array works as expected for me. A little more explanation on
> the permutations will also be helpful since joiner.map!array converts
> the subranges to arrays, so does joiner work by mutating state if so how
> does it do.

File.byLine.array will create an array of references to the same buffer, 
which is rewritten as byLine iterates. There can be cases where it 
works, but there are definitely those for which it won't work.

Basically, you are keeping references to the buffer for buffered i/o.

I think there is a byLineCopy which works.

-Steve


More information about the Digitalmars-d-learn mailing list