byChunk odd behavior?

cym13 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Mar 25 01:01:04 PDT 2016


On Thursday, 24 March 2016 at 07:52:27 UTC, Hanh wrote:
> On Wednesday, 23 March 2016 at 19:07:34 UTC, cym13 wrote:
>
>>> In Scala, 'take' consumes bytes from the iterator. So the 
>>> same code would be
>>> buffer = range.take(N).toArray
>>
>> Then just do that!
>>
>>     import std.range, std.array;
>>     auto buffer = range.take(N).array;
>>
>>     auto example = iota(0, 200, 5).take(5).array;
>>     assert(example == [0, 5, 10, 15, 20]);
>
> Well, that's what I do in the first post but you can't call it 
> twice with an InputRange.
>
> auto buffer1 = range.take(4).array; // ok
> range.popFrontN(4); // not ok
> auto buffer2 = range.take(4).array; // not ok

Please, take some time to reread cy's answer above.

     void main(string[] args) {
         import std.range;
         import std.array;
         import std.algorithm;

         auto range = iota(0, 25, 5);

         // Will not consume (forward ranges only)
         //
         // Note however that range elements are not stored in any 
way by default
         // so reusing the range will also need you to recompute 
them each time!
         auto buffer1 = range.save.take(4).array;
         assert(buffer1 == [0, 5, 10, 15]);

         // The solution to the recomputation problème, and often 
the best way to
         // handle range reuse is to store them in an array
         //
         // This is reusable at will with no redundant computation
         auto arr = range.save.array;
         assert(arr == [0, 5, 10, 15, 20]);

         // And it has a range interface too
         auto buffer2 = arr.take(4).array;
         assert(buffer2 == [0, 5, 10, 15]);

         // This consume
         auto buffer3 = range.take(4).array;
         assert(buffer3 == [0, 5, 10, 15]);
     }



More information about the Digitalmars-d-learn mailing list