Parametric polymorphism: Difference between revisions
Content deleted Content added
No edit summary |
D entry: updated and improved |
||
Line 189: | Line 189: | ||
=={{header|D}}== |
=={{header|D}}== |
||
⚫ | |||
D templates can parametric by constant too. |
|||
T[N] data; |
|||
⚫ | |||
typeof(this) left, right; |
|||
ArrayTree left, right; |
|||
this(T initValue) { data[] = initValue; } |
this(T initValue) { this.data[] = initValue; } |
||
void |
void tmap(const void delegate(ref typeof(data)) dg) { |
||
dg(data); |
dg(this.data); |
||
if (left) left. |
if (left) left.tmap(dg); |
||
if (right) right. |
if (right) right.tmap(dg); |
||
} |
} |
||
} |
} |
||
void main() { // |
void main() { // Demo code. |
||
import std.stdio; |
import std.stdio; |
||
// |
// Instantiate the template ArrayTree of three doubles. |
||
alias AT3 = ArrayTree!(double, 3); |
|||
alias ArrayTree!(double, 3) VecT; |
|||
// |
// Allocate the tree root. |
||
auto root = new |
auto root = new AT3(1.00); |
||
// |
// Add some nodes. |
||
root.left = new |
root.left = new AT3(1.10); |
||
root.left.left = new |
root.left.left = new AT3(1.11); |
||
root.left.right = new |
root.left.right = new AT3(1.12); |
||
root.right = new |
root.right = new AT3(1.20); |
||
root.right.left = new |
root.right.left = new AT3(1.21); |
||
root.right.right = new |
root.right.right = new AT3(1.22); |
||
// |
// Now the tree has seven nodes. |
||
// |
// Show the arrays of the whole tree. |
||
root. |
//root.tmap(x => writefln("%(%.2f %)", x)); |
||
root.tmap((ref double[3] x) => writefln("%(%.2f %)", x)); |
|||
// |
// Modify the arrays of the whole tree. |
||
//root.tmap((x){ x[] += 10; }); |
|||
root. |
root.tmap((ref double[3] x){ x[] += 10; }); |
||
// |
// Show the arrays of the whole tree again. |
||
writeln(); |
writeln(); |
||
root. |
//root.tmap(x => writefln("%(%.2f %)", x)); |
||
root.tmap((ref double[3] x) => writefln("%(%.2f %)", x)); |
|||
}</lang> |
}</lang> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre>1.00 1.00 1.00 |
||
1.10 1.10 1.10 |
|||
1.11 1.11 1.11 |
|||
1.12 1.12 1.12 |
|||
1.20 1.20 1.20 |
|||
1.21 1.21 1.21 |
|||
1.22 1.22 1.22 |
|||
11.00 11.00 11.00 |
|||
11.10 11.10 11.10 |
|||
11.11 11.11 11.11 |
|||
11.12 11.12 11.12 |
|||
11.20 11.20 11.20 |
|||
11.21 11.21 11.21 |
|||
11.22 11.22 11.22</pre> |
|||
=={{header|E}}== |
=={{header|E}}== |