Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Polymorphism and System F

So far, we have only studied simple types, such as Int -> Int, Nat + Bool, or Ref (Int -> Int). What makes these types simple is that they do not support polymorphism, which we will now discuss.

import Lait
#lait

\[ \newcommand{\Nat}{\texttt{Nat}} \newcommand{\List}{\texttt{List}} \]

Polymorphism in Programming Languages

Simply put, polymorphism allows you to write functions that work at multiple types. Already in the lambda calculus, you have been working with a simple example of this: the identity function \(\lambda x. x\). While this function should be able to take in a value of any type, embedding it into STLC requires you to pick a particular type for \(x\), while a polymorphic calculus allows the caller itself to pick the type.

This kind of polymorphism exists in many languages. In Java:

public static <T> T identity(T x) {
    return x;
}

In OCaml:

let id (x : 'a) : 'a = x;;

And in Lait:

def id (x : a) : a := x

Parametric vs Ad-Hoc Polymorphism This style of polymorphism, which we will study, is called parametric polymorphism. This means that we have a single piece of code that works at multiple types. This is essential for code reuse; for example, allowing you to map over a list of type List<Nat> as well as a list of type List<Bool>.

Parametric polymorphism is in contrast to ad-hoc polymorphism, where the type itself also specifies code that we should run. Typically, ad-hoc polymorphism means that a type is equipped with a record that specifies the operations the type allows you to do. An example would be interfaces in Java:

public interface Printable {
    void print();
}

class Text implements Printable {
    private String content;
    public Text(String content) {
        this.content = content;
    }

    @Override
    public void print() {
        System.out.println("Printing: " + content);
    }
}

public class Main {
    public static void printItem(Printable item) {
        item.print();
    }

    public static void Main(String[] args) {
        Printable o = new Text("Hello");
        printItem(o);
    }   
}

Traits and type classes in Rust and Haskell are other examples of ad-hoc polymorphism. Today, while we will study parametric polymorphism, we will see how ad-hoc polymorphism can be encoded.

System F

To study parametric polymorphism, we will design, implement, and study a small language. This language is called System F.

The idea of System F is to extend the simply-typed lambda calculus with the following features:

  • Type Abstraction. We need a way for functions to take in types, as well as values, like the polymorphisc identity function in Java. In our syntax, we will write the polymorphic identity function as follows: \[ \texttt{Id} := \Lambda X. (\lambda x : X.\ x) \] Here, we introduce a new kind of lambda abstraction, \(\Lambda X\), that abstracts over type variables, in constrast to \(\lambda x\), which abstracts over term variables. Thus, the function says “take in a type X; then, take in a value x of type X; then, return X.” This is almost 1-1 with the Java identity example.

  • Type Application. Now that we have a polymorphic identity function, we need to use it. Just like how type abstraction parallels ordinary abstraction over values, type application will behave the same way. We use the following notation for type application: \[ \texttt{id-nat} := \texttt{Id} [\texttt{Nat}] = (\Lambda X. (\lambda x : X.\ x)) [\texttt{Nat}] \] Above, we will have that id-nat has the type we expect: Nat -> Nat. We write type application in square brackets to distinguish it from ordinary application.

  • Universal Types. For this all to work out, we need our polymorphic identity \(\texttt{Id}\) to have a type as well. To do this, we introduce a new kind of type: universal types, written \(\forall X. t\) (read “for all X, t”), where X is a type identifier and t is a type that can make reference to X. This allows us to give the following type to \(\texttt{Id}\): \[ \texttt{Id} =\Lambda X. (\lambda x : X.\ x) : \forall X. X \to X\] You should think of \(\forall X. X \to X\) as like a “type-level lambda”: it is a type that, once given a type for X, gives you back a new type. For example, feeding it \(\texttt{Nat}\) gives you back \(\texttt{Nat} \to \texttt{Nat}\).

We can now specify the surface syntax of System F. For the purpose of having interesting examples, we will also throw in numbers and addition:

\[ \begin{align*} \text{Expressions}\ e ::=\ &x \mid n \mid \lambda x : \tau. e \mid e\ e\ \ \ \ &&\text{Inherited from STLC} \\ &\mid \Lambda X. e &&\text{Type abstraction} \\ &\mid e\ [\tau] &&\text{Type application} \\ \text{Types}\ \tau ::=\ &\texttt{Nat} \mid \tau \to \tau \ \ \ &&\text{Inherited from STLC} \\ & \mid \forall X. \tau &&\text{Forall-types} \\ & \mid X &&\text{Type variables} \end{align*} \]

System F Semantics

The semantics of System F is very similar to STLC. The main difference is that type abstraction and type application interact via beta reduction, similar to ordinary functions. Let’s see how \(\texttt{id-nat}\) from above evaluates, when we apply it to an argument: \[ ((\Lambda X. (\lambda x : X.\ x)) [\texttt{Nat}]) 10 \xrightarrow{\text{Substitute Nat}} (\lambda x : \texttt{Nat}. x) 10 \xrightarrow{\text{Substitute 10}} 10 \]

A more interesting example is a “call-twice” function which takes a type variable X, a function f : X -> X, a value x : X and returns f (f x): \[ \texttt{calltwice} = \Lambda X. \lambda f : X \to X. \lambda x : X. f (f x) \]

Let’s see it evaluate on numbers:

\[ \begin{align*} \texttt{calltwice}\ [\texttt{Nat}]\ (\lambda x : \texttt{Nat}. x + 1)\ 5 &= (((\Lambda X. \lambda f : X \to X. \lambda x : X. f (f x))\ [\texttt{Nat}])\ (\lambda x : \texttt{Nat}. x + 1))\ 5 \\ &\to ((\lambda f : \Nat \to \Nat. \lambda x : \Nat. f (f x))\ (\lambda x : \texttt{Nat}. x + 1))\ 5 \\ &\to (\lambda x : \Nat. (\lambda x : \Nat. x + 1) ((\lambda x : \Nat. x + 1)\ x))\ 5 \\ &\to (\lambda x : \Nat. x + 1) ((\lambda x : \Nat. x + 1)\ 5) \\ &\to \dots \\ &\to 7 \end{align*} \]

System F Types

The ruels for the type system of System F are quite similar to STLC. The difference is that we need to keep track of type variables as well as term variables. To that end, we will have the typing judgment of System F have two contexts: one for type variables, and one for term variables. The judgment looks like this: \[ \Delta; \Gamma \vdash e : \tau \]

Above, the context \(\Gamma\) is just like before: it maps term variables to types. The new context \(\Delta\) is a set of type variables, and only exists to ensure that each type variable is in scope. The types inside of \(\Gamma\) can make reference to the type variables in \(\Delta\).

Let’s now see the rules:

\[ \dfrac{}{\Delta; \Gamma \vdash n : \Nat}\ \text{(T-Num)} \qquad \dfrac{\Delta; \Gamma \vdash e_1 : \Nat \quad \Delta; \Gamma \vdash e_2 : \Nat} {\Delta; \Gamma \vdash e_1 + e_2 : \Nat}\ \text{(T-Add)} \]

\[ \dfrac{(x : \tau) \in \Gamma} {\Delta; \Gamma \vdash x : \tau}\ \text{(T-Var)} \]

\[ \dfrac{\Delta; \Gamma, x : \tau_1 \vdash e : \tau_2} {\Delta; \Gamma \vdash \lambda x : \tau_1.\ e : \tau_1 \to \tau_2}\ \text{(T-Lam)} \qquad \dfrac{\Delta; \Gamma \vdash e_1 : \tau_1 \to \tau_2 \quad \Delta; \Gamma \vdash e_2 : \tau_1} {\Delta; \Gamma \vdash e_1\ e_2 : \tau_2}\ \text{(T-App)} \]

\[ \dfrac{\Delta; X; \Gamma \vdash e : \tau} {\Delta; \Gamma \vdash \Lambda X.\ e : \forall X.\ \tau}\ \text{(T-TLam)} \qquad \dfrac{\Delta; \Gamma \vdash e : \forall X.\ \tau_1 \quad \Delta \vdash \tau_2\ \text{ok}} {\Delta; \Gamma \vdash e\ [\tau_2] : \tau_1[X := \tau_2]}\ \text{(T-TApp)} \]

All of the rules except for (T-TLam) and (T-TApp) are the same as STLC, except for the added context. The rule for \(\Lambda X. e\), (T-TLam), states that we type check \(e\), and then bind the free type variable \(X\) under a \(\forall\). This rule is directly analogous to (T-Lam).

The rule for type application, (T-TApp), states that if \(e\) has type \(\forall X.\ \tau_1\), then \(e[\tau_2]\) has the inner type \(\tau_1\), but with \(\tau_2\) substituted for \(X\). (Note here that we are using square brackets for substitution as well as type application.) This rule requires an auxiliary judgment, \(\Delta \vdash \tau\ \text{ok}\), which enforces that all free type variables are in scope according to Delta.

\[ \dfrac{}{\Delta \vdash \Nat\ \text{ok}}\ \text{(Ok-Nat)} \qquad \dfrac{\Delta \vdash \tau_1\ \text{ok} \quad \Delta \vdash \tau_2\ \text{ok}} {\Delta \vdash \tau_1 \to \tau_2\ \text{ok}}\ \text{(Ok-Arrow)} \]

\[ \dfrac{X \in \Delta} {\Delta \vdash X\ \text{ok}}\ \text{(Ok-Var)} \qquad \dfrac{\Delta, X \vdash \tau\ \text{ok}} {\Delta \vdash \forall X.\ \tau\ \text{ok}}\ \text{(Ok-Forall)} \]

Example typing judgment. Let’s now see how our example \(\texttt{calltwice}\) is well-typed. First, let’s see the typing derivation for \(\texttt{calltwice}\) itself. First, let’s type the body of calltwice under the type abstraction, with the free type variable \(X\) in scope:

\[ X; \emptyset \vdash \lambda f : X \to X.\ \lambda x : X.\ f\ (f\ x) : (X \to X) \to X \to X \]

Now, we can type check calltwice by closing off the inner body under a type abstraction, which removes the free type variable from our context:

\[ \dfrac{\rlap{X}\hphantom{\emptyset}; \emptyset \vdash \hphantom{\Lambda X.\ }\lambda f : X \to X.\ \lambda x : X.\ f\ (f\ x) : \hphantom{\forall X.\ }(X \to X) \to X \to X} {\emptyset; \emptyset \vdash \Lambda X.\ \lambda f : X \to X.\ \lambda x : X.\ f\ (f\ x) : \forall X.\ (X \to X) \to X \to X}\ \text{(T-TLam)} \]

Now, we can apply calltwice to the type Nat:

\[ \dfrac{\emptyset; \emptyset \vdash \texttt{calltwice} : \forall X.\ (X \to X) \to X \to X \quad \emptyset \vdash \Nat\ \text{ok}} {\emptyset; \emptyset \vdash \texttt{calltwice}\ [\Nat] : ((X \to X) \to X \to X)[X := \Nat] = (\Nat \to \Nat) \to \Nat \to \Nat}\ \text{(T-TApp)} \]

System F Types Constrain Implementations

A remarkable fact about System F is that we can infer a lot about terms just based on their types. For example, consider the polymorphic identity function:

\[ \begin{align*} \vdash \texttt{Id} &: \forall X.\ X \to X \\ \texttt{Id} &:= \Lambda X.\ \lambda x : X.\ x \end{align*} \]

Now, here is the cool part: are there any other implementations of \(\forall X. X \to X\) (up to observational equivalence)? It turns out there are not! There is only one. This is due to the fact that \(X\) is an abstract type variable. The implementation must return and \(X\), and it is only given an \(X\); hence, the only thing it can do is return the one it is given.

Following the same logic, let’s now implement Booleans in System F:

\[ \begin{align*} \texttt{Bool} &:= \forall X. X \to X \to X \\ \texttt{false} &:= \Lambda X.\ \lambda x : X.\ \lambda y : X.\ y \
\texttt{true} &:= \Lambda X.\ \lambda x : X.\ \lambda y : X.\ x \end{align*} \]

By the same logic as above, we can see that the two Church booleans are the only possible implementations of the type \(\texttt{Bool}\).

Exercise. What are the possible implementations (if any) of \(\forall X.\ X\)?

Church Numerals in System F

You might have noticed something interesting about our \(\texttt{calltwice}\) example: if you look at the implementation of \(\texttt{calltwice}\), it looks suspiciously similar to the Church numeral for two: \(\lambda f. \lambda x. f\ (f x)\). This is not an accident! Indeed, unlike STLC, the Church numerals can be encoded into System F.

Let’s now derive typed Church numerals in general. The basic idea is that we want to think of a number as how it behaves under iteration: given a function f and an argument x, the numeral for N will apply f to x N times. Since the type of x is arbitrary, we abstract over it. Hence, Church numerals in System F are values of the following type:

\[ \forall X.\ (X \to X) \to X \to X \]

Let’s see some examples:

\[ \begin{align*} \text{zero} &:= \Lambda X. \lambda f : X \to X. \lambda x : X. x \\ \text{one} &:= \Lambda X. \lambda f : X \to X. \lambda x : X. f x \\ \text{two} &:= \Lambda X. \lambda f : X \to X. \lambda x : X. f (f x) \\ & \dots \end{align*} \]

Values of this type are in one-to-one correspondence with actual natural numbers. Let’s see this:

From natural numbers to Church. Suppose we have a natural number N (say, 5). Then, we can create a term that applies f to x that many times: \[ \text{five} := \Lambda X. \lambda f : X \to X. \lambda x : X. f\ (f\ (f\ (f\ (f\ x)))) \]

From Church to natural numbers. Suppose we have a value \(n : \forall X.\ (X \to X) \to X \to X\). Because we can choose any type for \(X\), we can choose \(Nat.\) This allows us to then plug in \((\lambda x: Nat. x + 1)\) for the first argument, and \(0\) for the second argument. This gives us back a closed term of type \(\Nat\) which will evaluate to the corresponding natural number.

Programming with Lists

It turns out that System F is excellent at representing all kinds of data types, and not just Church numerals. Let’s now see how lists work in System F. Similar to Church numerals, the way we represent lists is through their behavior. For natural numbers, the canonical behavior is iterating a functions; for lists, it will be a fold. First, let’s see how folds work in Lait:

def fold(xs : List<t>) (nilCase : r) (consCase : t -> r -> r) : r :=
    match xs with
    | [] => nilCase
    | x :: xs' => consCase x (fold xs' nilCase consCase)

You can think of fold as a generic form of pattern match, where we abstract the body of the pattern match by functions. This, for example, allows us to sum a list, by setting t = Int and r = Int:

def sumList (xs : List<Int>) := fold xs 0 (fun x => fun acc => x + acc)

#eval sumList [1, 2, 3]>> 6

Now, here’s the magic trick: every list xs : List<t> is in one-to-one correspondence with its fold, of type forall r. r -> (t -> r -> r) -> r. We get xs’s fold by partially applying xs to the fold function. We can see this correspondence play out in Lait.

From lists to a folding function. This direction is trivial: take a list xs : List<t>, and output fold xs:

def list_to_fold (xs : List<t>) := fold xs
#check list_to_fold [1, 2, 3]>> a -> (Int -> a -> a) -> a

See that list_to_fold [1, 2, 3] has type a -> (Int -> a -> a) -> a. In Lait, type variables are implicitly universally quantified; thus, this type corresponds to the System F type \(\forall R.\ R \to (\texttt{Int} \to R to R) \to R\).

From folding functions to lists. This is the trick that is analogous with going back from Church numerals to numbers. We have a function of type r -> (Int -> r -> r) -> r, and we want to turn it back into a list of type List<Int>. How to do so? By setting r := List<Int>, and supplying nil and cons to the folding function:

def recovered_list :=
    (list_to_fold [1, 2, 3]) [] (fun x => fun acc => x :: acc)

#eval recovered_list>> Cons 1 (Cons 2 (Cons 3 Nil))

Lists in System F. Now that we have a bijection between lists and an appropriate polymorphic function, we can define lists in System F by this function:

\[ \texttt{List}\ \tau := \forall R.\ R \to (\tau \to R \to R) \to R. \]

Pattern matching over the list just becomes applying the “list” to an appropriate return type, nil case, and cons case. To actually build up a list requires inventing a folding function. First, let’s do nil:

\[ \begin{align*} \vdash \texttt{nil}_\tau &: \List\ \tau \\ \texttt{nil}_\tau &:= \Lambda R.\ \lambda n : R.\ \lambda c : (\tau \to R \to R). n \end{align*} \]

The nil value simply returns the “nil” case of the folding function. Now, let’s do cons:

\[ \begin{align*} \vdash \texttt{cons}_\tau &: \tau \to \List\ \tau \to \List\ \tau \\ \texttt{cons}_\tau &:= \lambda x : \tau.\ \lambda xs : \List\ \tau. \\ &\qquad \Lambda R.\ \lambda n : R.\ \lambda c : (\tau \to R \to R). \\ &\qquad\qquad c\ x\ (xs\ [R]\ n\ c) \end{align*} \]

The implementation of cons x xs creates a folding function that first calls the folding function for xs, and then applies the cons case to it.

Product and Sum Types in System F

Now that we’ve seen Church numerals and lists, we can see how the technique generalizes to product and sum types.

Product Types in System F A pair p : t1 * t2 is in bijection with all of the ways we can pattern match on it. Hence, we can define pairs via their pattern matches. A pattern match on a pair has one arm which takes both values. In Lait, it looks like this:

type MyProd<a, b> := | MkMyProd (x : a) (y : b)

def matchMyProd(p : MyProd<a, b>) (f : a -> b -> r) : r :=
    match p with
    | MkMyProd x y => f x y
    end

Which means that it looks as follows in System F:

\[ \texttt{Prod}_{\tau_1, \tau_2} := \forall R.\ (\tau_1 \to \tau_2 \to R) \to R \]

We can then construst pairs by implementing the pattern match.

\[ \begin{align*} \vdash \texttt{pair}_{\tau_1, \tau_2} &: \tau_1 \to \tau_2 \to \texttt{Prod}_{\tau_1, \tau_2} \\ \texttt{pair}_{\tau_1, \tau_2} &:= \lambda x : \tau_1.\ \lambda y : \tau_2.\ \Lambda R.\ \lambda f : (\tau_1 \to \tau_2 \to R). f\ x\ y \end{align*} \]

