Parametric polymorphism: Difference between revisions

Content added Content deleted
No edit summary
(D entry: updated and improved)
Line 189: Line 189:


=={{header|D}}==
=={{header|D}}==
<lang d>class ArrayTree(T, uint N) {
D templates can parametric by constant too.
T[N] data;
<lang d>class ArrayTree(T, int LEN) {
T[LEN] data;
typeof(this) left, right;
ArrayTree left, right;


this(T initValue) { data[] = initValue; }
this(T initValue) { this.data[] = initValue; }


void map(void delegate(T[]) dg) {
void tmap(const void delegate(ref typeof(data)) dg) {
dg(data);
dg(this.data);
if (left) left.map(dg);
if (left) left.tmap(dg);
if (right) right.map(dg);
if (right) right.tmap(dg);
}
}
}
}


void main() { // demo code
void main() { // Demo code.
import std.stdio;
import std.stdio;


// Instantiating an ArrayTree class of double(T) data,
// Instantiate the template ArrayTree of three doubles.
// whose length(LEN) is 3.
alias AT3 = ArrayTree!(double, 3);
alias ArrayTree!(double, 3) VecT;


// create the tree root
// Allocate the tree root.
auto root = new VecT(0.01);
auto root = new AT3(1.00);


// init the data tree root.
// Add some nodes.
root.left = new VecT(1.11);
root.left = new AT3(1.10);
root.left.left = new VecT(1.11);
root.left.left = new AT3(1.11);
root.left.right = new VecT(1.12);
root.left.right = new AT3(1.12);


root.right = new VecT(1.21);
root.right = new AT3(1.20);
root.right.left = new VecT(1.21);
root.right.left = new AT3(1.21);
root.right.right = new VecT(1.22);
root.right.right = new AT3(1.22);


// now the tree has seven nodes
// Now the tree has seven nodes.


// show arrays of the whole tree
// Show the arrays of the whole tree.
root.map((double[] x){ writeln(x); });
//root.tmap(x => writefln("%(%.2f %)", x));
root.tmap((ref double[3] x) => writefln("%(%.2f %)", x));


// change the arrays of the whole tree
// Modify the arrays of the whole tree.
double new_value = 0.9L;
//root.tmap((x){ x[] += 10; });
root.map((double[] x){ x[] = new_value; });
root.tmap((ref double[3] x){ x[] += 10; });


// show arrays of the whole tree again
// Show the arrays of the whole tree again.
writeln();
writeln();
root.map((double[] x){ writeln(x); });
//root.tmap(x => writefln("%(%.2f %)", x));
root.tmap((ref double[3] x) => writefln("%(%.2f %)", x));
}</lang>
}</lang>
{{out}}
{{out}}
<pre>[0.01, 0.01, 0.01]
<pre>1.00 1.00 1.00
[1.11, 1.11, 1.11]
1.10 1.10 1.10
[1.11, 1.11, 1.11]
1.11 1.11 1.11
[1.12, 1.12, 1.12]
1.12 1.12 1.12
[1.21, 1.21, 1.21]
1.20 1.20 1.20
[1.21, 1.21, 1.21]
1.21 1.21 1.21
[1.22, 1.22, 1.22]
1.22 1.22 1.22


[0.9, 0.9, 0.9]
11.00 11.00 11.00
[0.9, 0.9, 0.9]
11.10 11.10 11.10
[0.9, 0.9, 0.9]
11.11 11.11 11.11
[0.9, 0.9, 0.9]
11.12 11.12 11.12
[0.9, 0.9, 0.9]
11.20 11.20 11.20
[0.9, 0.9, 0.9]
11.21 11.21 11.21
[0.9, 0.9, 0.9]</pre>
11.22 11.22 11.22</pre>


=={{header|E}}==
=={{header|E}}==