46
Type Inference For a Modal Type System Yiluo Wei Supervisor: Ranald Clouston A report submitted for the course of COMP3740 Project Work in Computing The Australian National University May 2019

Type Inference For a Modal Type System · to di erent modal logics, including Intuitionistic K, Intuitionistic S4 and Intuitionistic R. I then modify the interpreter of the language,

  • Upload
    others

  • View
    6

  • Download
    1

Embed Size (px)

Citation preview

Type Inference For a Modal TypeSystem

Yiluo WeiSupervisor: Ranald Clouston

A report submitted for the course ofCOMP3740

Project Work in ComputingThe Australian National University

May 2019

c© Yiluo Wei 2019

Except where otherwise indicated, this report is my own original work. My work as intro-duced in this report is based on the work of Clouston [5] of Fitch-Style Modal Lambda Calculiand part of the project "Write You a Haskell" written by Diehl [8].

Yiluo Wei30 May 2019

Abstract

In this report, I extend a lambda-calculus-style language with modalities, � and _, as typeformers. By adding new syntax, typing and evaluation rules, I make the language correspondsto different modal logics, including Intuitionistic K , Intuitionistic S4 and Intuitionistic R. Ithen modify the interpreter of the language, especially for the typing part, where I extend theHindley-Milner type inference algorithm so it works with modal types. I also add product andsum types to the language. Finally, I do a performance analysis on the type inference algorithmto find that modalities will affect the running speed but in most cases it is acceptable.

v

vi

Contents

Abstract v

1 Introduction 11.1 Proposition as Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Intuitionistic Modal Logic and Types . . . . . . . . . . . . . . . . . . . . . . . 11.3 Fitch-Style Modal Lambda Calculi . . . . . . . . . . . . . . . . . . . . . . . . 21.4 Type Inference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.5 Contribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.6 Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

2 Background 52.1 Language Poly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2.1.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.1.2 Typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.1.3 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.1.4 How to Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.2 Hindley-Milner Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.2.1 Constraint and Unification . . . . . . . . . . . . . . . . . . . . . . . . 62.2.2 Pseudo-Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.2.3 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

3 Intuitionistic K 93.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93.2 Typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

3.2.1 Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93.2.2 Typing Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103.2.3 Type Inference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

3.3 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

4 Left Adjoint 134.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134.2 Typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

4.2.1 Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134.2.2 Typing rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144.2.3 Type Inference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

vii

viii Contents

4.3 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

5 Intuitionistic S4 175.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175.2 Typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175.3 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185.4 Left Adjoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

6 Intuitionistic R 196.1 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196.2 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

7 Other Features 217.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217.2 Typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217.3 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

8 Performance 238.1 Randomly Generated Expressions . . . . . . . . . . . . . . . . . . . . . . . . 238.2 Expressions With Dense Lock . . . . . . . . . . . . . . . . . . . . . . . . . . 248.3 Randomly Generated Typed Expressions . . . . . . . . . . . . . . . . . . . . . 248.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

9 Conclusion 279.1 Future Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

9.1.1 Complete Random Testing of Well Typed Expressions . . . . . . . . . 279.1.2 More Efficient Type Inference . . . . . . . . . . . . . . . . . . . . . . 279.1.3 More Modal Logics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279.1.4 More Advanced Language Features . . . . . . . . . . . . . . . . . . . 28

A Project Description 29A.1 TITLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29A.2 LEARNING OBJECTIVES . . . . . . . . . . . . . . . . . . . . . . . . . . . 29A.3 PROJECT DESCRIPTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

B Study Contract 31

C Artefact 35C.1 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35C.2 How to use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35C.3 License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

Chapter 1

Introduction

1.1 Proposition as Types

The Curry-Howard isomorphism, also known as proposition-as-types, links two fields of study,natural deduction and typed lambda calculus, which were thought to be separate [11; 25; 27].Based on the Curry-Howard isomorphism, various kinds of work are done in both logic andcomputing. For the field of logic, there are proof assistants such as Coq, which, with the useof dependent types, builds and checks logical proofs by constructing terms with correspondingtypes. For the field of computing, some new type systems, which are inspired by the corre-sponding logic are proposed to address special problems. For example, linear type systemfrom linear logic can be used to handle problems regarding memory management, such as datadeallocation [21]. My work will focus on intuitionistic modal logic and building a type systemwith modalities.

1.2 Intuitionistic Modal Logic and Types

