Parametric Polymorphism
type variables


Task

Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it.



A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree.

This language feature only applies to statically-typed languages.




 
domains
   tree{Type} = branch(tree{Type} Left, tree{Type} Right); leaf(Type Value).
 
class predicates
   treewalk : (tree{X},function{X,Y}) -> tree{Y} procedure (i,i).
 
clauses
   treewalk(branch(Left,Right),Func) = branch(NewLeft,NewRight) :-
        NewLeft = treewalk(Left,Func), NewRight = treewalk(Right,Func).
 
   treewalk(leaf(Value),Func) = leaf(X) :- 
        X = Func(Value).
 
   run():-
       init(),
       X = branch(leaf(2), branch(leaf(3),leaf(4))),
       Y = treewalk(X,addone),
       write(Y),
       succeed().
 