- Concepts of Programming Languages

Parametric Polymorphism

Instructor:

Learning Objectives

Inheritance for container classes?

  • Compare inheritance and type parameters

Monomorphic Linked Lists

  • Linked list, monomorphic type
  1. typedef struct Node Node;
  2. struct Node {
  3. int* item;
  4. Node* next;
  5. };
  6. int* get_last (Node* xs) {
  7. while (xs->next != NULL) {
  8. xs = xs->next;
  9. }
  10. return xs->item;
  11. }

Code duplication

  1. typedef struct FloatNode FloatNode;
  2. struct FloatNode {
  3. float* item;
  4. FloatNode* next;
  5. };
  6. float* get_last (FloatNode* xs) {
  7. while (xs->next != NULL) {
  8. xs = xs->next;
  9. }
  10. return xs->item;
  11. }

Benefits? Downsides?

Generic Linked Lists

  • Use a generic type, (void*) in C
  1. typedef struct Node Node;
  2. struct Node {
  3. void* item;
  4. Node* next;
  5. };
  6. void* get_last (Node* xs) {
  7. while (xs->next != NULL) {
  8. xs = xs->next;
  9. }
  10. return xs->item;
  11. }

Benefits? Downsides?

No static protection against casts
In C, no dynamic protection at runtime

  1. int main () {
  2. int p = (int*) malloc (sizeof(int));
  3. *p = 2123456789;
  4. Node* xs = (Node*) malloc (sizeof(Node));
  5. xs->next = NULL;
  6. xs->item = p; // store pointer
  7. double* q = get_last(xs); // alias of p
  8. printf ("q=%f\n", *q); // unsafe access
  9. }
  1. q=96621069057346178268049192388430659584.000000

Polymorphic Linked Lists

  • Generic using subtype polymorphism
  1. class Node {
  2. public Object item;
  3. public Node next;
  4. }
  5. Object getLast (Node xs) {
  6. while (xs.next != null) {
  7. xs = xs.next;
  8. }
  9. return xs.item;
  10. }
  • No static protection against casts
  • Dynamic protection against unsafe memory access
  1. public static void main (String[] args) {
  2. Integer p = Integer.valueOf(2123456789);
  3. Node xs = new Node();
  4. xs.next = null;
  5. xs.item = p; // store Integer
  6. Double q = (Double) getLast(xs); // ClassCastException
  7. System.out.printf ("d=%f\n", q); // unsafe access
  8. }
  1. java.lang.ClassCastException: Integer cannot be cast to Double
  • Benefits? Downsides?

Can Inheritance Solve This?

  • Container base class
    1. abstract class Node {
    2. public Object item;
    3. public Node next;
    4. public Object getLast() {
    5. Node xs = this;
    6. while (xs.next != null) xs = xs.next;
    7. return xs.item;
    8. }
    9. }
  • Implementations reuse getLast
    1. class IntNode extends Node {
    2. public int getLastItem() {
    3. return (int)getLast(); // cast
    4. }
    5. }

Benefits? Downsides?

Static casts shifted into library, but problem not solved

How to adapt a class?

  • Need type parameters

    1. class Node {
    2. public X item;
    3. public Node next;
    4. public X getLast() {
    5. Node xs = this;
    6. while (xs.next != null) xs = xs.next;
    7. return xs.item;
    8. }
    9. }
  • What is X and where is it defined?

Parametric Polymorphism

  • Generic using parametric polymorphism
  1. class Node<X> {
  2. public X item;
  3. public Node<X> next;
  4. public X getLast () {
  5. Node<X> xs = this;
  6. while (xs.next != null) xs = xs.next;
  7. return xs.item;
  8. }
  9. }
  • Create a list of Integer
    1. public static void main (String[] args) {
    2. Node<Integer> xs = new Node<>();
    3. xs.next = null;
    4. xs.item = Integer.valueOf(37);
  • Static protection against casts

    Dynamic protection

    Incompatible read: compile error

    1. Double q = (Double) xs.getLast(); // compiler error
    2. System.out.printf ("d=%f\n", q); // runtime exception
    3. }
    1. error: incompatible types: Integer cannot be converted to Double
    2. Double q = (Double) xs.getLast(); // compiler error
    3. ^

Parametric Polymorphism