Intuitionistic logic differs from classical logic in the absence of the Aristotelian law of excludedmiddle. The logic side of the Curry-Howard isomorphism is based on intuitionistic logic ratherthan classical logic [14]. Modal logic is primarily developed in 1960s as an extension of clas-sical propositional and predicate logic, where modals, as operators to express modalities, areintroduced to qualify a statement [22]. The basic unary modal operators are � and ^, whichstands for "Necessarily" and "Possibly" respectively. For example, if A is a statement of "peo-ple die if they are killed", then �A means "it is necessary that people die if they are killed".The chapters after are based on intuitionistic modal logic, which, roughly speaking, is a resultof adding modals to intuitionistic logic instead of classical logic [24].

The necessity modality, �, in intuitionistic normal modal logic is widely studied and appliedto types in particular. A famous example is the article of Moggi [18] about monads. Otherwork includes staged programming [7], propositional truncation [1] and homotopy type theory[23]. According to Clouston, "there is hence a need to develop all sides of the Curry-Howardisomorphism for necessity modalities" [5].

1

2 Introduction

1.3 Fitch-Style Modal Lambda Calculi

Fitch-style modal lambda calculi is first proposed by Borghuis [3] and by Martini and Masini[15]. It is highly intuitive with the Kripke’s semantics. Roughly speaking, in Kripke’s seman-tic, there is a set of worlds and a relation between the worlds. Let A be a proposition whichholds in world W , then �A means that in all worlds related to W , A also holds. The Fitch-stylecalculi uses a subordinate proof to represent the general world related to W thus in this sub-ordinate proof, A will hold but �A will not. Furthermore, if I prove a subordinate propositionB, I can conclude in the main proof that �B holds. Intuitively, this corresponds to "leavingthe general world related to W and come back to W". More formal descriptions of Fitch-stylemodal lambda calculi can be found in [5]. Fitch-style calculi is also convenient to be madeinto type system. The action of entering and leaving subordinate proof can be abstracted totwo operations, namely open and shut. This will be introduced in Chapter 3.

1.4 Type Inference

Type inference is a technique of automatically detecting the type of an expression in a program-ming language, which makes it possible to do type checking with type annotations omitted. Itis widely used in various kinds of programming languages, especially in functional languagessuch as ML and Haskell. Type inference for modal type systems is a major topic of my work.My project uses the Hindley-Milner (HM) algorithm, which is widely used for type inferenceand is first described by J. Roger Hindley [13] and later by Robin Milner [17]. I also providean introduction of the algorithm in 2.2.

1.5 Contribution

Few works have been done so far to examine the algorithmic properties (e.g., type inference)piratically on an implementation of a modal type system. My work is an implementation ofthe type system that corresponds to necessity modalities. Specifically, my work is a lambda-calculus style language called Poly (see 2.1) extended with modalities, together with an inter-preter that can evaluate the language and can also perform type inference on the language. Theprogram is based on part of the "Write you a Haskell" project [8], which implements the basicsyntax, typing, type inference and evaluation of the Poly language. I extend and modify it toinclude the necessity modality, �, and make the type system corresponds to different kinds ofmodal logic including IK , IS4 and IR by adding different typing rules. I then further extendthese three systems by adding the left adjoint _. I also modify the type inference algorithm sothat it can work with modalities.

§1.6 Outline 3

1.6 Outline

In Chapter 2, I will introduce the background, including the language definition and a short in-troduction to the Hindley-Milner type inference algorithm that is used through out the program.In Chapter 3, I introduce how to add modality to the language to implement a type system thatcorresponds to system Intuitionistic K . In Chapter 4, I add another modality _, which is theleft adjoint. In Chapter 5, I further extend the system from Intuitionistic K to Intuitionistic S4.In Chapter 6, I discuss the type system corresponding to Intuitionistic R. In Chapter 7, I brieflydiscuss other language features that I added. In Chapter 8, I do a performance analysis on myprogram. Chapter 9 will be the conclusion with a discussion of related and further work.

4 Introduction

Chapter 2

Background

This chapter provides necessary background information and knowledge related to the follow-ing chapters. Section 2.1 briefly describes the language named Poly, which is extended in myproject. It is part of a Haskell project written in by Diehl in [8], where the complete defini-tion of syntax, typing and evaluation can also be found. Section 2.2 is a short introduction ofthe Hindley-Milner type inference algorithm. Readers who are familiar with it may skip thissection.

2.1 Language Poly

2.1.1 Syntax

The expression in Poly is formally defined as

Expr := Var | Int | Bool | λVar.Expr | fix Expr | Expr Expr |let Var = Expr in Expr |

if Expr then Expr else Expr

where Var is a variable name and fix is a fix-point operator to define recursive functions.Besides the expression, Poly also accepts declaration, which will not evaluate but extend theenvironment with newly declared variables. The declaration is formally defined as

