Repeat and chunks
Saurabh Das via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Oct 24 08:43:44 PDT 2016
On Monday, 24 October 2016 at 15:28:50 UTC, Saurabh Das wrote:
> On Monday, 24 October 2016 at 14:25:46 UTC, Dorian Haglund
> wrote:
>> Hey,
>>
>> The following code crashes with DMD64 D Compiler v2.071.2:
>>
>> import std.algorithm;
>> import std.stdio;
>> import std.range;
>>
>> int main()
>> {
>> repeat(8, 10).chunks(3).writeln();
>>
>> return 0;
>> }
>>
>> Error message:
>>
>> pure nothrow @nogc @safe
>> std.range.Take!(std.range.Repeat!(int).Repeat).Take
>> std.range.Repeat!(int).Repeat.opSlice(ulong, ulong)
>>
>> If I replace repeat with iota, or a literal range (like [1, 2
>> ,3, 4]), I don't get the crash.
>>
>> I don't see why I should not be able to use chunks with repeat.
>> If some property of repeat's range is missing to use chunks,
>> shouldn't I get an error message ?
>>
>> Am I missing something ?
>>
>> PS: the behavior has been reproduced on someone else computer.
>>
>> Cheers :)
>
> This works:
>
> repeat(8, 12).chunks(3).writeln;
>
> The documentation of
> https://dlang.org/phobos/std_range.html#.chunks mentions
> something about evenly divisible by chunkSize – perhaps that is
> the cause of the assert fail. Not 100% sure why that's there
> though.
>
> Thanks,
> Saurabh
Some more cases, perhaps someone more knowledgeable can help:
import std.algorithm;
import std.stdio;
import std.range;
int main()
{
[8, 8, 8, 8, 8, 8].chunks(3).writeln; // prints [[8, 8, 8],
[8, 8, 8]]
repeat(8, 6).writeln; // prints [8, 8, 8, 8,
8, 8]
repeat(8, 6).chunks(3).writeln; // prints [[8, 8, 8]].
Why?
assert([8, 8, 8, 8, 8, 8] == repeat(8, 6).array); // Passes
assert([8, 8, 8, 8, 8, 8].chunks(3).array == repeat(8,
6).array.chunks(3).array); // Passes
assert([8, 8, 8, 8, 8, 8].chunks(3).array == repeat(8,
6).chunks(3).map!(a => a.array).array); // Fails
return 0;
}
More information about the Digitalmars-d-learn
mailing list