www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 13797] New: std.array.extend

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 puremagic.com
          Reporter: bearophile_hugs 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[]);
}

--
Nov 29 2014