Decl := let Var = Expr | let rec Var = Expr

where Var is a variable name and let rec is a syntactic sugar for fix when defining a recursivefunction. The detail of the syntax can be found in [8] and also in "Syntax.hs" and "Parser.hs".

2.1.2 Typing

The basic types are Int and Bool. There is certainly an Arrow type for function abstraction.Poly also supports polymorphism with universal type notation. For example λx .x will havetype ∀a.a → a where a is the type variable. The polymorphism feature also simplifies thework for type inference. The type is formally defined as

type := Int | Bool | type → type | TVar | ∀ TVars.type

where TVar is a type variable name and TVars is a list of TVar.

5

6 Background

2.1.3 Evaluation

The evaluation is written in a call-by-value style. However, the implementation is in Haskell,which means the evaluation is lazy by default. The evaluation rules can be found in [8].

2.1.4 How to Use

I include a short instruction in the appendix C. The software also contains a "read me" filewhich presents a more detailed tutorial.

2.2 Hindley-Milner Algorithm

Hindley-Milner (HM) algorithm is a widely used algorithm for type inference. The goal oftype inference is to construct a possible type for an expression with no type annotations. Inmathematics, if I do not know the value of something, I can set variables, say, x and y forit. Then I use a set of equations about x and y to solve for the value of the variables. Theequations are also called constraints. The same principle is applied in the HM algorithm whereevery unknown type is assigned a type variable and the constraints are identified and collectedaccording to the syntax of the expression. Then the constraints are unified (solved) to producethe value of the type variables. Finally, the free type variables are built into universal types.

2.2.1 Constraint and Unification

I use the notation T1 ∼ T2 to represent a constraint of type T1 and T2 and T1 ∼ T2 : θ meansthe type T1 and T2 can be unified with a substitution θ. Roughly, by applying the substitutionθ, T1 and T2 will be the same type. The unification rules for Poly can be found in [8].

2.2.2 Pseudo-Code

The HM algorithm runs depending on the syntax of the expression. Suppose the expression ehas syntax of a function abstraction λx .e′, then

infer e :=

1. Produce a free type variable T1 for x

2. T2 = infer e′ with x : T1 added to the environment

3. infer e′ will also produce a set of constraints C

4. According to the syntax, e should have type T1 → T2

5. Solve the constraint C, substitute the result into T1 and T2, generalize free variables intouniversal types, return T1 → T2.

Suppose the expression of e has syntax of a function application e1 e2, then

§2.3 Summary 7

infer e :=

1. Produce a free type variable T for e

2. T1 = infer e1 and produce a set of constraints C1

3. T2 = infer e2 and produce a set of constraints C2

4. According to the syntax, e1 should have type T2 → T

5. Generate constraints C : T1 ∼ T2 → T

6. Solve the constraint C1 ∪ C2 ∪ C, substitute the result into T , generalize free variablesinto universal types, return T .

These two sections of pseudo-code give a general idea of how the HM algorithm works ac-cording to the syntax of the expression and the typing rules. For the expressions of differentsyntax, the algorithm runs in a similar manner.

2.2.3 Example

λx .λy.x + y

1. According to the syntax, the expression must have have type Tx → Ta where Tx and Taare both type variables

2. Assign Tx to y, and under Γ, x : Tx , Ta is the same type as the type of λy.x + y.

3. Similarly, λy.x + y has type Ty → Tb. Assign Ty to y and under Γ, x : Tx , y : Ty,Tb = infer x + y.

4. Collect a constraint here, that is, Ta = Ty → Tb.

5. Then for x + y there are three constraints to collect, Tx = Int, Ty = Int and Tb = Int.

6. The return type is Tx → Ta . Solve the constraint and do the substitution to get Int →(Int → Int)

7. λx .λy.x + y has type Int → (Int → Int)

2.3 Summary

This chapter provides a overview of the background of the project including the basic languageand algorithm used. However, The language will be extended in the following chapters andnew rules for syntax, typing and evaluation may be introduced.

8 Background

Chapter 3

Intuitionistic K

In this chapter I extend the language so that the type system of the language corresponds tothe Intuitionistic K (IK) in modal logic. IK is the most basic logic for necessity, and was firstpresented as HK� [4]. IK adds a new symbol, �, which servers as a unary connective to intu-itionistic logic. IK also introduces one new axiom K and one new inference rule Necessitation,where K : �(A → B) → �A → �B and Necessitation : if A is a theorem, then so is �A.To make the type system able to derive the axiom, the modification and extension are made onsyntax, evaluation, typing and type inference.

3.1 Syntax

