Parametric polymorphism: Difference between revisions

Content added Content deleted
(Add Seed7 example)
(Improved D entry)
Line 189: Line 189:


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


this(T initValue) { data[] = initValue; }
class ArrayTree(T, int LEN) {
// template instantiation in alias
alias ArrayTree!(T, LEN) ANode ;
const int length = LEN ;
T[LEN] array ;
ANode LHS, RHS ;
this (T initvalue) { array[] = initvalue ; }
void map(void delegate(T[]) dg) {
dg(array) ;
if(LHS) LHS.map(dg) ;
if(RHS) RHS.map(dg) ;
}
}</lang>
This is a using example.
<lang d>module polytest ;
import std.stdio ;
import parapoly ;


void map(void delegate(T[]) dg) {
//Instantiating an ArrayTree class of real(T) array, whose length(LEN) is 3.
dg(data);
alias ArrayTree!(real, 3) VecT ;
if (left) left.map(dg);
if (right) right.map(dg);
}
}


void main() {
void main() { // demo code
VecT v = new VecT(0.01);
import std.stdio;
// init an array tree.
v.LHS = new VecT(1.11) ; v.LHS.LHS = new VecT(1.11) ; v.LHS.RHS = new VecT(1.12) ;
v.RHS = new VecT(1.21) ; v.RHS.LHS = new VecT(1.21) ; v.RHS.RHS = new VecT(1.22) ;


// Instantiating an ArrayTree class of double(T) data,
// do something start from root v
// whose length(LEN) is 3.
v.map((real[] x){writefln(x) ;} ) ;
alias ArrayTree!(double, 3) VecT;
real new_value = 0.9L ;

v.map((real[] x){x[] = new_value ;} ) ;
// create the tree root
writefln() ;
auto root = new VecT(0.01);
v.map((real[] x){writefln(x) ;} ) ;

// init the data tree root.
root.left = new VecT(1.11);
root.left.left = new VecT(1.11);
root.left.right = new VecT(1.12);

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

// now the tree has seven nodes

// show arrays of the whole tree
root.map((double[] x){ writeln(x); });

// change the arrays of the whole tree
double new_value = 0.9L;
root.map((double[] x){ x[] = new_value; });

// show arrays of the whole tree again
writeln();
root.map((double[] x){ writeln(x); });
}</lang>
}</lang>
{{out}}
<pre>[0.01, 0.01, 0.01]
[1.11, 1.11, 1.11]
[1.11, 1.11, 1.11]
[1.12, 1.12, 1.12]
[1.21, 1.21, 1.21]
[1.21, 1.21, 1.21]
[1.22, 1.22, 1.22]

[0.9, 0.9, 0.9]
[0.9, 0.9, 0.9]
[0.9, 0.9, 0.9]
[0.9, 0.9, 0.9]
[0.9, 0.9, 0.9]
[0.9, 0.9, 0.9]
[0.9, 0.9, 0.9]</pre>


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