How to append range to array?

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 25 10:19:21 PDT 2015


On Saturday, 23 May 2015 at 07:03:35 UTC, Vladimir Panteleev 
wrote:
> int[] arr = [1, 2, 3];
> auto r = iota(4, 10);
> // ???
> assert(equal(arr, iota(1, 10)));
>
> Hopefully in one GC allocation (assuming we know the range's 
> length).
>
> I tried std.range.primitives.put but its behavior seems a 
> little mysterious:
>
> This compiles but asserts at runtime:
>
> int[] arr = [1, 2, 3];
> arr.put(iota(4, 10));
>
> And this is even weirder, can you guess what it will print?
>
> int[] arr = [1, 2, 3];
> arr.put(4);
> writeln(arr);

int[] arr = [1,2,3];
auto r = iota(4, 10);
auto app = arr.refAppender;
app.put(r);
assert(equal(arr, iota(1, 10)));

which of course you wrap with something like

auto append(T, R)(ref T arr, R r)
if(is(T : Q[], Q) && isInputRange!r);
{
     auto app = arr.refAppender;
     app.put(r);
     return arr;
}

to get

int[] arr = [1,2,3];
auto r = iota(4, 10);
arr.append(r);
assert(equal(arr, iota(1, 10)));

Walter has mentioned that he was interested in adding more 
range-awareness to the language, so who knows, maybe this sort of 
thing will get sugar at some point.


More information about the Digitalmars-d-learn mailing list