Parametric polymorphism: Difference between revisions

D entry: updated and improved
No edit summary
(D entry: updated and improved)
Line 189:
 
=={{header|D}}==
<lang d>class ArrayTree(T, intuint LENN) {
D templates can parametric by constant too.
T[N] data;
<lang d>class ArrayTree(T, int LEN) {
T[LEN]typeof(this) dataleft, right;
ArrayTree left, right;
 
this(T initValue) { this.data[] = initValue; }
 
void maptmap(const void delegate(T[]ref typeof(data)) dg) {
dg(this.data);
if (left) left.maptmap(dg);
if (right) right.maptmap(dg);
}
}
 
void main() { // demoDemo code.
import std.stdio;
 
// InstantiatingInstantiate anthe ArrayTreetemplate classArrayTree of double(T)three data,doubles.
//alias whoseAT3 length= ArrayTree!(LEN) isdouble, 3.);
alias ArrayTree!(double, 3) VecT;
 
// createAllocate the tree root.
auto root = new VecTAT3(01.0100);
 
// initAdd thesome data tree rootnodes.
root.left = new VecTAT3(1.1110);
root.left.left = new VecTAT3(1.11);
root.left.right = new VecTAT3(1.12);
 
root.right = new VecTAT3(1.2120);
root.right.left = new VecTAT3(1.21);
root.right.right = new VecTAT3(1.22);
 
// nowNow the tree has seven nodes.
 
// showShow the arrays of the whole tree.
//root.maptmap(x => writefln(double[]"%(%.2f x%){", writeln(x); });
root.tmap((ref double[3] x) => writefln("%(%.2f %)", x));
 
// changeModify the arrays of the whole tree.
double//root.tmap((x){ new_valuex[] += 0.9L10; });
root.maptmap((ref double[3] x){ x[] += new_value10; });
 
// showShow the arrays of the whole tree again.
writeln();
//root.maptmap(x => writefln(double[]"%(%.2f x%){", writeln(x); });
root.tmap((ref double[3] x) => writefln("%(%.2f %)", x));
}</lang>
{{out}}
<pre>[01.01,00 01.01,00 01.01]00
[1.11,10 1.11,10 1.11]10
[1.11, 1.11, 1.11]
[1.12, 1.12, 1.12]
[1.21,20 1.21,20 1.21]20
[1.21, 1.21, 1.21]
[1.22, 1.22, 1.22]
 
[011.9,00 011.9,00 011.9]00
[011.9,10 011.9,10 011.9]10
[011.9,11 011.9,11 011.9]11
[011.9,12 011.9,12 011.9]12
[011.9,20 011.9,20 011.9]20
[011.9,21 011.9,21 011.9]21
[011.9,22 011.9,22 011.9]22</pre>
 
=={{header|E}}==