Simple and Inductive Types

The Sum Type


Learning Objectives

  • You know the sum type terms (inl, inr, and scase) and their intended meaning.
  • You can derive and implement typing rules for sums.
  • You can implement call-by-value reduction rules for injections and sum case matching.

Introduction

Sum types, as you already know from chapter 1 are useful for lots of situations. For example, when we want a variable to hold one of many different types, we could express that using sum types.

DefinitionInjections and Case Matching TermsThe left and right injection terms are denoted inl(𝑡,𝑇2) and inr(𝑡,𝑇1)respectively.To deconstruct a sum, we use the sum case matching termscase(𝑡1,𝑡𝑙,𝑡𝑟) where 𝑡1 represents the scrutinee, 𝑡𝑙 the left case and𝑡𝑟 the right case. The left and right cases are usually abstractions.DefinitionSum Type (𝑇1+𝑇2)The formation rule for the sum of two types is as follows.𝑇1type𝑇2type𝑇1+𝑇2typeNotationWe use scase(𝑡1,𝑥.𝑡𝑙,𝑦.𝑡𝑟) to denote the case matching termscase(𝑡1,𝜆𝑥:𝑇1.𝑡𝑙,𝜆𝑦:𝑇2.𝑡𝑟) where the branches are abstractions.The types 𝑇1 and 𝑇2 are the types of the summands where 𝑡1 hastype 𝑇1+𝑇2.This notation has a more direct connection to the usual case-ofconstruct, which represents the same term.scase𝑡1of|inl(𝑥)𝑡𝑙|inr(𝑦)𝑡𝑟DefinitionValue (Injections)The terms inl(𝑡) and inr(𝑡) are values if 𝑡 is a value.

The dynamics of sum types are straight-forward. We reduce injection terms until they are values. Sum case matching reduces the scrutinee and once it’s an injection, it reduces to the corresponding branch. The types in the injection are not used after type checking so we ignore them (by blanketing them with underscores) during the reduction rules.

DefinitionDynamics of Sums (𝑡CBV𝑡)𝑡CBV𝑡Inl1inl(𝑡)CBVinl(𝑡)𝑡CBV𝑡Inr1inr(𝑡)CBVinr(𝑡)𝑡1CBV𝑡1CaseSum1scase(𝑡1,𝑡𝑙,𝑡𝑟)CBVscase(𝑡1,𝑡𝑙,𝑡𝑟)𝑣valueCaseSumLscase(inl(𝑣,_),𝑡𝑙,𝑡𝑟)CBV𝑡𝑙𝑣𝑣valueCaseSumRscase(inr(𝑣,_),𝑡𝑙,𝑡𝑟)CBV𝑡𝑟𝑣

The rules should seem familiar, because they are very closely related to natural numbers (compare with CaseNat for example).

Typing rules for sums are as follows.

DefinitionTyping Rules for Sums (Γ𝑡::𝑇)Γ𝑡::𝑇1InlΓinl(𝑡,𝑇2)::𝑇1+𝑇2Γ𝑡::𝑇2InrΓinr(𝑡,𝑇1)::𝑇1+𝑇2Γ𝑡𝑙::𝑇1𝑇Γ𝑡𝑟::𝑇2𝑇Γ𝑡1::𝑇1+𝑇2CaseSumΓscase(𝑡1,𝑡𝑙,𝑡𝑟)::𝑇

Again, the CaseSum typing rule reminds us of the CaseNat rule.


Loading Exercise...