digitalmars.D.learn - Genuine copy of an element from an associative array
- Holzofen (27/27) Oct 03 2024 This is my (feeble) source code, for testing purposes only:
- Nick Treleaven (10/36) Oct 06 2024 You can copy an AA using `dup`:
- Holzofen (2/15) Oct 06 2024 Thanks a lot!
This is my (feeble) source code, for testing purposes only:
uint64 sod_decompose(const uint64 n, const uint64 mod, const
ref uint64[] primes, const ref uint64[uint64][uint64] factorials)
{
auto result = factorials[n];
for (uint64 k = 2; k < n - 1; k++) {
auto backup = factorials[n];
tuple("1", backup).writeln;
foreach (p, e; factorials[k]) {
backup[p] -= e;
}
tuple("2", backup).writeln;
foreach (p, e; factorials[n-k]) {
backup[p] -= e;
}
tuple("3", backup).writeln;
}
return 0;
}
uint64 is equivalent to ulong. Upon compilation I get this error:
Error: cannot modify `const` expression `backup[p]`
which concerns these two lines: backup[p] -= e;
Without the const statement in the function declaration the
source array will be modified which is definitely not desirable.
Could anybody point me to a way how to make a straight copy
without meddling with the source array?
Thank you!
Oct 03 2024
On Thursday, 3 October 2024 at 12:23:27 UTC, Holzofen wrote:```d uint64 sod_decompose(const uint64 n, const uint64 mod, const ref uint64[] primes, const ref uint64[uint64][uint64] factorials) { auto result = factorials[n]; for (uint64 k = 2; k < n - 1; k++) { auto backup = factorials[n]; tuple("1", backup).writeln; foreach (p, e; factorials[k]) { backup[p] -= e; } tuple("2", backup).writeln; foreach (p, e; factorials[n-k]) { backup[p] -= e; } tuple("3", backup).writeln; } return 0; } ``` uint64 is equivalent to ulong. Upon compilation I get this error: Error: cannot modify `const` expression `backup[p]`Could anybody point me to a way how to make a straight copy without meddling with the source array?You can copy an AA using `dup`: https://dlang.org/phobos/object.html#.dup Unfortunately this doesn't work: uint64[uint64] backup = factorials[n].dup; https://issues.dlang.org/show_bug.cgi?id=11725 Instead you can use: auto backup = cast(uint64[uint64]) factorials[n].dup; I think casting away const is OK because the AA produced by `dup` is unique, and the element type doesn't have indirections.
Oct 06 2024
On Sunday, 6 October 2024 at 10:53:28 UTC, Nick Treleaven wrote:On Thursday, 3 October 2024 at 12:23:27 UTC, Holzofen wrote:Thanks a lot![...]Could anybody point me to a way how to make a straight copy without meddling with the source array?You can copy an AA using `dup`: https://dlang.org/phobos/object.html#.dup Unfortunately this doesn't work: uint64[uint64] backup = factorials[n].dup; https://issues.dlang.org/show_bug.cgi?id=11725 Instead you can use: auto backup = cast(uint64[uint64]) factorials[n].dup; I think casting away const is OK because the AA produced by `dup` is unique, and the element type doesn't have indirections.
Oct 06 2024








Holzofen <z5iph7ukvx yopmail.com>