On Friday, 8 May 2015 at 06:30:46 UTC, Ali Çehreli wrote:
In D, everything is possible and very easy. :p I called it
deepDup:
import std.stdio;
import std.traits;
import std.range;
import std.algorithm;
auto deepDup(A)(A arr)
if (isArray!A)
{
static if (isArray!(ElementType!A)) {
return arr.map!(a => a.deepDup).array;
} else {
return arr.dup;
}
}
void main()
{
auto c = [[[1, 2, 3], [4, 5, 6, 7, 8]],
[[9, 10], [11, 12, 13]]];
auto d = c.deepDup;
d[0][1][1 .. $ - 1] *= 3;
writeln("c = ", c);
// [[[1, 2, 3], [4, 5, 6, 7, 8]],
// [[9, 10], [11, 12, 13]]] // OK
writeln("d = ", d);
// [[[1, 2, 3], [4, 15, 18, 21, 8]],
// [[9, 10], [11, 12, 13]]] // OK
}
Ali
Thank you. In D it's really easy :)
Recursion, which works with the lambda map looks fine.
I was a little question: why static int idx variable declared
within a function deepDup takes the values 1, 1, 1, 2, 2, 3, 4,
as opposed to a global variable static int idx, which receives
the expected value of 1, 2, 3, 4, 5, 6, 7 ?
-----
import std.stdio,
std.range,
std.traits,
std.algorithm;
// static int idx; // 1, 2, 3, 4, 5, 6, 7 // OK
auto deepDup(A)(A arr)
if (isArray!A)
{
static int idx; // 1, 1, 1, 2, 2, 3, 4 // Why is this happening?
++idx;
writeln("visited");
static if (isArray!(ElementType!A)) {
writeln("ifIdx = ", idx);
writeln("ifArr = ", arr);
return arr.map!(a => a.deepDup).array;
} else {
writeln("elseIdx = ", idx);
writeln("elseArr = ", arr);
return arr.dup;
}
}
void main() {
auto a = [[[1, 2, 3], [4, 5, 6, 7, 8]],
[[9, 10], [11, 12, 13]]];
auto b = a.deepDup;
b[0][1][1 .. $ - 1] *= 3;
writeln("\nResualt: ");
writeln("a = ", a);
// [[[1, 2, 3], [4, 5, 6, 7, 8]],
// [[9, 10], [11, 12, 13]]]
writeln("b = ", b);
// [[[1, 2, 3], [4, 15, 18, 21, 8]],
// [[9, 10], [11, 12, 13]]]
}
-----
http://ideone.com/mAHZyO