Two new syntax rules are introduced here, namely open and shut, which intuitively corre-sponding to entering and leaving a subordinate proof respectively [5]. Formally, let Exprdenotes expressions, then

Expr := ... | shut Expr | open Expr

3.2 Typing

I first add � as a first-class-type-former and formally, let type denotes types, then

type := ... | �type

3.2.1 Context

I here define the context. Formally, let Γ be the context, then

Γ := · | Γ, x : A | Γ, b

where x is an expression, A is a type and b is called a Lock, which is used to indicate that a �has been opened. The implementation of the context is heavily modified to accommodate theexistence of Lock but the signature of interface functions such as insert and lookup remainsthe same.

9

10 Intuitionistic K

3.2.2 Typing Rules

The sum and product types 7 are not yet introduced here while the function abstraction andapplication rule do not change.

varΓ, x : A, Γ′ ` x : A

b< Γ′

shutΓ, b ` t : A

Γ ` shut t : �A

openΓ, t : �A

Γ, b, Γ′ ` open t : Ab< Γ′

The rules are also given in [5]. Note that according to the var rule, a variable cannot beaccessed if there is a Lock to its right. Therefore, the variable cannot be found if it is not in thescope or it is blocked by Lock.

3.2.3 Type Inference

The type inference uses the Hindley-Milner algorithm as introduced in 2.2. According to therules in 3.2.2, I first modify the rule of variables. The change is made on the lookup functionof the context. It will iterate through the context List until it finds the variable in a Map toreturn a type or meets a Lock to return Nothing.

Then I add the rules for open and shut. The shut rule is straightforward. For shut e Ionly need to add a � to the inferred type of e in the context with a new Lock. The open rulerequires a bit more work. For open e I need to remove a Lock from the context to infer e andconstraint the type of e to be �t for some type t. Then t, if the constraints are solvable, is thetype for open e.

I also add new unification rules for � type:

boxT1 ∼ T2 : θ�T1 ∼ �T2 : θ

3.3 Evaluation

A term is a value if it cannot be further reduced. Then I introduce the new reduction rules.Formally,

shutt 7→ t′

shut t 7→ shut t′open1

t 7→ t′

open t 7→ open t′

open2value t

open shut t 7→ t

§3.4 Summary 11

As is mentioned in 2.1.3, the evaluation is lazy because of Haskell, although it is written inthis style.

3.4 Summary

Now IK is successfully added to the language. I should be able to derive

K : �(A → B)→ �A → �B

To test the result, load the "MainK.hs" file and call the function main to enter the interactiveenvironment. Type the expression

λf .λx .shut (open f ) (open x)

which should have the type

∀a b. �(a → b)→ �a → �b

The inference rule Necessitation can also be tested. It is a theorem that 0 has type Int. Typeshut0 which should have type �Int.

12 Intuitionistic K

Chapter 4

Left Adjoint

In this Chapter, I extend the language with the left adjoint _ for IK . The corresponding logicis ’intuitionistic logic with a Galois connection’ proposed in [9]. I will use the name IK_. IK_introduces two new axioms

ηm : A → �_Aϸm : _�A → A

This also introduces one new inference rule

Monotonicity: if A → B is a theorem, then so is _A → _B

To implement IK_, modification and extension are made on syntax, evaluation, typing and typeinference.

4.1 Syntax

Two new syntax rules, dia (short for ’diamond’) and letdia, are added to the language. For-mally, let Expr denotes expressions and Var variables, then

Expr := ... | dia Expr | let (dia Var) = Expr in Expr

The letdia rule is roughly the same as let rule, with the difference that letdia accepts dia Varonly and let accepts Var only.

4.2 Typing

The type system will include _ as a first-class-type-former. The type system now containsboth � and _. Formally, let type denotes types, then

type := ... | _type | �type

4.2.1 Context

The context is the same as IK (see 3.2).

13

14 Left Adjoint

4.2.2 Typing rules

To derive the new axioms I extend IK with the following two typing rules.

diaΓ ` t : A

Γ, b, Γ′ ` dia t : _Ab< Γ′

letdiaΓ ` t : _A x : A, b ` u : B

