Type Theory & Functional Programming

Total Page:16

File Type:pdf, Size:1020Kb

Type Theory & Functional Programming Type Theory & Functional Programming Simon Thompson Computing Laboratory, University of Kent March 1999 c Simon Thompson, 1999 Not to be reproduced i ii To my parents Preface Constructive Type theory has been a topic of research interest to computer scientists, mathematicians, logicians and philosophers for a number of years. For computer scientists it provides a framework which brings together logic and programming languages in a most elegant and fertile way: program development and verification can proceed within a single system. Viewed in a different way, type theory is a functional programming language with some novel features, such as the totality of all its functions, its expressive type system allowing functions whose result type depends upon the value of its input, and sophisticated modules and abstract types whose interfaces can contain logical assertions as well as signature information. A third point of view emphasizes that programs (or functions) can be extracted from proofs in the logic. Up until now most of the material on type theory has only appeared in proceedings of conferences and in research papers, so it seems appropriate to try to set down the current state of development in a form accessible to interested final-year undergraduates, graduate students, research workers and teachers in computer science and related fields – hence this book. The book can be thought of as giving both a first and a second course in type theory. We begin with introductory material on logic and functional programming, and follow this by presenting the system of type theory itself, together with many examples. As well as this we go further, looking at the system from a mathematical perspective, thus elucidating a number of its important properties. Then we take a critical look at the profusion of suggestions in the literature about why and how type theory could be augmented. In doing this we are aiming at a moving target; it must be the case that further developments will have been made before the book reaches the press. Nonetheless, such an survey can give the reader a much more developed sense of the potential of type theory, as well as giving the background of what is to come. iii iv PREFACE Outline It seems in order to give an overview of the book. Each chapter begins with a more detailed introduction, so we shall be brief here. We follow this with a guide on how the book might be approached. The first three chapters survey the three fields upon which type theory depends: logic, the λ-calculus and functional programming and construc- tive mathematics. The surveys are short, establishing terminology, notation and a general context for the discussion; pointers to the relevant literature and in particular to more detailed introductions are provided. In the second chapter we discuss some issues in the λ-calculus and functional program- ming which suggest analogous questions in type theory. The fourth chapter forms the focus of the book. We give the formal system for type theory, developing examples of both programs and proofs as we go along. These tend to be short, illustrating the construct just introduced – chapter 6 contains many more examples. The system of type theory is complex, and in chapter which follows we explore a number of different aspects of the theory. We prove certain results about it (rather than using it) including the important facts that programs are terminating and that evaluation is deterministic. Other topics examined include the variety of equality relations in the system, the addition of types (or ‘universes’) of types and some more technical points. Much of our understanding of a complex formal system must derive from out using it. Chapter six covers a variety of examples and larger case studies. From the functional programming point of view, we choose to stress the differences between the system and more traditional languages. After a lengthy discussion of recursion, we look at the impact of the quan- tified types, especially in the light of the universes added above. We also take the opportunity to demonstrate how programs can be extracted from constructive proofs, and one way that imperative programs can be seen as arising. We conclude with a survey of examples in the relevant literature. As an aside it is worth saying that for any formal system, we can really only understand its precise details after attempting to implement it. The combination of symbolic and natural language used by mathematicians is surprisingly suggestive, yet ambiguous, and it is only the discipline of having to implement a system which makes us look at some aspects of it. In the case of TT , it was only through writing an implementation in the functional programming language Miranda1 that the author came to understand the distinctive role of assumptions in TT , for instance. The system is expressive, as witnessed by the previous chapter, but are programs given in their most natural or efficient form? There is a 1Miranda is a trade mark of Research Software Limited v host of proposals of how to augment the system, and we look at these in chapter 7. Crucial to them is the incorporation of a class of subset types, in which the witnessing information contained in a type like (∃x:A) .B(x) is suppressed. As well as describing the subset type, we lay out the arguments for its addition to type theory, and conclude that it is not as necessary as has been thought. Other proposals include quotient (or equivalence class) types, and ways in which general recursion can be added to the system without its losing its properties like termination. A particularly elegant proposal for the addition of co-inductive types, such as infinite streams, without losing these properties, is examined. Chapter eight examines the foundations of the system: how it compares with other systems for constructive mathematics, how models of it are formed and used and how certain of the rules, the closure rules, may be seen as being generated from the introduction rules, which state what are the canonical members of each type. We end the book with a survey of related systems, implemented or not, and some concluding remarks. Bibliographic information is collected at the end of the book, together with a table of the rules of the various systems. We have used standard terminology whenever were able, but when a subject is of current research interest this is not always possible. Using the book In the hope of making this a self-contained introduction, we have included chapters one and two, which discuss natural deduction logic and the λ- calculus – these chapters survey the fields and provide an introduction to the notation and terminology we shall use later. The core of the text is chapter four, which is the introduction to type theory. Readers who are familiar with natural deduction logic and the λ-calculus could begin with the brief introduction to constructive mathematics pro- vided by chapter three, and then turn to chapter four. This is the core of the book, where we lay out type theory as both a logic and an functional programming system, giving small examples as we go. The chapters which follow are more or less loosely coupled. Someone keen to see applications of type theory can turn to chapter six, which contains examples and larger case studies; only occasionally will readers need to need to refer back to topics in chapter five. Another option on concluding chapter four is to move straight on to chapter five, where the system is examined from various mathematical per- spectives, and an number of important results on the consistency, express- ibility and determinacy are proved. Chapter eight should be seen as a continuation of this, as it explores topics of a foundational nature. vi PREFACE Chapter seven is perhaps best read after the examples of chapter six, and digesting the deliberations of chapter five. In each chapter exercises are included. These range from the routine to the challenging. Not many programming projects are included as it is expected that readers will to be able to think of suitable projects for themselves – the world is full of potential applications, after all. Acknowledgements The genesis of this book was a set of notes prepared for a lecture series on type theory given to the Theoretical Computer Science seminar at the Uni- versity of Kent, and subsequently at the Federal University of Pernambuco, Recife, Brazil. Thanks are due to colleagues from both institutions; I am especially grateful to David Turner and Allan Grimley for both encourage- ment and stimulating discussions on the topic of type theory. I should also thank colleagues at UFPE, and the Brazilian National Research Council, CNPq, for making my visit to Brazil possible. In its various forms the text has received detailed commment and criti- cism from a number of people, including Martin Henson, John Hughes, Nic McPhee, Jerry Mead and various anonymous reviewers. Thanks to them the manuscript has been much improved, though needless to say, I alone will accept responsibility for any infelicities or errors which remain. The text itself was prepared using the LaTeX document preparation system; in this respect Tim Hopkins and Ian Utting have put up with nu- merous queries of varying complexity with unfailing good humour – thanks to both of them. Duncan Langford and Richard Jones have given me much appreciated advice on using the Macintosh. The editorial and production staff at Addison-Wesley have been most helpful; in particular Simon Plumtree has given me exactly the right mix- ture of assistance and direction. The most important acknowledgements are to Jane and Alice: Jane has supported me through all stages of the book, giving me encouragement when it was needed and coping so well with having to share me with this enterprise over the last year; without her I am sure the book would not have been completed.
Recommended publications
  • Program #6: Word Count
    CSc 227 — Program Design and Development Spring 2014 (McCann) http://www.cs.arizona.edu/classes/cs227/spring14/ Program #6: Word Count Due Date: March 11 th, 2014, at 9:00 p.m. MST Overview: The UNIX operating system (and its variants, of which Linux is one) includes quite a few useful utility programs. One of those is wc, which is short for Word Count. The purpose of wc is to give users an easy way to determine the size of a text file in terms of the number of lines, words, and bytes it contains. (It can do a bit more, but that’s all of the functionality that we are concerned with for this assignment.) Counting lines is done by looking for “end of line” characters (\n (ASCII 10) for UNIX text files, or the pair \r\n (ASCII 13 and 10) for Windows/DOS text files). Counting words is also straight–forward: Any sequence of characters not interrupted by “whitespace” (spaces, tabs, end–of–line characters) is a word. Of course, whitespace characters are characters, and need to be counted as such. A problem with wc is that it generates a very minimal output format. Here’s an example of what wc produces on a Linux system when asked to count the content of a pair of files; we can do better! $ wc prog6a.dat prog6b.dat 2 6 38 prog6a.dat 32 321 1883 prog6b.dat 34 327 1921 total Assignment: Write a Java program (completely documented according to the class documentation guidelines, of course) that counts lines, words, and bytes (characters) of text files.
    [Show full text]
  • Pragmatic Quotient Types in Coq Cyril Cohen
    Pragmatic Quotient Types in Coq Cyril Cohen To cite this version: Cyril Cohen. Pragmatic Quotient Types in Coq. International Conference on Interactive Theorem Proving, Jul 2013, Rennes, France. pp.16. hal-01966714 HAL Id: hal-01966714 https://hal.inria.fr/hal-01966714 Submitted on 29 Dec 2018 HAL is a multi-disciplinary open access L’archive ouverte pluridisciplinaire HAL, est archive for the deposit and dissemination of sci- destinée au dépôt et à la diffusion de documents entific research documents, whether they are pub- scientifiques de niveau recherche, publiés ou non, lished or not. The documents may come from émanant des établissements d’enseignement et de teaching and research institutions in France or recherche français ou étrangers, des laboratoires abroad, or from public or private research centers. publics ou privés. Pragmatic Quotient Types in Coq Cyril Cohen Department of Computer Science and Engineering University of Gothenburg [email protected] Abstract. In intensional type theory, it is not always possible to form the quotient of a type by an equivalence relation. However, quotients are extremely useful when formalizing mathematics, especially in algebra. We provide a Coq library with a pragmatic approach in two complemen- tary components. First, we provide a framework to work with quotient types in an axiomatic manner. Second, we program construction mecha- nisms for some specific cases where it is possible to build a quotient type. This library was helpful in implementing the types of rational fractions, multivariate polynomials, field extensions and real algebraic numbers. Keywords: Quotient types, Formalization of mathematics, Coq Introduction In set-based mathematics, given some base set S and an equivalence ≡, one may see the quotient (S/ ≡) as the partition {π(x) | x ∈ S} of S into the sets π(x) ˆ= {y ∈ S | x ≡ y}, which are called equivalence classes.
    [Show full text]
  • Metaobject Protocols: Why We Want Them and What Else They Can Do
    Metaobject protocols: Why we want them and what else they can do Gregor Kiczales, J.Michael Ashley, Luis Rodriguez, Amin Vahdat, and Daniel G. Bobrow Published in A. Paepcke, editor, Object-Oriented Programming: The CLOS Perspective, pages 101 ¾ 118. The MIT Press, Cambridge, MA, 1993. © Massachusetts Institute of Technology All rights reserved. No part of this book may be reproduced in any form by any electronic or mechanical means (including photocopying, recording, or information storage and retrieval) without permission in writing from the publisher. Metaob ject Proto cols WhyWeWant Them and What Else They Can Do App ears in Object OrientedProgramming: The CLOS Perspective c Copyright 1993 MIT Press Gregor Kiczales, J. Michael Ashley, Luis Ro driguez, Amin Vahdat and Daniel G. Bobrow Original ly conceivedasaneat idea that could help solve problems in the design and implementation of CLOS, the metaobject protocol framework now appears to have applicability to a wide range of problems that come up in high-level languages. This chapter sketches this wider potential, by drawing an analogy to ordinary language design, by presenting some early design principles, and by presenting an overview of three new metaobject protcols we have designed that, respectively, control the semantics of Scheme, the compilation of Scheme, and the static paral lelization of Scheme programs. Intro duction The CLOS Metaob ject Proto col MOP was motivated by the tension b etween, what at the time, seemed liketwo con icting desires. The rst was to have a relatively small but p owerful language for doing ob ject-oriented programming in Lisp. The second was to satisfy what seemed to b e a large numb er of user demands, including: compatibility with previous languages, p erformance compara- ble to or b etter than previous implementations and extensibility to allow further exp erimentation with ob ject-oriented concepts see Chapter 2 for examples of directions in which ob ject-oriented techniques might b e pushed.
    [Show full text]
  • DC Console Using DC Console Application Design Software
    DC Console Using DC Console Application Design Software DC Console is easy-to-use, application design software developed specifically to work in conjunction with AML’s DC Suite. Create. Distribute. Collect. Every LDX10 handheld computer comes with DC Suite, which includes seven (7) pre-developed applications for common data collection tasks. Now LDX10 users can use DC Console to modify these applications, or create their own from scratch. AML 800.648.4452 Made in USA www.amltd.com Introduction This document briefly covers how to use DC Console and the features and settings. Be sure to read this document in its entirety before attempting to use AML’s DC Console with a DC Suite compatible device. What is the difference between an “App” and a “Suite”? “Apps” are single applications running on the device used to collect and store data. In most cases, multiple apps would be utilized to handle various operations. For example, the ‘Item_Quantity’ app is one of the most widely used apps and the most direct means to take a basic inventory count, it produces a data file showing what items are in stock, the relative quantities, and requires minimal input from the mobile worker(s). Other operations will require additional input, for example, if you also need to know the specific location for each item in inventory, the ‘Item_Lot_Quantity’ app would be a better fit. Apps can be used in a variety of ways and provide the LDX10 the flexibility to handle virtually any data collection operation. “Suite” files are simply collections of individual apps. Suite files allow you to easily manage and edit multiple apps from within a single ‘store-house’ file and provide an effortless means for device deployment.
    [Show full text]
  • Countability of Inductive Types Formalized in the Object-Logic Level
    Countability of Inductive Types Formalized in the Object-Logic Level QinxiangCao XiweiWu * Abstract: The set of integer number lists with finite length, and the set of binary trees with integer labels are both countably infinite. Many inductively defined types also have countably many ele- ments. In this paper, we formalize the syntax of first order inductive definitions in Coq and prove them countable, under some side conditions. Instead of writing a proof generator in a meta language, we develop an axiom-free proof in the Coq object logic. In other words, our proof is a dependently typed Coq function from the syntax of the inductive definition to the countability of the type. Based on this proof, we provide a Coq tactic to automatically prove the countability of concrete inductive types. We also developed Coq libraries for countability and for the syntax of inductive definitions, which have value on their own. Keywords: countable, Coq, dependent type, inductive type, object logic, meta logic 1 Introduction In type theory, a system supports inductive types if it allows users to define new types from constants and functions that create terms of objects of that type. The Calculus of Inductive Constructions (CIC) is a powerful language that aims to represent both functional programs in the style of the ML language and proofs in higher-order logic [16]. Its extensions are used as the kernel language of Coq [5] and Lean [14], both of which are widely used, and are widely considered to be a great success. In this paper, we focus on a common property, countability, of all first-order inductive types, and provide a general proof in Coq’s object-logic.
    [Show full text]
  • Proving Termination of Evaluation for System F with Control Operators
    Proving termination of evaluation for System F with control operators Małgorzata Biernacka Dariusz Biernacki Sergue¨ıLenglet Institute of Computer Science Institute of Computer Science LORIA University of Wrocław University of Wrocław Universit´ede Lorraine [email protected] [email protected] [email protected] Marek Materzok Institute of Computer Science University of Wrocław [email protected] We present new proofs of termination of evaluation in reduction semantics (i.e., a small-step opera- tional semantics with explicit representation of evaluation contexts) for System F with control oper- ators. We introduce a modified version of Girard’s proof method based on reducibility candidates, where the reducibility predicates are defined on values and on evaluation contexts as prescribed by the reduction semantics format. We address both abortive control operators (callcc) and delimited- control operators (shift and reset) for which we introduce novel polymorphic type systems, and we consider both the call-by-value and call-by-name evaluation strategies. 1 Introduction Termination of reductions is one of the crucial properties of typed λ-calculi. When considering a λ- calculus as a deterministic programming language, one is usually interested in termination of reductions according to a given evaluation strategy, such as call by value or call by name, rather than in more general normalization properties. A convenient format to specify such strategies is reduction semantics, i.e., a form of operational semantics with explicit representation of evaluation (reduction) contexts [14], where the evaluation contexts represent continuations [10]. Reduction semantics is particularly convenient for expressing non-local control effects and has been most successfully used to express the semantics of control operators such as callcc [14], or shift and reset [5].
    [Show full text]
  • Types Are Internal Infinity-Groupoids Antoine Allioux, Eric Finster, Matthieu Sozeau
    Types are internal infinity-groupoids Antoine Allioux, Eric Finster, Matthieu Sozeau To cite this version: Antoine Allioux, Eric Finster, Matthieu Sozeau. Types are internal infinity-groupoids. 2021. hal- 03133144 HAL Id: hal-03133144 https://hal.inria.fr/hal-03133144 Preprint submitted on 5 Feb 2021 HAL is a multi-disciplinary open access L’archive ouverte pluridisciplinaire HAL, est archive for the deposit and dissemination of sci- destinée au dépôt et à la diffusion de documents entific research documents, whether they are pub- scientifiques de niveau recherche, publiés ou non, lished or not. The documents may come from émanant des établissements d’enseignement et de teaching and research institutions in France or recherche français ou étrangers, des laboratoires abroad, or from public or private research centers. publics ou privés. Types are Internal 1-groupoids Antoine Allioux∗, Eric Finstery, Matthieu Sozeauz ∗Inria & University of Paris, France [email protected] yUniversity of Birmingham, United Kingdom ericfi[email protected] zInria, France [email protected] Abstract—By extending type theory with a universe of defini- attempts to import these ideas into plain homotopy type theory tionally associative and unital polynomial monads, we show how have, so far, failed. This appears to be a result of a kind of to arrive at a definition of opetopic type which is able to encode circularity: all of the known classical techniques at some point a number of fully coherent algebraic structures. In particular, our approach leads to a definition of 1-groupoid internal to rely on set-level algebraic structures themselves (presheaves, type theory and we prove that the type of such 1-groupoids is operads, or something similar) as a means of presenting or equivalent to the universe of types.
    [Show full text]
  • Acm Names Fellows for Innovations in Computing
    CONTACT: Virginia Gold 212-626-0505 [email protected] ACM NAMES FELLOWS FOR INNOVATIONS IN COMPUTING 2014 Fellows Made Computing Contributions to Enterprise, Entertainment, and Education NEW YORK, January 8, 2015—ACM has recognized 47 of its members for their contributions to computing that are driving innovations across multiple domains and disciplines. The 2014 ACM Fellows, who hail from some of the world’s leading universities, corporations, and research labs, have achieved advances in computing research and development that are driving innovation and sustaining economic development around the world. ACM President Alexander L. Wolf acknowledged the advances made by this year’s ACM Fellows. “Our world has been immeasurably improved by the impact of their innovations. We recognize their contributions to the dynamic computing technologies that are making a difference to the study of computer science, the community of computing professionals, and the countless consumers and citizens who are benefiting from their creativity and commitment.” The 2014 ACM Fellows have been cited for contributions to key computing fields including database mining and design; artificial intelligence and machine learning; cryptography and verification; Internet security and privacy; computer vision and medical imaging; electronic design automation; and human-computer interaction. ACM will formally recognize the 2014 Fellows at its annual Awards Banquet in June in San Francisco. Additional information about the ACM 2014 Fellows, the awards event, as well as previous
    [Show full text]
  • Journal of Applied Logic
    JOURNAL OF APPLIED LOGIC AUTHOR INFORMATION PACK TABLE OF CONTENTS XXX . • Description p.1 • Impact Factor p.1 • Abstracting and Indexing p.1 • Editorial Board p.1 • Guide for Authors p.5 ISSN: 1570-8683 DESCRIPTION . This journal welcomes papers in the areas of logic which can be applied in other disciplines as well as application papers in those disciplines, the unifying theme being logics arising from modelling the human agent. For a list of areas covered see the Editorial Board. The editors keep close contact with the various application areas, with The International Federation of Compuational Logic and with the book series Studies in Logic and Practical Reasoning. Benefits to authors We also provide many author benefits, such as free PDFs, a liberal copyright policy, special discounts on Elsevier publications and much more. Please click here for more information on our author services. Please see our Guide for Authors for information on article submission. This journal has an Open Archive. All published items, including research articles, have unrestricted access and will remain permanently free to read and download 48 months after publication. All papers in the Archive are subject to Elsevier's user license. If you require any further information or help, please visit our Support Center IMPACT FACTOR . 2016: 0.838 © Clarivate Analytics Journal Citation Reports 2017 ABSTRACTING AND INDEXING . Zentralblatt MATH Scopus EDITORIAL BOARD . Executive Editors Dov M. Gabbay, King's College London, London, UK Sarit Kraus, Bar-llan University,
    [Show full text]
  • Sequent Calculus and Equational Programming (Work in Progress)
    Sequent Calculus and Equational Programming (work in progress) Nicolas Guenot and Daniel Gustafsson IT University of Copenhagen {ngue,dagu}@itu.dk Proof assistants and programming languages based on type theories usually come in two flavours: one is based on the standard natural deduction presentation of type theory and involves eliminators, while the other provides a syntax in equational style. We show here that the equational approach corresponds to the use of a focused presentation of a type theory expressed as a sequent calculus. A typed functional language is presented, based on a sequent calculus, that we relate to the syntax and internal language of Agda. In particular, we discuss the use of patterns and case splittings, as well as rules implementing inductive reasoning and dependent products and sums. 1 Programming with Equations Functional programming has proved extremely useful in making the task of writing correct software more abstract and thus less tied to the specific, and complex, architecture of modern computers. This, is in a large part, due to its extensive use of types as an abstraction mechanism, specifying in a crisp way the intended behaviour of a program, but it also relies on its declarative style, as a mathematical approach to functions and data structures. However, the vast gain in expressivity obtained through the development of dependent types makes the programming task more challenging, as it amounts to the question of proving complex theorems — as illustrated by the double nature of proof assistants such as Coq [11] and Agda [18]. Keeping this task as simple as possible is then of the highest importance, and it requires the use of a clear declarative style.
    [Show full text]
  • On Modeling Homotopy Type Theory in Higher Toposes
    Review: model categories for type theory Left exact localizations Injective fibrations On modeling homotopy type theory in higher toposes Mike Shulman1 1(University of San Diego) Midwest homotopy type theory seminar Indiana University Bloomington March 9, 2019 Review: model categories for type theory Left exact localizations Injective fibrations Here we go Theorem Every Grothendieck (1; 1)-topos can be presented by a model category that interprets \Book" Homotopy Type Theory with: • Σ-types, a unit type, Π-types with function extensionality, and identity types. • Strict universes, closed under all the above type formers, and satisfying univalence and the propositional resizing axiom. Review: model categories for type theory Left exact localizations Injective fibrations Here we go Theorem Every Grothendieck (1; 1)-topos can be presented by a model category that interprets \Book" Homotopy Type Theory with: • Σ-types, a unit type, Π-types with function extensionality, and identity types. • Strict universes, closed under all the above type formers, and satisfying univalence and the propositional resizing axiom. Review: model categories for type theory Left exact localizations Injective fibrations Some caveats 1 Classical metatheory: ZFC with inaccessible cardinals. 2 Classical homotopy theory: simplicial sets. (It's not clear which cubical sets can even model the (1; 1)-topos of 1-groupoids.) 3 Will not mention \elementary (1; 1)-toposes" (though we can deduce partial results about them by Yoneda embedding). 4 Not the full \internal language hypothesis" that some \homotopy theory of type theories" is equivalent to the homotopy theory of some kind of (1; 1)-category. Only a unidirectional interpretation | in the useful direction! 5 We assume the initiality hypothesis: a \model of type theory" means a CwF.
    [Show full text]
  • Multi-Level Constraints
    Multi-Level Constraints Tony Clark1 and Ulrich Frank2 1 Aston University, UK, [email protected] 2 University of Duisburg-Essen, DE, [email protected] Abstract. Meta-modelling and domain-specific modelling languages are supported by multi-level modelling which liberates model-based engi- neering from the traditional two-level type-instance language architec- ture. Proponents of this approach claim that multi-level modelling in- creases the quality of the resulting systems by introducing a second ab- straction dimension and thereby allowing both intra-level abstraction via sub-typing and inter-level abstraction via meta-types. Modelling ap- proaches include constraint languages that are used to express model semantics. Traditional languages, such as OCL, support intra-level con- straints, but not inter-level constraints. This paper motivates the need for multi-level constraints, shows how to implement such a language in a reflexive language architecture and applies multi-level constraints to an example multi-level model. 1 Introduction Conceptual models aim to bridge the gap between natural languages that are required to design and use a system and implementation languages. To this end, general-purpose modelling languages (GPML) like the UML consist of concepts that represent semantic primitives such as class, attribute, etc., that, on the one hand correspond to concepts of foundational ontologies, e.g., [4], and on the other hand can be nicely mapped to corresponding elements of object-oriented programming languages. Since GPML can be used to model a wide range of systems, they promise at- tractive economies of scale. At the same time, their use suffers from the fact that they offer generic concepts only.
    [Show full text]