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.




 
#lang typed/racket
 
(define-type (Tree A) (U False (Node A)))
 
(struct: (A) Node
  ([val : A] [left : (Tree A)] [right : (Tree A)])
  #:transparent)
 
(: tree-map (All (A B) (A -> B) (Tree A) -> (Tree B)))
(define (tree-map f tree)
  (match tree
    [#f #f]
    [(Node val left right)
     (Node (f val) (tree-map f left) (tree-map f right))]))
 
;; unit tests
(require typed/rackunit)
(check-equal?
 (tree-map add1 (Node 5 (Node 3 #f #f) #f))
 (Node 6 (Node 4 #f #f) #f))
 