Java Generics

  1. class Node<X> {
  2. public X item;
  3. public Node<X> next;
  4. public X getLast () {
  5. Node<X> xs = this;
  6. while (xs.next != null)
  7. xs = xs.next;
  8. return xs.item;
  9. }
  10. }

Scala Type Parameters

  1. {runnable}
  2. class Node[X](val item: X, val next: Node[X]):
  3. def getLast () : X =
  4. var xs = this
  5. while xs.next != null do
  6. xs = xs.next
  7. xs.item
  8. end getLast
  9. end Node

Scala (ADT and recursive)

  1. {runnable}
  2. enum List[+X]:
  3. case Nil
  4. case Node(item: X, next: List[X])
  5. def lastOption: Option[X] = this match
  6. case Nil => None
  7. case Node(item, Nil) => Some(item)
  8. case Node(_, next) => next.lastOption
  9. end lastOption
  10. def last: X = lastOption.get
  11. end List
enum List[+X]:
  case Nil
  case Node(item: X, next: List[X])
  
  def lastOption: Option[X] = this match
    case Nil             => None
    case Node(item, Nil) => Some(item)
    case Node(_, next)   => next.lastOption
  end lastOption

  def last: X = lastOption.get

  // ::: is right-associative (other ::: this)
  def :::[Y >: X](other: List[Y]) : List[Y] = other match
    case Nil              => this
    case Node(item, Nil)  => Node(item, this)
    case Node(item, next) => Node(item, next ::: this)
  end :::
end List

List.Node(1, List.Nil) ::: List.Nil
List.Node(1, List.Nil) ::: List.Node(2, List.Node(3, List.Nil))

// EXERCISE: turn Tree into a parametric type

enum Tree:
  case Leaf
  case Node(item: Any, left: Tree, right: Tree)

  def infix: List[Any] = this match
    case Leaf          => List.Nil
    case Node(i, l, r) => l.infix ::: List.Node(i, r.infix)
end Tree

Tree.Node(
  2,
  Tree.Node(1, Tree.Leaf, Tree.Leaf),
  Tree.Node(3, Tree.Leaf, Tree.Leaf)
).infix

Tree.Node(
  3,
  Tree.Node(1, Tree.Leaf, Tree.Node(2, Tree.Leaf, Tree.Leaf)),
  Tree.Node(
    5,
    Tree.Node(4, Tree.Leaf, Tree.Leaf),
    Tree.Node(7, Tree.Node(6, Tree.Leaf, Tree.Leaf), Tree.Leaf)
    )
).infix

Type Parameter Erasure

  • Scala retains type parameters at runtime (ClassTag)

    1. {runnable}
    2. class ArrayList[X: scala.reflect.ClassTag](val size: Int):
    3. private val a = new Array[X](size)
    4. def put(i: Int, item: X) : Unit = a(i) = item
    5. def get(i: Int) : X = a(i)
    6. end ArrayList
  • Java and Python type parameters are not part of runtime type information

    1. class ArrayList<X> {
    2. private X[] a;
    3. public ArrayList(int n) { a = new X[n]; }
    4. public void put (int i, X item) { a[i] = item; }
    5. public X get (int i) { return a[i]; }
    6. }
    1. error: generic array creation
    2. a = new X[n];
    3. ^

Type Parameter Erasure: Consequences

  • Type parameter erasure in Java and Python
  • Compiler replaces type paremeters X with top type Object and casts
  • When concrete type is needed (e.g., arrays) use Object
  • Some casts cannot be checked and may result in runtime exceptions

    1. class ArrayList<X> {
    2. private X[] a;
    3. ArrayList(int n) {
    4. a = (X[]) new Object[n];
    5. }
    6. void put (int i, X item) { a[i] = item; }
    7. X get (int i) { return a[i]; }
    8. }
    1. warning: [unchecked] unchecked cast
    2. a = (X[]) new Object[n];
    3. ^

Type Parameter Erasure: Consequences

  • Manually inspect code and supress compiler warnings
    1. static class ArrayList<X> {
    2. X[] a;
    3. @SuppressWarnings("unchecked")
    4. ArrayList(int n) {
    5. a = (X[]) new Object[n];
    6. }
    7. void put (int i, X item) { a[i] = item; }
    8. X get (int i) { return a[i]; }
    9. }
  • Why is @SupressWarnings ok?
  • What are the entries of arrat a before any item is placed in it?
  • All references in array are null
  • null can be assigned to any reference type, so also to X and the type it represents

Type Parameter Erasure: Consequences

  • Parameterized and unparameterized aliases can be mixed
  • Casts not checked at compile time when working with unparameterized alias

    1. ArrayList<String> ss = new ArrayList<>(10);
    2. ArrayList os = ss;
    3. os.put (1, 2123456789);
    4. String s = ss.get (1); // ClassCastException when reading
    1. Note: Parametric6.java uses unchecked or unsafe operations.
    2. Note: Recompile with -Xlint:unchecked for details.
    1. ClassCastException: Integer cannot be cast to class String
  • Runtime exception late on reading even though writing is the problem

Type Erasure: Not Necessarily Uniform

  • Java stores types with arrays

  • Alias with top-type not checked at compile time

    1. String[] ss = new String[10];
    2. Object[] os = ss;
    3. os[1] = 2123456789; // ArrayStoreException when writing
    4. String s = ss[1];
    1. ArrayStoreException: Integer
  • Runtime exception early on writing

Parametric Polymorphism with Templates

  • C++ class templates are instantiated with concrete types

  • Compiler checks that types fit to all used operations

    1. template <class T> class Node {
    2. public:
    3. T item;
    4. Node<T>* next;
    5. T getLast() {
    6. Node<T>* c = this;
    7. while (c->next != nullptr)
    8. c = c->next;
    9. return c->item;
    10. }
    11. }
    1. int main(int argc, char* argv[]) {
    2. Node<int>* n = new Node<int>();
    3. n->item = 5;
    4. n->next = new Node<int>();
    5. n->next->item = 6;
    6. cout
    7. << "Last item: "
    8. << n->getLast() << endl;
    9. }

Templates: Consequences

Problems in template not noticed until instantiated

  1. template <class T> class Node {
  2. public:
  3. T item;
  4. Node<T>* next;
  5. // ...
  6. void printCout() {
  7. Node<T>* c = this;
  8. cout << c->item;
  9. while (c->next != nullptr) {
  10. c = c->next;
  11. cout << "," << c->item;
  12. }
  13. cout << endl;
  14. }
  15. }
  • Compiles

    1. int main(int argc, char* argv[]) {
    2. Node<int>* n = new Node<int>();
    3. n->item = 5;
    4. n->printCout();
    5. }
  • Compile error: cannot print Pair

    1. typedef struct { int a; int b; } Pair;
    2. int main(int argc, char* argv[]) {
    3. Node<Pair>* n = new Node<Pair>();
    4. n->item = (Pair) { .a=2, .b=3 };
    5. n->printCout();
    6. }

Parametric Polymorphism: Benefits

  • Generality: one implementation fits many concrete uses
  • Specificity: type parameters constrain possible implementations

    Function with Seq[Int]

    1. def f(xs: Seq[Int]) : Int
    • Many possible implementations: length, minimum, first element, median, sum, ...

    Function with parametric Seq[T]

    1. def f[T](xs: Seq[T]) : Int
    • 1 sensible implementation: length
  • Goal of PL research: functional correctness checked at compile time

Implicit Arguments and Given Instances

Ordering of elements

Subtyping Polymorphism

  1. trait Ord[T]:
  2. def compare(other: Ord[T]): Int
  3. end Ord
  • Add to classes statically

    1. case class MyInt(x: Int) extends Ord[MyInt]:
    2. override def compare(other: Ord[MyInt]) : Int = other match
    3. case MyInt(y) => x - y
    4. end compare
    5. end MyInt
  • Use as types in arguments

    1. def max[T](x: Ord[T], y: Ord[T]): Ord[T] =
    2. if x.compare(y) > 0 then x else y
    3. val m: Ord[MyInt] = max(MyInt(2), MyInt(3))
trait Ord[T]:  
  def compare(other: Ord[T]): Int
end Ord

case class MyInt(x: Int) extends Ord[MyInt]:
  override def compare(other: Ord[MyInt]) : Int = other match
    case MyInt(y) => x - y
  end compare
end MyInt

def max[T](x: Ord[T], y: Ord[T]): Ord[T] =
  if x.compare(y) > 0 then x else y  

