Bug 13797 – std.array.extend

Status
NEW
Severity
enhancement
Priority
P4
Component
phobos
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2014-11-29T13:44:38Z
Last change time
2024-12-01T16:23:08Z
Assigned to
No Owner
Creator
bearophile_hugs
Moved to GitHub: phobos#9647 →

Comments

Comment #0 by bearophile_hugs — 2014-11-29T13:44:38Z
I suggest to add to Phobos a simple function like this, mainly useful to extend dynamic arrays with a given lazy iterable (but this works with std.array.array too): void extend(A, R)(ref A arr, R iterable) if (__traits(compiles, { foreach (item; iterable) arr ~= item; })) { import std.range: hasLength; static if (hasLength!R && hasLength!A) arr.reserve(arr.length + iterable.length); foreach (item; iterable) arr ~= item; } void main() { import std.stdio, std.range; int[] arr; arr.extend(only(1, 2, 3, 4)); writeln(arr); static struct Gen5 { int opApply(int delegate(ref int) dg) { int result; foreach (i; 0 .. 5) { result = dg(i); if (result) break; } return result; } } arr.extend(Gen5()); writeln(arr); import std.container: Array; Array!int arr2; writeln(arr2[]); arr2.extend(only(1, 2, 3, 4)); writeln(arr2[]); }
Comment #1 by greensunny12 — 2018-03-31T15:07:09Z
Hmm. Why can't we handle this on a language level? --- int[] arr; arr ~= [0, 1, 2]; --- works fine. So I don't see any reason why the compiler couldn't be improved to accept this too: --- int[] arr; arr ~= 3.iota; --- Custom data types can already do this with operator overloading, but built-in arrays can't. I submitted an enhancement request: https://issues.dlang.org/show_bug.cgi?id=18699
Comment #2 by robert.schadek — 2024-12-01T16:23:08Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/phobos/issues/9647 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB