June 03, 2021

On Wednesday, 2 June 2021 at 17:50:13 UTC, Sean wrote:

>

On Wednesday, 2 June 2021 at 15:32:38 UTC, Sean wrote:

>

if so, how can I get the behavior i am searching for? Thank you.

My current solution, if anyone wonders : https://github.com/patefacio/d-help/blob/master/d-help/opmix/dup.d

You may find the hasIndirections template from std.traits useful.

import std.traits : hasIndirections, ValueType;
import std.range.primitives : ElementType;
int[] a;
int[][] b;
int[string] x;
int[][string] y;
struct S { int s; }
struct T { int[] t; }

assert(!hasIndirections!( ElementType!(typeof(a)) ));
assert( hasIndirections!( ElementType!(typeof(b)) ));
assert(!hasIndirections!( ValueType!(typeof(x)) ));
assert( hasIndirections!( ValueType!(typeof(y)) ));
assert(!hasIndirections!S);
assert( hasIndirections!T);
June 03, 2021

On Wednesday, 2 June 2021 at 15:32:38 UTC, Sean wrote:

>

...

You can implement deep copy using template recursion:

import std;

T[] rdup(T : U[], U)(T[] duped) {
    return duped.map!(arr => arr.rdup).array;
}

T[] rdup(T)(T[] duped) {
    return duped.dup;
}

void main()
{
    int[][][] dupeable = [[[1], [2]], [[3]]];
    auto duped = dupeable.rdup;
    duped[0][0][0] = 9;
    writeln("Hello D-eep copy of ", dupeable, " to ", duped);
}

Best regards,
Alexandru.

June 03, 2021
import std.stdio;
void main(){
auto a=new int[][] (0,0);
a~=[1,2];
a~=[3,4];
auto b= a.dup;
a[0]=[5,6];
a[1][1]=7;
writeln(b);
}

Program above outputs [[1, 2], [3, 7]]
Which means a[1][1] and b[1][1] point to the same memory location.
But a[0] occupies a different memory location as b[0].
It is a shallow copy and is the expected behaviour.
Maybe there is need for a library function dupdeep ?

1 2
Next ›   Last »