Thread overview | ||||||
---|---|---|---|---|---|---|
|
January 06, 2018 Why is "array operation without destination memory not allowed"? | ||||
---|---|---|---|---|
| ||||
It seems a bit silly that I have to write int[] a = [1, 2, 300, -29]; int[] b; b.length = 4; b[] = a[] * 2; writeln(b); to do what I would expect int[] a = [1, 2, 300, -29]; writeln(a[] * 2); to do. What am I not understanding? |
January 06, 2018 Re: Why is "array operation without destination memory not allowed"? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Lily | On Saturday, 6 January 2018 at 23:08:14 UTC, Lily wrote:
> What am I not understanding?
Where do you expect it to put the result?
|
January 06, 2018 Re: Why is "array operation without destination memory not allowed"? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Lily | On 01/06/2018 03:08 PM, Lily wrote:
> It seems a bit silly that I have to write
>
> int[] a = [1, 2, 300, -29];
> int[] b;
> b.length = 4;
> b[] = a[] * 2;
> writeln(b);
>
> to do what I would expect
>
> int[] a = [1, 2, 300, -29];
> writeln(a[] * 2);
>
> to do. What am I not understanding?
So, apparently a[] * 2 is not an expression in D. It looks like such array-wise operations require a left-hand side with memory for the results.
The reason must be for performance. If a[]*2 were an expression, the runtime would have to allocate memory and put the results there. Assigning that memory then to b[] would require an additional copy. Current rule puts the burden on the programmer to find the memory. No need to allocate if there's memory already.
However, idiomatic D delays arrays as much as possible. For example, there is no need for destination memory for this example:
import std.stdio;
import std.algorithm;
void main() {
int[] a = [1, 2, 300, -29];
writeln(a.map!(x => 2 * x));
}
Ali
|
January 06, 2018 Re: Why is "array operation without destination memory not allowed"? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ali Çehreli | On Saturday, 6 January 2018 at 23:17:53 UTC, Ali Çehreli wrote: > So, apparently a[] * 2 is not an expression in D. > The reason must be for performance. If a[]*2 were an expression, the runtime would have to allocate memory and put the results there. Assigning that memory then to b[] would require an additional copy. Current rule puts the burden on the programmer to find the memory. No need to allocate if there's memory already. That makes sense, thanks! |
Copyright © 1999-2021 by the D Language Foundation