Anonymous user
Parametric polymorphism: Difference between revisions
m
lang tags
(added standard ml) |
m (lang tags) |
||
Line 40:
=={{header|C++}}==
class tree
{
Line 48:
public:
void replace_all (T new_value);
};</lang>
For simplicity, we replace all values in the tree with a new value:
void tree<T>::replace_all (T new_value)
{
Line 58:
left->replace_all (new_value);
right->replace_all (new_value);
}</lang>
=={{header|D}}==
D template can parametric by constant.
<
class ArrayTree(T, int LEN) {
Line 75:
if(RHS) RHS.map(dg) ;
}
}</
This is a using example.
<
module polytest ;
import std.stdio ;
import parapoly ;
//Instantiating an ArrayTree class of real(T) array, whose length(LEN) is 3.
alias ArrayTree!(real, 3) VecT ;
void main() {
VecT v = new VecT(0.01);
Line 99 ⟶ 97:
writefln() ;
v.map((real[] x){writefln(x) ;} ) ;
}</
=={{header|Haskell}}==
mapTree :: (a -> b) -> Tree a -> Tree b
mapTree f Empty = Empty
mapTree f (Node x l r) = Node (f x) (mapTree f l) (mapTree f r)</lang>
=={{header|Java}}==
Following the C++ example:
private T value;
private Tree<T> left;
Line 122 ⟶ 120:
right.replaceAll(value);
}
}</lang>
=={{header|OCaml}}==
(** val map_tree : ('a -> 'b) -> 'a tree -> 'b tree *)
let rec map_tree f = function
| Empty -> Empty
| Node (x,l,r) -> Node (f x, map_tree f l, map_tree f r)</lang>
=={{header|Standard ML}}==
(** val map_tree = fn : ('a -> 'b) -> 'a tree -> 'b tree *)
fun map_tree f Empty = Empty
| map_tree f (Node (x,l,r)) = Node (f x, map_tree f l, map_tree f r)</lang>
|