Genuine copy of an element from an associative array
Nick Treleaven
nick at geany.org
Sun Oct 6 10:53:28 UTC 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.
More information about the Digitalmars-d-learn
mailing list