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.




using System;
 
class BinaryTree<T>
{
    public T value;
    public BinaryTree<T> left;
    public BinaryTree<T> right;
 
    public BinaryTree(T value)
    {
        this.value = value;
    }
 
    public BinaryTree<U> Map<U>(Func<T, U> f)
    {
        BinaryTree<U> tree = new BinaryTree<U>(f(this.value));
        if (this.left != null)
        {
            tree.left = this.left.Map(f);
        }
        if (this.right != null)
        {
            tree.right = this.right.Map(f);
        }
        return tree;
    }
}