Описание тега parametric-polymorphism

In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. The concept of parametric polymorphism applies to both data types and functions.

Parametric polymorphism is a kind of polymorphism where a function or data type is parameterized over a type. By doing so, the function or data structure will be able to handle any type without knowing anything about it, while consumers will still be able to track which type is handled, thereby maintaining full type-safety.

Examples

OCaml

type 'a tree =
  | Node of 'a * 'a tree * 'a tree
  | Empty

(** val map : ('a -> 'b) -> 'a tree -> 'b tree *)
let rec map f =
  function | Empty -> Empty
           | Node (value, left, right) ->
             Node (f value, map f left, map f right)

(* val int_tree : int tree *)
let int_tree = Node (1, Node (2, Empty, Empty), Empty)

(* val string_tree : string tree *)
let string_tree = int_tree |> map string_of_int

C#

using System;

class Tree<T> {
    public T value;
    public Tree<T> left;
    public Tree<T> right;

    public Tree(T value) {
        this.value = value;
    }

    public Tree<U> Map<U>(Func<T,U> f) {
        var tree = new Tree<U>(f(this.value));
        tree.left = left?.Map(f);
        tree.right = right?.Map(f);
        return tree;
    }
}

public class Program {
    public static void Main(string[] args) {
        var intTree = new Tree<int>(1);
        intTree.left = new Tree<int>(2);

        Tree<string> stringTree = intTree.Map(n => n.ToString());
    }
}

Papers

Types, abstraction, and parametric polymorphism by John C. Reynolds

See also