[Issue 13797] New: std.array.extend

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Sat Nov 29 05:44:38 PST 2014


https://issues.dlang.org/show_bug.cgi?id=13797

          Issue ID: 13797
           Summary: std.array.extend
           Product: D
           Version: D2
          Hardware: x86
                OS: Windows
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: Phobos
          Assignee: nobody at puremagic.com
          Reporter: bearophile_hugs at eml.cc

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[]);
}

--


More information about the Digitalmars-d-bugs mailing list