Concatenation of array and range
Paul Backus
snarwin at gmail.com
Sun Jan 19 19:25:48 UTC 2025
On Sunday, 19 January 2025 at 18:57:51 UTC, Samuel Redding wrote:
> Hello there,
>
> is it possible to concat an array and a range? In Python one
> would have
> """
> list1 = [1, 2, 3]
> list1 += array.array('L', range(a, b))
> """
>
> The equivalent in D should be something like
> """
> ulong[] list1 = [1, 2, 3];
> list1 ~= iota(a, b);
> """
>
> I haven't found a way to do this. The only way to do it seems
> to extend "list1" and then iterate over the range and insert
> the elements.
The exact D equivalent of your Python code would be to use
`std.array.array` to create an array with the range's elements.
For example:
import std.range : iota;
import std.array : array;
ulong[] list1 = [1, 2, 3];
list1 ~= iota(4UL, 10UL).array;
There is also another way to do this which avoids allocating (and
immediately discarding) a temporary array:
import std.range : iota;
import std.array : appender;
import std.algorithm : copy;
ulong[] list1 = [1, 2, 3];
copy(iota(4UL, 10UL), appender(&list1));
In this code:
* `appender(&list1)` creates an output range which appends each
element inserted into it to `list1`
* `copy` takes each element from an input range (in this case,
`iota(4UL, 10UL)`) and inserts it into an output range (in this
case, `appender(&list1)`).
More information about the Digitalmars-d
mailing list