Parametric polymorphism: Difference between revisions

m
lang tags
(added standard ml)
m (lang tags)
Line 40:
=={{header|C++}}==
 
<lang cpp> template<class T>
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:
 
<lang cpp> template<class T>
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.
<prelang d>module parapoly ;
 
class ArrayTree(T, int LEN) {
Line 75:
if(RHS) RHS.map(dg) ;
}
}</prelang>
This is a using example.
<prelang d>
module polytest ;
import std.stdio ;
import parapoly ;
 
</pre>
<pre style="background-color:#ffe">
//Instantiating an ArrayTree class of real(T) array, whose length(LEN) is 3.
alias ArrayTree!(real, 3) VecT ;
 
</pre>
<pre>
void main() {
VecT v = new VecT(0.01);
Line 99 ⟶ 97:
writefln() ;
v.map((real[] x){writefln(x) ;} ) ;
}</prelang>
=={{header|Haskell}}==
 
<lang haskell> data Tree a = Empty | Node a (Tree a) (Tree a)
 
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:
<lang java> public class Tree<T>{
private T value;
private Tree<T> left;
Line 122 ⟶ 120:
right.replaceAll(value);
}
}</lang>
 
=={{header|OCaml}}==
 
<lang ocaml> type 'a tree = Empty | Node of 'a * 'a tree * 'a tree
 
(** 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}}==
 
<lang sml> datatype 'a tree = Empty | Node of 'a * 'a tree * 'a tree
 
(** 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>