Issue 10176 - Something to extend an array with a lazy range
Summary: Something to extend an array with a lazy range
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2013-05-26 06:14 UTC by bearophile_hugs
Modified: 2024-12-01 16:17 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2013-05-26 06:14:15 UTC
Maybe it's worth adding a std.array.extend() function that's similar to "~=" but accepts a lazy range (in theory, in a language where ranges are built-ins, ~= should append ranges too to arrays).

In std.array there is a join, but it creates a whole new array. It's usually more efficient to extend arrays.


foreach (x; myrange)
    myarray ~= x;


Is replaced by:

myarray.extend(myrange);
Comment 1 Andrej Mitrovic 2013-05-26 06:21:09 UTC
Hmm, I would have hoped that 'put' would work here, but it doesn't:

-----
import std.range;
import std.array;

void main()
{
    {
        Appender!(int[]) arr;
        arr.put(iota(5));  // ok
        assert(arr.data == [0, 1, 2, 3, 4]);
    }

    {
        int[] arr;
        arr.put(iota(5));  // runtime exception
        assert(arr == [0, 1, 2, 3, 4]);
    }
}
-----

> core.exception.AssertError@C:\dmd-git\dmd2\windows\bin\..\..\src\phobos\std\array.d(587): Attempting to fetch the front of an empty array of int
Comment 2 bearophile_hugs 2013-05-26 13:12:23 UTC
More general issue summary.
Comment 3 Jonathan M Davis 2013-05-26 17:22:46 UTC
> Hmm, I would have hoped that 'put' would work here, but it doesn't:

put on arrays does not append. It starts writing at the beginning of the array. So, it functions fundamentally differently from most output ranges. Presumably, it's the desired behavior if you're dealing with a pre-allocated chunk of memory that you're trying to fill, but it is problematic in that it doesn't function like other output ranges. I've been think of opening a discussion in the newsgroup on it so that we can figure out how to better sort out some of these quirks of output ranges.
Comment 4 Andrej Mitrovic 2013-05-27 02:06:50 UTC
(In reply to comment #3)
> > Hmm, I would have hoped that 'put' would work here, but it doesn't:
> 
> put on arrays does not append. It starts writing at the beginning of the array.

That makes sense now that I think about it.
Comment 5 dlangBugzillaToGithub 2024-12-01 16:17:43 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/phobos/issues/9978

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB