Simple and Inductive Types

Pairs and The Product Type


Learning Objectives

  • You know the syntax, typing rules, and call-by-value dynamics for pairs and projections.
  • You can implement pair typing and reduction rules in the Rust STLC evaluator.
  • You know the Unit type and its single canonical value unit.

Introduction

Pairs are a very useful data type for bundling together two pieces of data. The type of a pair is called the product type, or the product of types 𝑇 and 𝑈, and is denoted (𝑇,𝑈) or sometimes 𝑇×𝑈.

DefinitionPair and Projection TermsWe denote a pair of two terms with (𝑡1,𝑡2).The projection terms to the first and second element are denotedfst(𝑡),snd(𝑡).NotationWhen taking the projection of a pair, we can omit parentheses, soinstead of writing fst((𝑡1,𝑡2)) we write fst(𝑡1,𝑡2).

The type of products can be formed given any two types. Its formation rule is as follows.

DefinitionProduct Type (𝑇1,𝑇2)𝑇1type𝑇2type(𝑇1,𝑇2)typeExampleThe following are examples of product types(Bool,Nat)(Bool,(Nat,Bool))(Bool,NatNat)

Notice that the projection terms, like the ncase term from the previous chapter, are not functions in the lambda calculus sense. Even if they were, simple types are not enough to express their types. In a polymorphic language, the projections would have the types

fst:𝐴,𝐵,(𝐴,𝐵)𝐴snd:𝐴,𝐵,(𝐴,𝐵)𝐵

The dynamics of pairs and projections are straight-forward. We reduce inner terms inside pairs so that they have a consistent canonical form. A pair is a value only if and only if both subterms are values (i.e. canonical forms).

DefinitionValue (Pair)The term (𝑡1,𝑡2) is a value if 𝑡1 and 𝑡2 are values.

Reducing the terms inside fst and snd lets them eventually become pairs so that FstPair and SndPair can be applied.

DefinitionDynamics of Products (𝑡CBV𝑡)𝑡1CBV𝑡1Pair1(𝑡1,𝑡2)CBV(𝑡1,𝑡2)𝑡2CBV𝑡2𝑣1valuePair2(𝑣1,𝑡2)CBV(𝑣1,𝑡2)𝑡1CBV𝑡1Fst1fst(𝑡1)CBVfst(𝑡1)𝑡1CBV𝑡1Snd1snd(𝑡1)CBVsnd(𝑡1)FstPairfst(𝑡1,𝑡2)CBV𝑡1SndPairsnd(𝑡1,𝑡2)CBV𝑡2

Typing rules for pairs and projections are not hard to guess:

  1. A pair (𝑡1,𝑡2) of terms 𝑡1::𝑇1 and 𝑡2::𝑇2 has type (𝑇1,𝑇2).
  2. The first and second projections from a term 𝑡::(𝑇1,𝑇2) have type 𝑇1 and 𝑇2 respectively.
DefinitionProduct Typing Rules (Γ𝑡::𝑇)Γ𝑡1::𝑇1Γ𝑡2::𝑇2PairΓ(𝑡1,𝑡2)::(𝑇1,𝑇2)Γ𝑡::(𝑇1,𝑇2)FstΓfst(𝑡)::𝑇1Γ𝑡::(𝑇1,𝑇2)SndΓsnd(𝑡)::𝑇2
Loading Exercise...

Unit/Singleton Type

The singleton type with only one element is called Unit. The element in Rust is written (), but we will just call it unit.

DefinitionTrivial ElementWe denote the trivial element of the Unit type with unit. DefinitionUnit Type (Unit)Unittype DefinitionDynamics of Unit Type (𝑡CBV𝑡)There are no reduction rules.DefinitionUnit Typing Rules (Γ𝑡::𝑇)UnitΓunit::Unit

Implementing the unit type is left as an exercise for the reader. In the next chapter, we implement sum types.