Γ ` let dia x = t in u : B

Note that in the right upper side of the letdia rule, I do NOT miss a Γ.

4.2.3 Type Inference

The type inference for dia is similar to open. In IK_, I need to first check whether there is aLock in the environment when inferring dia e. Then I infer e in the environment where oneLock and everything to the right of it are removed and let t = infer e. If t is unifiable, the typeof dia e is _t. To infer (letdia n e1 e2), I need to infer e1 first and constraint the type of e1

to be _A for some type A. Then I infer e2 in the environment with only n : A to the left of aLock and let B be the inferred type. If all constraints are unifiable, the type of (letdia n e1 e2)is B. I also add a new unification rule for _:

diaT1 ∼ T2 : θ_T1 ∼ _T2 : θ

4.3 Evaluation

I first add a new value form vdia e for some value e. Then the corresponding reduction rules:

diat 7→ t′

dia t 7→ dia t′

letdiavalue t

let dia x = dia t in u 7→ u[t/x ]

Note that in the letdia rule, u[t/x ] means to substitute all t with x in u. Also, x can onlybe an identifier as defined by the syntax 2.1.1, but not an expression. Therefore, I do not needto reduce x and can directly do the substitution.

§4.4 Summary 15

4.4 Summary

Now I extend IK to IK_. I should be able to derive ηm and ϸm . To test it, load the "MainK.hs"file and call the functionmain to enter the interactive environment. For ηm , type the expression

λx .shut dia x

which should have type

∀a. a → �_a

For ϸm , type the expression

λx .let dia y = x in open y

which should have type

∀a. _�a → a

The inference rule Monotonicity can also be tested. Let f be (== 0) as a function that hastype Int → Bool. Type the expression

λx .let dia y = x in dia (y == 0)

which should have type

_Int → _Bool

16 Left Adjoint

Chapter 5

Intuitionistic S4

In this chapter I extend the language so that the type system of the language corresponds tothe Intuitionistic S4 (IS4) in modal logic. IS4 is widely studied and applied and in the fieldof category theory it corresponds to comonad. Clouston [5] suggests that by restricting toidempotent comonads, where �A and ��A are isomorphic, the calculi can be simpler than thethe existing two [20; 7]. IS4 extends IK with two new axioms

T : �A → A4 : �A → ��A

To make the type system able to derive the axioms, the further modification and extension aremade based on IK in Chapter 3.

5.1 Syntax

The syntax is the same as IK in 3.1, with open and shut.

5.2 Typing

The var rule and the shut rule in 3.2 are not changed. The only modification is on the openrule. In IS4 it does not require a Lock in the environment to type an open expression [5].Formally, the new open rule is

openΓ ` t : �A

Γ, Γ′ ` open t : A

The type inference for open now is more tricky. Note that the open rule is not determinis-tic because for a context, I can make any division of Γ and Γ′. I observe that an inference fora term will succeed only if all free variables in the term are accessible in the context. I usethis observation in my algorithm, which, when inferring open t, will always try to give a Γ inwhich all free variables in t are accessible. More specifically, for a context of the form

Γ = Γ1, b, Γ2, b, ... Γn−1, b, Γn

The algorithm will first check whether the all free variables are accessible in Γ. If they are,then do the type inference with Γ. If they are not, then it will recurs with

17

18 Intuitionistic S4

Γ = Γ1, b, Γ2, b, ... Γn−1

that is, throw away the right most Lock and everything to the right of this Lock. Intuitively,everything to the left of this Lock is blocked, therefore, the algorithm need to get rid of thisLock so that it can access to some new variables to make a difference. If finally Γ becomes freeof Lock but the free-variable check still fails, the algorithm will raise an error.

However, it also has a problem when producing error messages, which cannot tell exactlywhich variable is not in the scope. For example, to infer the expression

λx .shut λy.open (x y)

the algorithm will need to make a division in the context

x : T1, b, y : T2

to infer the x y in the expression open (x y). However, no division with both x and y accessibleis possible. It can only put an error message that either x or y is not in the scope. Or it couldsay something like "cannot find a good division of the context" but this is even more confusing.

5.3 Evaluation

The evaluation rules do not change from 3.3. However, more terms are now able to be evaluatedbecause of the change on typing rules.

5.4 Left Adjoint

To add left adjoint _ to IS4 is simple based on the implementation of IK_ in Chapter 4. Themodification is made on the typing rules and type inference of dia, where

diaΓ ` t : A

Γ, Γ′ ` dia t : _A

The type inference for dia is similar to open as discussed in 5.2. The algorithm will try tofind a proper division of Γ and Γ′ to deal with the non-determinism.

5.5 Summary

Now I extend IK to IS4. I should be able to derive the two axioms T and 4 as well as K . To testit, load the "MainS4.hs" file and call the function main to enter the interactive environment.For T and 4, type the expression

λx .open xλx .shut shut open x

which should respectively have type

∀a. �a → a∀a. �a → ��a

Chapter 6

Intuitionistic R

Intuitionistic R (IR) extends IK with the axiom

R : A → �A

which was first studied by Curry in his work on monads with another axiom M [6]. Then thelogic with R but without M is showed to correspond to applicative functors in programminglanguages by McBride and Paterson [16].

6.1 Implementation

The implementation for IR is straightforward. The only thing differing from IK in Chapter 3 isthe typing rules for variable, open and with introducing the _, dia, where the side conditionb< Γ′ is removed. Formally

varΓ, x : A, Γ′ ` x : A

openΓ, t : �A

Γ, b, Γ′ ` open t : A

diaΓ ` t : A

Γ, b, Γ′ ` dia t : _A

All variables are accessible regardless of the Lock. The modification is made on the envi-ronment. Roughly, now the function to look up the environment will simply ignore any Lock.While for the open and dia rules, it still requires at least one Lock in the environment. Myimplementation will remove the rightmost Lock. This uses the same intuition as described in5.2 that the algorithm looks for a Γ where every free variable is accessible. In IR, the Lockdoes not block the access, therefore, the algorithm only needs to keep the environment with asmany variables as possible.

19

20 Intuitionistic R

6.2 Summary

Now I can derive the axiom, R. To test it, load the "MainR.hs" file and call the function mainto enter the interactive environment. Type the expression

λx .shut x

which should have type

∀a. a → �a

Chapter 7

Other Features

In this chapter I add product types and sum types to the language. It is interesting to see howmodal types systems work with more advanced language features. It may also be a help whenintroducing other modalities. I will briefly introduce the syntax, typing rules and evaluationwhile not go through the details.

7.1 Syntax

The new syntax rules are

Expr := ... | < Expr, Expr > | fst Expr | snd Expr | inl Expr | inr Expr |case Expr {Var.Expr} {Var.Expr}

7.2 Typing

I first add the type former + and ∗.

type := ... | type+ type | type ∗ type

The typing rules are

proΓ ` e1 : t1 Γ ` e2 : t2

Γ ` <e1, e2> : t1 ∗ t2

fstΓ ` e : t1 ∗ t2Γ ` fst e : t1

sndΓ ` e : t1 ∗ t2Γ ` snd e : t2

inlΓ ` e : t1 Γ ` t2Γ ` inl e : t1 + t2

inrΓ ` e : t1 Γ ` t2Γ ` inr e : t2 + t1

caseΓ ` e1 : t1 + t2 Γ,a : t1 ` e2 : t3 Γ, b : t2 ` e3 : t3

Γ ` case e1 {a.e2} {b.e3} : t3

21

22 Other Features

7.3 Evaluation

Most of the evaluation rules are trivial and I only present the rule for case here. Note that theimplementation is in Haskell thus the evaluation is lazy.

case1

e1 7→ inl e′1

case e1 {a.e2} {b.e3} 7→ e2[a/e′1]

case2

e1 7→ inr e′1

case e1 {a.e2} {b.e3} 7→ e3[b/e′1]

7.4 Summary

Sum types and product types work in the language. In the future more advanced features maybe added to the language.

Chapter 8

Performance

8.1 Randomly Generated Expressions

I use the test-suite AutoBench [12] to do a performance analysis of my program. I first com-pare the performance of my type inference algorithm for randomly generated expressions ofdifferent sizes. The figure shows the running times for all three modal type systems, IK , IR andIS4. It should be noted that most of these randomly generated expressions cannot be typed,that is, the type inference is expected to fail. Also, it is expected that the type inference mayfail quickly since it does not always need to go through the whole expression to find an in-consistency. It can be seen that the failing speed of IR and IK are almost identical while S4sometimes takes much more time. I further investigate this problem in the following sections.

Figure 8.1: Random Expressions

23

24 Performance

8.2 Expressions With Dense Lock

The only difference between IS4 and IK is that when inferring open in IS4, more work needsto be done as described in 5.2. I think the open term with Lock in the environment make typeinference in S4 slow. Therefore, I set the testing data as n shut terms followed by one openterm, where n is the input size. It seems that what I think is correct according to the figure8.2. However, the running time is still linear to the input size, which is acceptable. I also ranthe test with randomly generated expressions with no open terms for comparison in figure 8.3,where IK and IS4 have similar running time.

8.3 Randomly Generated Typed Expressions

In this section, I aim to use randomly generated but well-typed expressions to test the perfor-mance of my algorithm. Unfortunately, I am not able to do a complete version of this case.The algorithms for as described in [26; 19; 10] for generating well-typed lambda expressionsare as complicated as the type inference algorithm. It is like a reversed procedure of type infer-ence, and involving more non-determinism. I am not able to implement a complete generatorincluding all syntax rules in the language. However, by cutting the syntax, to include only thefunction abstraction, function application, shut, open, variables and literals, I made a simplifiedgenerator. It captures the most important features of the language. The result is presented infigure 8.4. I also ran the test with the same configuration but further exclude the shut and openexpressions (that is, without modal types) for comparison. The result is presented in figure 8.5.It can be seen that there is no significant difference in the performance.