max(MyInt(2), MyInt(3))

// EXERCISE add orderable String

// EXERCISE compare two strings using max

Parametric Polymorphism

  1. trait Ord[T]:
  2. def compare(x: T, y: T): Int
  3. end Ord
  • Explicit instance of Ord[T]

    1. val ord = new Ord[Int]:
    2. override def compare(x: Int, y: Int) = x - y
  • Compare items using Ord[T]

    1. def max(x: T, y: T)(ord: Ord[T]): T =
    2. if ord.compare(x,y) > 0 then x else y
    3. val m: Int = max(2, 3)(ord)
trait Ord[T]:  
  def compare(x: T, y: T): Int
end Ord

def max[T](x: T, y: T)(using ord: Ord[T]) =   
  if ord.compare(x, y) > 0 then x else y
end max

given Ord[Int]:
  def compare(x: Int, y: Int) = x-y

max(2, 3)

// EXERCISE: create Ord[String]

// EXERCISE: compare Strings using max

Context Type Bounds

Implicit Arguments and Given Instances

Ordering of elements

Subtyping Polymorphism

Parametric Polymorphism

  1. trait Ord[T]:
  2. def compare(x: T, y: T): Int
  3. end Ord
  • Explicit instance of Ord[T]

    1. val ord = new Ord[Int]:
    2. override def compare(x: Int, y: Int) = x - y
  • Compare items using Ord[T]

    1. def max(x: T, y: T)(ord: Ord[T]): T =
    2. if ord.compare(x,y) > 0 then x else y
    3. val m: Int = max(2, 3)(ord)

Context Type Bounds

  1. trait Ord[T]:
  2. def compare(x: T, y: T): Int
  3. end Ord
  • given instance of Ord[T]

    1. given Ord[Int]:
    2. def compare(x: Int, y: Int): Int = x - y
  • Use context type bounds

    1. def max[T](x: T, y: T)(using ord: Ord[T]): T =
    2. if ord.compare(x,y) > 0 then x else y
    3. val m: Int = max(2, 3)
trait Ord[T]:  
  def compare(x: T, y: T): Int
end Ord
  
given Ord[Int]:
  def compare(x: Int, y: Int): Int = x - y

def max[T](x: T, y: T)(using ord: Ord[T]): T =
  if ord.compare(x,y) > 0 then x else y

max(2, 3)

// EXERCISE: give Ord[String]

// EXERCISE: compare Strings using max

Summoning Instances

  • Explicit named type bound using ord : Ord[T]
    1. def max(x: T, y: T)(using ord: Ord[T]): T =
    2. if ord.compare(x,y) > 0 then x else y
  • Type bound [T : Ord] and summoned instance
    1. def max[T : Ord](x: T, y: T): T =
    2. if summon[Ord[T]].compare(x,y) > 0 then x else y

Summoning Instances

Find the maximum among a sequence of orderable items

  • Explicit forwarding
    1. def maximum[T](xs: Seq[T])(using ord: Ord[T]): T =
    2. xs.reduceLeft(max(_, _)(using ord)) // explicitly forwards ord to max
  • Type bounds

    1. def maximum[T : Ord](xs: Seq[T]): T =
    2. xs.reduceLeft(max) // type bound Ord implicitly forward to max as ord
  • Descending order based on ascending order (using is explicit named type bound)

    1. def desc[T](using asc: Ord[T]): Ord[T] = new Ord[T]:
    2. def compare(x: T, y: T): Int = asc.compare(y, x)
    1. given desc: [T : Ord] => Ord[T]:
    2. def compare(x: T, y: T): Int = summon[Ord[T]].compare(y, x)
  • Find the minimum among a sequence of orderable items

    1. def minimum[T : Ord](xs: List[T]): T =
    2. maximum(xs)(using desc) // pass desc for the type bound of maximum
trait Ord[T]:  
  def compare(x: T, y: T): Int
end Ord
  
given Ord[Int]:
  def compare(x: Int, y: Int): Int = x - y

def max[T](x: T, y: T)(using ord: Ord[T]): T =
  if ord.compare(x,y) > 0 then x else y

max(2, 3)

def maximum[T : Ord](xs: Seq[T]): T =
  xs.reduceLeft(max)
  