Sum Types in System F A sum type v : t1 + t2 can be pattern matched on by two arms, each of which takes one value. In Lait, that looks like this:

type Sum<a, b> := | Inl (x : a) | Inr (y : b)

def matchSum(p : Sum<a, b>) (f : a -> r) (g : b -> r) : r :=
    match p with
    | Inl x => f x
    | Inr y => g y
    end

Which means that sums have the following type in System F:

\[ \texttt{Sum}_{\tau_1, \tau_2} := \forall R.\ (\tau_1 \to R) \to (\tau_2 \to R) \to R\]

We can then construct elements of a sum type by calling the appropriate functions:

\[ \begin{align*} \vdash \texttt{inl}_{\tau_1, \tau_2} &: \tau_1 \to \texttt{Sum}_{\tau_1, \tau_2} \\ \texttt{inl}_{\tau_1, \tau_2} &:= \lambda x : \tau_1.\ \Lambda R.\ \lambda f : (\tau_1 \to R).\ \lambda g : (\tau_2 \to R). f\ x \\ \\ \vdash \texttt{inr}_{\tau_1, \tau_2} &: \tau_2 \to \texttt{Sum}_{\tau_1, \tau_2} \\ \texttt{inr}_{\tau_1, \tau_2} &:= \lambda y : \tau_2.\ \Lambda R.\ \lambda f : (\tau_1 \to R).\ \lambda g : (\tau_2 \to R). g\ y \end{align*} \]

Enabling Ad-Hoc Polymorphism

Let’s consider an interface in Java called Show:

interface Show {
    String show();
}

class Main {
    public static String WithBraces(Show t) {
        String x = t.show();
        return "{" + x + "}";
    }
}

We can think of WithBraces as a polymorphic function that takes in an arbitrary value t of an arbitrary type T, so long as T implements the Show interface. We can implement this in a language with parametric polymorphism by passing around a field that holds the stuff that T needs to implement:

\[ \texttt{Show}_\tau := \tau \to \texttt{String} \]

(If Show had multiple fields, we could put them together by using a product type.)

Then, we can implement WithBraces by taking in the type T and a value t : T, along with the \(\texttt{Show}\) field:

\[ \begin{align*} \vdash \texttt{WithBraces} &: \forall T.\ \texttt{Show}_T \to T \to \texttt{String} \\ \texttt{WithBraces} &:= \Lambda T.\ \lambda f : \texttt{Show}_T.\ \lambda x : T. \\ &\qquad \texttt{"\{"} \mathbin{\texttt{++}} f\ x \mathbin{\texttt{++}} \texttt{"\}"} \end{align*} \]