8.4 Summary

By doing performance analysis, I show that in some cases, type inference in IS4 will take moretime than IK and IR. This difference is still acceptable, however, I think it will be better if theperformance can be improved.

§8.4 Summary 25

Figure 8.2: Dense Lock Environment

Figure 8.3: No Lock Environment

26 Performance

Figure 8.4: Random Well Typed Expressions

Figure 8.5: Random Well Typed Expressions Without Modals

Chapter 9

Conclusion

In this project, I extend the λ-calculus with modalities and build modal type systems corre-sponding to different modal logics, including intuitionistic K , intuitionistic S4 and intuitionis-tic R. Besides the basic �, I also add the left adjoint _. I modify the Hindley-Milner algorithmso that it is possible to perform type inference in modal type systems. I then add product typesand sum types to the language and they work with modalities. I also do a performance analy-sis, which suggests that the current implementation of type inference may not be very efficientwhen handling Locks in the environment. However, the random tests also suggest that in mostsituations, the running time with or without the Lock are close. Finally, I would like to discusssome future work that can be done based on this project.

9.1 Future Work

9.1.1 Complete Random Testing of Well Typed Expressions

The current random generator only covers a subset of the language. By completing the randomgenerator, more reliable and valuable test and performance data can be collected.

9.1.2 More Efficient Type Inference

As is showed in Chapter 8, the current implementation of type inference is not very efficient es-pecially with many Lock in the environment. There could be some more sophisticated methodsto make it run faster. Possible improvement includes a better data structure for environmentand a better strategy to deal with non-determinism in typing rules. Also, it may produce bettererror message as discussed in section 5.2.

9.1.3 More Modal Logics

In this project I implement intuitionistic K , intuitionistic S4 and intuitionistic R. It is alsopossible to include more modal logics with different axioms by adjusting the typing rules andtype inference rules. New modality can also be introduced as a type former.

27

28 Conclusion

9.1.4 More Advanced Language Features

Besides product types and sum types, more advanced language features may be added in thelanguage. A possible example can be dependent types, which is discussed in this paper [2].

Appendix A

Project Description

A.1 TITLE

Type inference for a modal type system

A.2 LEARNING OBJECTIVES

Upon successful completion, the student will have the knowledge and skills to: 1, Understandand discuss the Hindley-Milner type inference algorithm 2, Understand and discuss the ’propo-sitions as types’ connection between logic and type systems, in particular as applied to modallogic 3, Modify the Hindley-Milner type inference algorithm to work for a type system basedon a modal logic

A.3 PROJECT DESCRIPTION

Modal logic is a well-known family of logics involving ’modalities’, operators which modifythe truth of a proposition. ’Propositions as types’ is a concept relating logic to type theorywhich is important both to theoretical computer science and to the practical design of typesystems. The propositions as types interpretation of modal logics is an increasingly populararea of research with a number of applications. As a relatively new area of research, manybasic algorithmic questions about such type systems have not yet been investigated. In thisproject the student will investigate the extension to a basic modal type system of the well-known and widely applied ’Hindley-Milner’ algorithm for type inference. This will involvefirst understanding, then modifying, an existing Haskell implementation by Stephen Diehl ofHindley-Milner type inference for a polymorphic lambda-calculus.

29

30 Project Description

Appendix B

Study Contract

31

32 Study Contract

33

34 Study Contract

Appendix C

Artefact

The software is based on the write-you-a-haskell project written by Stephen Diehl [8]. Allmodules except for the rep-line are extended, modified or refactored.

C.1 Modules

• Syntax: Define the syntax rules of the language

• Lexer: Define the lexer

• Parser: Define the parser

• Env: Define the typing environment

• Type: Define the types

• Pretty: Do the pretty print job

• Eval: Define the evaluation

• Infer(Top, K, S4, R): Implement type inference (with type inference rules specified indifferent files, and InferTop as the top level interface)

• Main(K, S4, R): The main programs

• Test: Used for testing

C.2 How to use

The ghc version should be higher than 8.4.2 or some slight change need to be made as com-mented in the code. Call ghci with the Main file then call the main function to enter theinteractive environment. Type ":quit", which will trigger an exception, to leave the interactiveenvironment. See the "README" file for more details.

C.3 License

The software is under MIT license.