maximum(1::2::3::Nil)

def desc[T](using asc: Ord[T]): Ord[T] = new Ord[T]:
  def compare(x: T, y: T): Int = asc.compare(y, x)

def minimum[T : Ord](xs: List[T]): T =
  maximum(xs)(using desc)

minimum(1::2::3::Nil)

// EXERCISE: give an Ord[String] and get the maximum and minimum of a List[String].
//           do the existing maximum and minimum functions work?

Extending Type Bounds

  • Extend ordering on elements to ordering on containers
  • Is a function Ord[T] => Ord[List[T]] of one ordering to another ordering
  • Function can be implemented explicit or using type bounds

    1. def listOrd[T](using ordT: Ord[T]): Ord[List[T]] = new Ord[List[T]]:
    1. given listOrd: [T: Ord] => Ord[List[T]]:
    1. def compare(xs: List[T], ys: List[T]): Int =
    2. (xs, ys) match
    3. // base cases: compare with empty list
    4. case (Nil, Nil) => 0
    5. case (Nil, _) => -1
    6. case (_, Nil) => 1
    7. // recursive case: compare heads and if equal, compare rest
    8. case (x :: xtail, y :: ytail) =>
    9. val firstComp = summon[Ord[T]].compare(x, y) // ordT.compare(x, y)
    10. if firstComp != 0 then firstComp
    11. else compare(xtail, ytail)
    12. end compare
trait Ord[T]:  
  def compare(x: T, y: T): Int
end Ord
  
given Ord[Int]:
  def compare(x: Int, y: Int): Int = x - y

def max[T](x: T, y: T)(using ord: Ord[T]): T =
  if ord.compare(x,y) > 0 then x else y

max(2, 3)

def maximum[T : Ord](xs: Seq[T]): T =
  xs.reduceLeft(max)
  
maximum(1::2::3::Nil)

def desc[T](using asc: Ord[T]): Ord[T] = new Ord[T]:
  def compare(x: T, y: T): Int = asc.compare(y, x)

def minimum[T : Ord](xs: List[T]): T =
  maximum(xs)(using desc)

minimum(1::2::3::Nil)

given listOrd: [T: Ord] => Ord[List[T]]:
  def compare(xs: List[T], ys: List[T]): Int =
    (xs, ys) match
      // base cases: compare with empty list
      case (Nil, Nil) => 0
      case (Nil, _)   => -1
      case (_, Nil)   => 1

      // recursive case: compare heads and if equal, compare rest
      case (x :: xtail, y :: ytail) =>
        val firstComp = summon[Ord[T]].compare(x, y) // ordT.compare(x, y)
        if firstComp != 0 then firstComp
        else compare(xtail, ytail)
  end compare

maximum(List(
  List(1,2,3),
  List(4,5)
))

// EXERCISE: get the maximum and minimum of a List[List[List[Int]]].
//           do the existing maximum and minimum functions work?

// EXERCISE: give an Ord[String] and get the maximum and minimum of a List[List[String]].
//           do the existing maximum and minimum functions work?

Summary: Parametric Polymorphism

Type Parameters

  • Independence between container class and types of contained objects
  • Type safety for reading and writing
  • Not all languages retain type parameters at runtime (Java: compiler knows generics, JVM does not)
  • Functional languages use type parameters to shift "code correctness" to the compiler

C++ templates

  • Template itself has no executable form: List<T>
  • Executable generated for each instantiation: List<int>, List<string>
  • Compile problems hidden until template gets instantiated

Scastie integration for live coding in slides

highlight.js consistent with Scastie (Solarized light theme)

Hidden modal dialogs

Copy code

Scastie embedded Scala editor

Modal dialogs

# <span class="fa-stack"><i class="fa-solid fa-circle fa-stack-2x"></i><i class="fa-solid fa-book fa-stack-1x fa-inverse"></i></span> Parametric Polymorphism - In Java, C#, Ada, Haskell, Scala, Rust, etc - First developed in [ML](https://www.google.com/search?q=ml+programming+language) (1970s, modern descendants: F#, oCaml, Standard ML) - Strong connection to mathematical logic: [Agda](https://wiki.portal.chalmers.se/agda), [Coq](https://coq.inria.fr/about-coq), etc. ---