35

36 Artefact

Bibliography

1. Awodey, S., and Bauer, A. Propositions as [types]. J. Log. Comput. 14(4) (2004), 447–471. (cited on page 1)

2. Birkedal, L., Clouston, R., Mannaa, B., Mogelberg, R. E., Pitts, A. M., and Spitters,B. Modal dependent type theory and dependent right adjoints. arXiv e-prints (Apr 2018),arXiv:1804.05236. (cited on page 28)

3. Borghuis, V. Coming to terms with modal logic: on the interpretation of modalities intyped lambda-calculus. PhD thesis, Technische Universiteit Eindhoven, 1994. (cited onpage 2)

4. Bozic, M., and Dosen, K. Models for normal intuitionistic modal logics. Studia Logica(1984), 217–245. (cited on page 9)

5. Clouston, R. Fitch-style modal lambda calculi. In Foundations of Software Science andComputation Structures (2018), pp. 258–275. (cited on pages iii, 1, 2, 9, 10, and 17)

6. Curry, H. A theory of formal deducibility. University of Notre Dame Press, 1957. (citedon page 19)

7. Davies, R., and Pfenning, F. A modal analysis of staged computation. JACM 48 (3) (2001),555–604. (cited on pages 1 and 17)

8. Diehl, S. Write you a Haskell https://github.com/sdiehl/write-you-a-haskell. (cited onpages iii, 2, 5, 6, and 35)

9. Dzik, W., J’arvinen, J., and Kondo, M. Intuitionistic propositional logic with Galois con-nections. Log. J. IGPL 18(6) (2009), 837–858. (cited on page 13)

10. Fetscher, B., Claessen, K., Palka, M. H., Hughes, J., and Findler, R. B. Making ran-dom judgments: Automatically generating well-typed terms from the definition of a type-system. In 24th European Symposium on Programming (2015). (cited on page 24)

11. Girard, J., Taylor, P., and Lafont, Y. Proofs and types. Cambridge University Press,1989. (cited on page 1)

12. Handley, M. A. T., and Hutton, G. Autobench: comparing the time performance ofHaskell programs. In Haskell 2018 Proceedings of the 11th ACM SIGPLAN InternationalSymposium on Haskell (2018), pp. 26–37. (cited on page 23)

13. Hindley, J. R. The principal type-scheme of an object in combinatory logic. Transactionsof the American Mathematical Society 146 (1969), 29–60. (cited on page 2)

37

38 BIBLIOGRAPHY

14. Howard, W. A. To H.B. Curry: Essays on Combinatory Logic, Lambda Calculus andFormalism. Academic Press, 1980. Seldin, Jonathan P.; Hindley, J. Roger (eds.). (citedon page 1)

15. Martini, S., and Masini, A. Proof theory of modal logic. Springer, 1996. (cited on page2)

16. McBride, C., and Paterson, R. Applicative programming with effects. Journal of Func-tional Programming 18:1 (2008), 1–13. (cited on page 19)

17. Milner, R. A theory of type polymorphism in programming. Journal of Computer andSystem Sciences 17 (3) (1978), 348–374. (cited on page 2)

18. Moggi, E. Computational lambda-calculus and monads. In LICS (1989), pp. 14–23. (citedon page 1)

19. Palka, M. H., Claessen, K., Russo, A., and Hughes, J. Testing an optimising compilerby generating random lambda terms. In Proceedings ofthe 6th International Workshop onAutomation of Software Test (2001). (cited on page 24)

20. Pfenning, F., andWong, H. On a modal lambda-calculus for S4. In MFPS (1995). (citedon page 17)

21. Pierce, B. C. Advanced Topics in Types and Programming Languages. The MIT Press,2004. (cited on page 1)

22. Prior, A. N. Formal Logic. Oxford Univ. Press, 1962. (cited on page 1)

23. Shulman, M. Brouwer’s fixed-point theorem in real-cohesive homotopy type theory. Math.Structures Comput. Sci. (2017). (cited on page 1)

24. Simpson, A. K. The Proof Theory and Semantics of Intuitionistic Modal Logic. PhD thesis,University of Edinburgh, 1994. (cited on page 1)

25. Sorensen, M., and Urzyczyn, P. Lectures on the Curry-Howard Isomorphism. Elsevier,2006. (cited on page 1)

26. Tarau, P. On type-directed generation of lambda terms. In InProceedings of the Techni-cal Communications of the 31st International Conference on Logic Programming (ICLP2015) (2015). (cited on page 24)

27. Wadler, P. Propositions as types. Commun. ACM 58(12) (2015), 75–84. (cited on page1)