<<

PROCEEDINGS OF THE

WORKSHOP ON

TYPES FOR PROOFS AND PROGRAMS

Bastad

June

Eds Bengt Nordstrom Kent Petersson and Gordon Plotkin

Contents

Foreword

Workshop Programme

List of Participants

Demonstrations

P Aczel Schematic Consequence

P Audebaud CC an extension of the Calculus of Constructions with xp oints

F Barbanera Continuations and Simple Types a Strong Normalization Result ab

stract

S Berardi Game theory and Program extraction abstract

R Burstall James McKinna Deliverables a categorical approach to program devel

opment in type theory

T Co quand Pattern Matching with Dep endent Types

C Co quand A pro of of normalization for simply typed lambda calculus written in ALF

V Danos L Regnier Virtual reduction abstract

J Desp eyroux A Hirschowitz Natural Semantics in Co q First exp eriments

P Dyb jer Universes and a General Notion of Simultaneous InductiveRecursive Deni

tion in Type Theory

D Fridlender Formalizing Prop erties of WellQuasi Ordered Sets in ALF

V Gasp es Formal Pro ofs of Combinatorial Completeness

V Gasp es J M Smith Machine Checked Normalization Pro ofs for Typed Combinator

Calculi

H Geuvers Inductive and Coinductive types with Iteration and Recursion

L Helmink Girards Paradox in lambda U abstract

H Herb elin Computable interpretation of crosscuts pro cedure abstract

B Jutting Typing in Pure Type Systems abstract

J Lipton Relating Logic Programming and Prop ositionsasTypes A Logical Compila

tion

F Leclerc C PaulinMohring Programming with Streams in Co q A case study

the Sieve of Eratosthenes i

Z Luo Comp ositional understanding of type theory abstract

L Magnusson The new Implementation of ALF

N Mendler P Aczel An implementation of Constructive Theory in the Lego

system

M Parigot lambda mucalculus an algorithmic interpretation of classical natural de

duction abstract

F Pfenning Teaching Theory of Programming Languages Using a Logical Framework

an Exp erience Rep ort abstract

R Pollack Typechecking in Pure Type Systems

D Pym GPlotkin A Relevant Analysis of Natural Deduction abstract

C Raalli Fixed p oint and type systems abstract

P Rudnicki An Overview of the MIZAR Pro ject

A K Simpson Kripke Semantics for a Logical Framework

B Werner A Normalization Pro of for an Impredicative Type System with Large Elimi

nation over Integers ii

and

Types Programs

? ?

Foreword

This do cument is the preliminary pro ceedings of the Workshop on Types for Pro ofs

and Programs held at Hotel Riviera in Bastad Sweden from the th to the th of June

The workshop was organized by Peter Dyb jer Bengt Nordstrom Kent Petersson and Jan Smith

from Goteborg together with Ro d Burstall and Claire Jones from Edinburgh The workshop

was attended by p eople

Lo cal arrangements were lo oked after by Marie Larsson et al and Lennart Augustsson and

Per Lundgren to ok care of the computer equipment

a

These preliminary pro ceedings have b een collected from L T X sources using electronic mail

E

and spliced together They comprise of the pap ers presented at the meeting abstracts

are also included

This do cument may b e obtained by anonymous ftp from Chalmers University of Technol

ogy compressed le pubbaastadprocpsZ on animalcschalmersse login name anony

mous and your ordinary name as password

Workshop Programme Types for Pro ofs and Programs

Sunday June th

pm Dinner

Monday June th

am Per MartinLof

Do es denotational semantics have any role to play in type theory

am Peter Aczel

A LEGO implementation of constructive

am Coee Break

am Zhaohui Luo

Comp ositional understanding of type theory

pm Veronica Gasp es and Jan Smith

Machine checked normalization pro ofs for typed combinator calculi

pm Veronica Gasp es

Formal pro ofs of combinatorial completeness

pm Lunch

pm Vincent Danos and Laurent Regnier

Virtual reduction

pm Christine PaulinMohring

Representation of sp ecications and programs involving streams in

the Calculus of Inductive Constructions

pm Lena Magnusson

The new implementation of ALF

pm Coee Break

pm Demo Session

pm Dinner

Tuesday June th

am Thierry Co quand

Contexts substitutions and patternmatching

am Jo elle Desp eyroux

Natural semantics in Co q rst exp eriments

am Piotr Rudnicki

Mizar

am Coee Break

am Leen Helmink

Girards paradox in lambdaU

pm DEMO SESSION

pm Lunch

pm Benjamin Werner

Strong normalization of lambdacalculi with types dened by

recursion

pm James McKinna

Deliverables an approach to program development

pm Coee break

pm PANEL SESSION

pm Site leaders meeting

pm Dinner

pm Concert in Bastad Church

Wednesday June th

am Michel Parigot

calculus an algorithmic interpretation of classical natural

deduction

am Hugo Herb elin

Computable interpretation of crosscuts pro cedure

am Coee Break

am Stefano Berardi

Game theory and program extraction

pm Franco Barbanera

Continuations and simple types A strong normalisation result

pm Thomas Streicher

Truly intensional mo dels for type theory arising from mo died re

alizability

pm Lunch

pm FREE AFTERNOON

Bus leaves for walks various distances to Hovs hallar

pm Dinner in Torekov bus from Hovs hallar at pm

Thursday June th

am Peter Aczel

Schematic consequence

am Randy Pollack

Type checking in Pure Type Systems

am Coee Break

pm Bert Jutting

Typing in Pure Type Systems

pm Alex Simpson

Kripke semantics for a logical framework

pm Lunch

pm Catarina Co quand

The pro of of normalisation for simply typed lambda calculus writ

ten in ALF

pm Daniel Fridlender

Formalizing pro ofs of prop erties of wellquasiorders

pm Frank Pfenning

Teaching theory of programming languages using a logical frame

work an exp erience rep ort

pm Coee Break

pm Christophe Raalli

Fixed p oint and type systems

pm Dinner

Friday June th

am Jim Lipton

Logic programming and prop ositions as types A realizability in

terpretation of declarative programs

am David Pym and Gordon Plotkin

A relevant analysis of natural deduction

am Coee Break

am Phillip e Audebaud

An extension of the calculus of constructions using xp oints

pm Peter Dyb jer

Simultaneous inductiverecursive denitions in type theory

pm Lunch

List of Participants

INRIA Ro cquencourt

Samuel Boutin boutinmargauxinriafr

Hugo Herb elin herbelinmargauxinriafr

Gerard Huet huetmargauxinriafr

Chet Murthy murthymargauxinriafr

Benjamin Werner wernermargauxinriafr

Lyon

Catherine Parent parentlipenslyonfr

Christine Paulin cpaulinlipenslyonfr

Eindhoven

Leen Helmink helminkprlphilipsnl

Erik Poll erikwintuenl

EdinburghOxford

Ro d Burstall rbdcsedacuk

Philippa Gardner pagdcsedacuk

Claire Jones ccmjdcsedacuk

Zhaohui Luo zldcsedacuk

Savi Mahara j svmdcsedacuk

James McKinna jhmdcsedacuk

Randy Pollack rapdcsedacuk

David Pym dpymdcsedacuk

Alex Simpson alsdcsedacuk

Manchester

Peter Aczel peteracsmanacuk

Nijmegen

Henk Barendregt henkcskunnl

Bert van Benthem Jutting

Mark Ruys markrcskunnl

Paris

Vincent Danos danoslogiquejussieufr

JeanLouis Krivine krivinelogiquejussieufr

Pascal Manoury elephlogiquejussieufr

Patrick Meche mechelogiquejussieufr

Michel Parigot parigotlogiquejussieufr

Christophe Raalli raffallilogiquejussieufr

Laurent Regnier regnierlogiquejussieufr

Marianne Simonot simonotlogiquejussieufr

SophiaAntipolis

Joelle Desp eyroux jdsophiainriafr

Torino

Stefano Berardi stefanodiunitoit

Franco Barbanera barbadiunitoit

Pietro Di Gianantonio digianantudunivcinecait

Goteborg

Lennart Augustsson augustsscschalmersse

Jan Cederqvist cedercschalmersse

Catarina Co quand catarinacschalmersse

Thierry Co quand coquandcschalmersse

Peter Dyb jer peterdcschalmersse

Veronica Gasp es verocschalmersse

Michael Hedb erg hedbergcschalmersse

Daniel Friedlender fritocschalmersse

Lena Magnusson lenacschalmersse

Bengt Nordstrom bengtcschalmersse

Kent Petersson kentpcschalmersse

Jan Smith smithcschalmersse

Nora Szasz noracschalmersse

Alvaro Tasistro tatocschalmersse

Others

JeanPaul Audebaud paudebaulipenslyonfr

Eduardo Gimenez gimenezincouyeduuy

Jim Lipton liptonsaulcisupennedu

Per MartinLof Barnhusgatan Stockholm Sweden

Frank Pfenning FrankPfenningcscmuedu

Piotr Rudnicki piotrcsualbertaca

Anne Salvesen absifiuiono

Thomas Streicher streicherinformatikunimuenchende

Demonstrations

In the demosessions the following systems were shown

ALF Lennart Augustsson and Thierry Co quand

Co q Catherine Parent and Benjamin Werner

Elf Frank Pfenning

Lego Randy Pollack

Schematic Consequence

Peter Aczel

Manchester University

August

Abstract

The aim of this note is rst to set up some general theory for discussing dierent asp ects

of the notion of a logic and then to draw attention to the schematic asp ects of logic and

suggest a way of capturing this asp ect without making any commitment to the kind of

syntax a logic should have

Introduction

Nowadays we are well aware that there are many dierent logics There are computer systems

which are meant to b e used to implement many logics But there is no generally accepted account

of what a logic is Perhaps this is as it should b e We need imprecision in our vocabulary to

mirror the exible imprecision of our thinking There are a number of related phrases that seem

to have a similar imprecision eg formal system language axiom system theory deductive

system logical system etc These are sometimes given technical meanings often without

adequate consideration of the informal notions

When a logic has b een implemented in a computer system the logic has b een represented

in the logical framework that the computer system uses The logical framework will involve a

particular approach to syntax which may dier from the approach to syntax taken when the

logic was rst presented This means that in order to represent the logic as rst presented in

the framework a certain amount of co ding may b e needed and the question will arise whether

the logic as rst presented is indeed the logic that has b een represented in the framework To

make this question precise it is necessary to have a notion of a logic that abstracts away from

particular approaches to syntactic presentation

So we want to have a formal abstract denition of the notion a logic It is probable that

there is no single notion to b e captured but rather several related notions hiding under the

single phrase Nevertheless it would seem to b e very worthwhile to try to analyse the situation

and come up with some technical denitions that can b e used to capture the various facets of

the notions of a logic Of course there has b een previous work on this topic An imp ortant

ingredient in all recent work is the notion of a consequence relation This is essentially due to

Tarski who developed a fairly general theory of consequence op erators and deductive systems

in the s Dana Scott has more recently fo cused on the notion of a consequence relation

This pap er is incomplete and rep orts on work in progress An earlier version was called The Notion of a

Logic and was based on a talk given at the workshop on Deductive Systems at Ob erwolfach in May My

attention was drawn to the adjoint situations in the topic by a question after my talk This work was partially

supp orted by the Esprit Basic Research Action Logical Frameworks and an SERC research Fellowship

Another imp ortant development was Barwises abstract mo del theory Barwise which

gave a mo del theoretic approach to a general of logics those based on classical rst

order semantic structures A further stage of abstraction gives rise to Goguen and Burstalls

notion of an institution Goguen and Burstall This level of abstraction seems to

b e needed to capture the variety of logics that seem to b e of relevence in computer science

and linguistics The notion of an institution only fo cuses on the semantic asp ect of logical

consequence Meseguer in Meseguer has given a denition of a logic which uses an

institution to capture the semantic asp ect but also uses an entailment system to capture the

op erational asp ect An entailment system is roughly a system of consequence relations indexed

by signatures In Meseguers notion of a logic the consequence relations of the entailment system

are required to b e sound with resp ect to the semantic consequence relations of the institution

The notion of an entailment system has also b een used in Harp er Sannella and Tarlecki

where they called it a logical system or logic

At this p oint we should also mention the Edinburgh Logical Framework Harp er Honsell

and Plotkin and other systems playing similar roles in connection with computer sys

tems for implementing logics These logical frameworks provide an environment in which the

op erational nonsemantic asp ects of a logic can b e sp ecied provided that a syntax for the

logic is acceptable to the framework or can b e made acceptable without essentially changing

the logic One approach to the notion of a logic might b e to choose a logical framework and

require that the op erational part of a logic must have a representation in the logical framework

What are the key issues in connection with the notions of a logic We list some of them

Logic is concerned with what follows from what ie with logical consequence

Logic is generally applicable ie a logic should have a range of p ossible applications so

that if A follows logically from B in a logic then in every application or interpretation or

context where A is true B is true

Logic is schematic eg the rule of mo dus p onens that B follows logically from A and

A B is not expressed in the language of any particular application of the logic but

in a language of schematic expressions involving parameters which can b e instantiated in

any application language

In the next section b elow we give some denitions relevent to the rst issue We fo cus on

nitary traditional consequence More general notions are of interest See for example Avron

But the more restricted and familiar notion of a consequence relation will b e go o d

enough for our present purp oses We also introduce several other notions which are relevent in

connection with the formation of consequence relations either op erationally from an axiomatic

system or semantically from a semantic system Both metho ds of formation can b e seen to use

the notion of a truth system We also dene a hybrid notion incorp orating a semantic system

with an axiomatic system that is sound

We address the second issue ab ove by indexing the ab ove notions in section Finally we

address the third and less familiar issue in section There is a go o d deal more to b e said

on these topics and we hop e to pro duce an expanded version of this pap er In section we

make a slight detour from the main topic to consider the connections with Scotts notion of an

information system and domains

Finitary Traditional Consequence

We describ e ve categories relevent to an abstract theory of nitary traditional consequence

and study the relationships b etween them

Axiomatic systems

An axiomatic system A consists of a set A and a set f inA A where f inA is the

set of nite of A Axiomatic systems form a AS A map A A

of AS is a function A A such that

where f j g if F inA

We think of an axiomatic system as sp ecifying a notion of pro of whose inference steps have

the form

n

where f g Here of course are the premises of the inference step and

n n

is the conclusion

Consequence Relations

A consequence relation A is an axiomatic system satisfying the following

reexivity f g

monotonicity fg

transitivity and fg

Consequence relations form a full sub category CR of AS

Prop osition The inclusion functor CR AS has a left adjoint AS CR which associates

with each axiomatic system A the consequence relation A generated by A ie

is the least relation including such that A is a consequence relation or alternatively

is in the smal lest closed set including

where X A is closed if whenever

X X

Truth Systems

A truth system A M consists of a set A and a set M pow A where pow A is the set of all

subsets of A Truth systems form a category TS where a map A M A M of TS is

a function A A such that

X M X M

With each axiomatic system A we may asso ciate the truth system A cl where cl

is the set of closed subsets of A

Prop osition A A cl can be made into a functor AS TS which factorises

AS CR TS Moreover CR TS has a right adjoint TS CR which associates with

each truth system A M the consequence relation A j where

M

j X M X X

M

Closure Systems

A closure system is a truth system A M such that

T T

X M for all X M where we take X A when X

S

X M for all directed X M

Let CS b e the full sub category of TS whose ob jects are the closure systems

Prop osition The adjoint functors CR TS and TS CR have factorisations CR

CS TS and TS CS CR which are also adjoints Moreover the functors CR CS

and CS CR are inverses of each other so that CR CS

Semantical Systems

A semantical system A M od j consists of a set A a class M od and a class relation j that is a

sub class of M od A Semantical systems form a category SS where a map A M od j

A M od j of SS consists of a function A A and a function M od M od

such that for m M od A

m j m j

Each truth system A M determines a semantical system A M where m

M M

m M This gives a functor TS SS

Prop osition The functor TS SS has a right adjoint SS TS which associates with

each semantical system A M od j the truth system

A fthm j m M odg

where for each m M od

thm f A j m j g

Note that the comp osition SS TS CR gives a functor SS CR that sends each

semantical system A M od j to the consequence relation A j where

j m M od m j m j

Axiomatic system with semantics

We now describ e a hybrid notion An axiomatic system with semantics A M od j consists

of an axiomatic system A and a semantical system A M od j such that

soundness j

The axiomatic system with semantics is complete if the converse holds ie

j

Axiomatic systems with semantics form a category AS S in the obvious way

Summary

We have dened the four categories AS C R T S S S with functors

AS CR CS TS SS

which have right adjoints

AS CR CS TS S S

There is also the hybrid category AS S with the obvious forgetfull functors AS S AS and

AS S SS All these categories and functors are over the ie for each of

these categories C there is a forgetful functor C S ets and for each of the ab ove functors

C C the diagram

C C

S ets

commutes

Lindenbaum Algebras

A more abstract algebraic treatment of traditional consequence will work with meet semilat

tices and the Lindenbaum algebra construction Consider the following natural way to make a

meet semilattice A into a consequence relation A where

C a C a

This gives rise to a functor from the category SL of semilattices to the category CR We can

characterise the Lindenbaum algebra construction as a left adjoint CR SL to this functor

that maps A to Q where Q is a of f inA with resp ect to the

given by

C C for all a A C a i C a

and is the partial ordering on Q given by

C C C a for all a C

Consequence Relations and Scotts Information Systems

This section is really a detour from the main topic As in the previous section the categories

and functors that we will consider are all over the category of sets

There is an interesting relationship b etween the notion of a consequence relation and Scotts

notion of an information system see Scott This gives rise to a relationship b etween

closure systems and Scott domains Essentially a Scott Information System can b e viewed as a

consequence relation A and a consistency notion C on for it ie C on f inA such that for

all C f inA a A

C fag C on C C on

C a C C on

C a and C C on C fag C on

Given such a consistency notion we can call a closed set X A consistent if f inX C on

Then the set C l A C on fX cl j X is consistentg of elements of the information

system form a Scott domain when partially ordered by the relation It is a standard

fact that every Scott domain is isomorphic to one of these

We call a truth system A M a weak closure system if it satises the two conditions of a

T

closure system except that in condition X M need only hold for nonempty X M

So a closure system is simply a weak closure system A M such that A M We may form

the category w C S which is the full sub category of CS consisting of weak closure systems Also

let CRC b e the category whose ob jects are triples A C on where A is a consequence

relation and C on is a consistency notion for it The maps A C on A C on in

this category are the maps A A in CR such that for all X f inA

X C on X C on

Then we get an isomorphism

CRC w C S

given by mapping A C on in CRC to A C l A C on in w C S The inverse of this

isomorphism maps A M in w C S to A C on in CRC where the map A M A

M M M

is given by the functor w C S TS CR and

C on fC f inA j C X for some X M g

M

Given a consequence relation A there are two extreme ways to form a consistency

notion C on for it The maximum consistency notion is given by C on f inA The minimum

consistency notion is given by

C on C onA fX f inA j X a for some a Ag

Of course in some cases the two consistency notions may coincide so that the consequence

relation has a unique consistency notion But in familiar cases we exp ect the two notions to

b e distinct eg in a logic with negation we might exp ect that fb bg a for all a so that if

X fb bg then X is in f inA but not in C onA Can there b e other consistency notions

for a given consequence relation I was initially surprised to observe that

Prop osition For any consequence relation the two extreme consistency notions are the only

possible ones

To see why this is so let C on b e a consistency notion for the consequence relation A which

is dierent from C onA It follows that there is some C C on such that C a for all

a A We want to show that any X f inA is in C on So let X fa a g f inA As

n

C a we get that C fa g C on As C a we get C fa g a so that C fa a g C on

Continuing in this way we eventually get that C X C on As X C X it follows that

X C on

The two ways to construct consistency notions give rise to functors in a natural way though

for the second way a little care is needed In the rst case we have the functor CR CRC

that maps A to A f inA

Prop osition The above functor CR CRC is left adjoint to the forgetfull functor CRC

CR that maps A C on to A

For the other consistency notion construction we need to restrict to surjective functions Let CR

b e the sub category of CR having the same ob jects as CR but having as maps only those maps

of CR that are surjective as functions Similarily we may dene categories CRC C S etc

The ab ove functor CR CRC can b e restricted to give a functor CR CRC which is still a

left adjoint to the forgetful functor on CRC But we also have another functor CR CRC

that maps A to A C onA It is not p ossible to extend this to CR

Prop osition The latter functor CR CRC is right adjoint to the forgetful functor

CRC CR

So we get a sequence of three functors b etween CR and CRC where the rst functor in each

successive pair is left adjoint to the second

CR CRC A A f inA

CRC CR A C on A

CR CRC A C onA A

The isomorphisms

CR CS and CRC w C S

induce isomorphisms

CR CS and CRC w C S

and hence give rise to a corresp onding sequence of functors b etween CS and w C S

CS w C S A M A M

w C S CS A M A M fAg

M CS w C S A M A

where M is M fAg if this is a weak closure system and is M otherwise

There is a close connection b etween the collections of weak closure systems and Scott do

mains But it is to o strong to assert that the category S cott of Scott domains and continuous

maps is equivalent to the category w C S We do get an equivalence if we restrict to categories of

op

isomorphisms To get a b etter result we can consider the contravariant functor w C S S cott

which on ob jects maps A M to A where is the subset relation on M and on

M M

maps assigns to each A M A M of w C S the inverse continuous function

M M This functor is an equivalence if S cott is mo died so that only

M M

certain continuous functions are allowed as maps

Indexed Consequence

One asp ect of a logic is that there is a notion of signature so that asso ciated with each signature

is a set of sentences that can b e formed with the signature So we p ostulate a category SIG over

the category of sets the functor SIG S ets b eing the functor asso ciating with each signature

of SIG the set sent of sentences of

As an example rst order logic could use the category SIG whose ob jects consist of sets

of individual constant symbols and nplace function and predicate symbols for n The

signature maps of SIG are functions from symbols to symbols that map individual constants to

individual constants nplace function symbols to nplace function symbols and nplace predicate

symbols to nplace predicate symbols Now sent can b e the set of rst order sentences formed

in the standard way using the symbols of logical symbols and individual variables

Given SIG and SIG S et we get SIGindexed notions as functors from SIG over the

category S et For example a SIGindexed consequence relation is a functor SIG CR over

S et This is Meseguers notion of an entailment system and also the Harp er Sanella and Tarlecki

notion of a logical system

A version of the notion of an institution is a category SIG over S et together with a SIG

indexed semantical system SIG SS over S et

Let CRS b e the full sub category of AS S consisting of A M od j in AS S where A

is in CR Now Meseguers notion of a logic is a category SIG over S et together with a SIG

indexed consequence relation with semantics SIG CRS over S et

Schematic Consequence

We wish to capture the schematic asp ects of logic A logic is axiomatised by giving schematic

axioms and rules of inference which can b e instantiated to get inference steps Instantiations

may themselves b e schematic so that we are interested in the notion of a derived rule of inference

obtained by comp osing instances of the axioms and rules Note We need only fo cus on rules

as an axiom is simply a rule with no premises

Substitution

We want a syntax free way of talking ab out instantiation We are led to fo cus on substitution

We will assume that the substitutions on a set A are functions s A A that form a submonoid

A A

of A id Here A is the set of all functions A A id A A is the identity function

A A

of A and if s s A A then s s A A is their comp osition If S ub is such a submonoid

then we call A S ub a concrete monoid The instances of a A are the elements of A of the

form sa for s S ub

Concrete monoids form a category CM where a map A S ub A S ub consists

of a function A A and a monoid homomorphism S ub S ub such that for all

a A s S ub

sa s a

We can now give schematic versions of axiomatic systems consequence relations etc

Schematic Axiomatic Systems

A schematic axiomatic system A S ub consists of a concrete monoid A S ub and an ax

iomatic system A In an obvious way we get a category S AS of schematic axiomatic

system

Schematic Consequence Relations

A schematic consequence relation A S ub is a schematic axiomatic system such that A

is a consequence relation and for all s S ub

s A A in CR

ie

s s

We can now let SCR b e the full sub category of S AS consisting of schematic consequence

relations

Prop osition The inclusion functor SCR S AS has a left adjoint S AS SCR which

associates with each schematic axiomatic system A S ub the schematic consequence relation

A S ub generated by A S ub ie the least relation including such that A S ub

is a schematic consequence relation or alternatively

is in the smal lest S ubclosed set including

where

S ub fs s j s S ub and g

If then is a derived rule of relative to A S ub

Schematic Truth Systems

A schematic truth system A S ub M consists of a concrete monoid A S ub and a truth system

A M such that s A M A M in TS for all s S ub ie

X M s X M

for all s S ub

STS is the category of schematic truth systems with the obvious notion of map With

each schematic axiomatic system A S ub we may asso ciate the schematic truth system

A S ub cl S ub

Prop osition A S ub A S ub cl S ub can be made into a functor S AS STS

which factorises S AS SCR STS Moreover SCR STS has a right adjoint STS

SCR which associates with each schematic truth system A S ub M the consequence relation

A S ub j where j is obtained from M as in TS CR

M M

References

Avron Axiomatic Systems Deduction and Implication Tech Rep ort

Institute of Computer Sciences TelAviv University

Barwise Axioms for Abstract Mo del Theory Annals of Mathematical Logic

Goguen and Burstall Institutions Abstract Mo del Theory for Sp ecication and

Programming Edinburgh LFCS Rep ort

Harp er Sannella and Tarlecki Structure and Representation in LF A version

app eared in the pro ceedings of the th LICS meeting

Harp er Honsell and Plotkin A Framework for dening logics In Pro c LICS

Meseguer General Logics Pro c Logic Collo quium edited by HD Ebbinghaus et

al North Holland

Scott Domains for Denotational Semantics in the pro ceedings of ICALP Springer

Lecture Notes in Computer Science

CC an extension of the Calculus of Constructions

with xp oints

Philipp e Audebaud

LaBRI Universite Bordeaux I FRANCE

email audebaudlabrigrecoprogfr paudebaulipenslyonfr

August

Abstract

We follow an original idea suggested by Constable and Smith CoSm CoSm pro

viding a way for reasoning ab out non terminating computations in a typed framework This

work has b een initiated within NuPrl by Smith Smi However its adaptation to the Cal

culus of Constructions CC has showed to b e easy We get a conservative extension of CC

denoted CC where strong normalisation for reductions is preserved We recover the alter

nate recursive co ding for integers already introduced in AF by Parigot Par Par

thus the computational b ehaviour for the co des of integers is improved Moreover as ex

p ected all partial recursive functions are denable The prop osition asserting that every

term satises the principle of induction remains with no pro of but trivial ones All these

results easily generalize to all the usual data structures

Motivations

The initial CurryHoward isomorphism has b een greatly extended in the past decade leading to

p owerful type systems The corresp ondance b etween logic and functional programming within

a typed framework forces b oth pro ofs and programs to b e identied with strong normalizing

lambdaterms

Even if we may content ourselves with such a strong result from a pure logical p oint of

view its seems clear enough that type systems miss the p oint as far as they are intended to b e

considered as development systems for correct programs For instance treatment of exceptions

unbounded lo ops or recursive denitions are widely used in all programming languages in current

use

So connections b etween logic and programming need to b e rened maybe even b eyond

CurryHoward corresp ondance Grins original pap er Gri emphasizes the interactions b e

tween continuations in Scheme and absurd reasoning This is the starting p oint of studies

undertaken among other p eople by Murthy Mur and Krivine Kria leading to a some

what dierent approach of the relation b etween the two domains

From an other p oint of view unbounded lo ops and recursives denitions seem to require the

consideration of lambdaterms no longer normalisable Starting from the the thesis that recur

sive structures can b e co ded by xp oints this pap er is concerned with the study of an extension

of a typed framework with a xp oint constructor allowing us to examine more deeply how it

should b e p ossible to develop type systems where to reason with non terminating programs or

other recusive program scheme Our study restrited to CC actually develops in the same way as

Parigots study of recusive integers in the AF framework but indep endantly since originated

by Constable and Smith pap ers and PaulinMohrings thesis PaMoc Moreover most of

the work remains to b e done in order to answer the question whether or not such a solution

catch most of the spirit b eyond recusive features in current use in functional programming

languages

This pap er develops as follow in a rst part we give a short overview of dierent p ossible

solutions for the introduction of partial terms and we describ e how to make the last of these

solution t with the Calculus of Constructions Then the extension CC is presented and

examined with its main metamathematical prop erties The second part is devoted to the study

of dierent internal co dings for intergers in our framework there computational and logical

expressivity are the case in p oint

Partial ob jects in a typed framework

From now on we rely on the thesis that recursive structures can b e co ded through xp oint

constructs Let T b e any type system we assume at least the constructor is available in T

The main prop erty we should exp ect from a type system is its logical consistency there exists

at least one type inhabited by no term

A rst attempt

Let P b e any type and an empty type A xp oint constructor say f ix given a term

f P P provides a new term f ixf P One step of computation obviously consists in an

unfolding step

x f ixf f f ixf

Now observe that we can always form xx P P hence f ixxx P In particuliar

the type can no longer remains a empty type Consistency is lost

A renement

We may wonder whether it is p ossible to avoid this phenomenon by allowing such a new term

to b e formed only in case P is already an inhabited type Although there is no general answer

to such a question this renement fails for example in the Intuitionnistic Type Theories ITT

Per MartinLof observed that the base type N is now provided with a xp oint for the successor

function But then the axiom n n n is no longer valid

A general solution

In CoSm CoSm Constable and Smith suggested a simple and elegant solution which

avoids the diculties encountered Moreover it seems to t with most of the type systems

Starting from a type system T we build an extension T where the same rules are allowed

at the level of types and terms as well However a new feature is now available Each type P

P This type is intended to b e the type of the computations is asso ciated a new bar type

over terms b elonging to P these computations when converging having a value denote terms

from P Thus the fundamental rule from the authors p oint of view is

A a a A bar a

where t is an internal predicate asserting the convergence of t

Let us give some examples

A A the type for partial functions over A

A A the type for terms which if they converge are total functions

A A which corresp onds to the type of all partial functions over A in a lazy programming

language

These examples suggest that we can exp ect to work in a very expressive type theory from

the p oint of view of the degrees of partiality that can b e expressed

As exp ected the introduction of xp oints is now allowed over bar types only

x If f A A then f ixf A

Some examples are provided in CoSm CoSm and in Smi where a consequent study

of this kind of extended type system is done in the NuPrl framework We devote our attention

to the adaptation of this idea to a somewhat dierent type system

Adaptation to the Calculus of Constructions

Although the adaptation from NuPrl to CC followed a more sinuous way it is p ossible to ex

plain the translation shortly We are ab out to work with terms for which termination can b e

guaranteed no longer This is what we want at the level of programs Nevertheless up to now

logical pro ofs and programs are all identied with the same ob jects the same typed terms in

the system But we do want to consider that a logical pro of must b e complete so as to say

So from the logical p oint of view strong normalisation is the prop erty required

It seems clear for us that logical pro ofs and programs can no longer b e identied The notion

of value is dierent from the two p oints of view It is actually the case that the introduction

of bar types pro ceeds from this analysis even if the justication has not b e given this way by

Constable and Smith So we have to nd the right way to split the system into two parts the

rst b eing semantically taken as the logical system and the second one as the programming

language Now we already know how to do the job In PaMoc PaulinMohring introduced

a new constant S pec S et elsewhere in order to distinguish b etween terms with or without any

informative contents The explanation given explicitly was to separate pro ofs from programs

And such a trick do es the job since then terms are unambigous corresp ondance with one of the

two constants P r op and S pec or S et Hence the solution follows the same idea we introduce

P r op in order to mark terms to b e considered as partial terms Here is a new constant named

for the construction of bar types in the Calculus of Constructions Now partial programs and

partial schema are easily formed through a single new constructor in the CClike style

At least we can accept a logical pro of as so on as there is a pro of for its termination This

last p oint is taken into account through the predicate of convergence within NuPrl However

we consider that this predicate cannot b e put in the system but rather b elongs to a metalevel

with resp ect to CC system So this part will b e dropp ed out from our extension

Presentation of CC main results

P r op the use of the additional symbol T y pe will ease Although we need only the new constant

presentation However T y pe and T y pe can b e confuse in any implementation of our extension

Terms

The set of terms of CC denoted is the least set of terms containing the constants P r op

P r op a denumerable set V of variables and close for the following constructs and

application M N

abstraction x M N

xp oint hx M iN

pro duct x M N

where M N and x V

Positive o ccurrences of a variable

The necessity of a restriction on the recusive schema is obvious if we exp ect to keep the calculus

as well b ehaved as p ossible Otherwise for instance the prop osition

hX P r opiC P r opX X C C

will collect all pure lambdaterms

Let M and x V a xed variable The predicates P os and N eg are given a

X X

mutually recursive denition as follow

if X FV M then P os M and N eg M

X X

if M X then P os M

X

if M B A or y AB then

P os M if X FV A and P os B

X X

N eg M if X FV A and N eg B

X X

if M y AB then

P os M if N eg A and P os B

X X X

N eg M if P os A and N eg B

X X X

if M hy AiB then

P os M and N eg M if X FV M

X X

The case for a xp oint is justied plainly in the ab ove lines

Notions of reduction

Substitution is dened straightforwardly There are two notions of reduction

x M N L N xL

f ix hx M iN x M N hx M iN

f ix

where M N L and x V We let b e the reexive and transitive closure of x

and the congruence generated by it

Our choice for f ix comes from the fact that if is a xp oint for the function f then we do

have f Cho osing f ix as hx M iN N xhx M iN would have hidden the fact

f ix

that in the Calculus of Constructions all the xp oints we may construct are actually xp oints

of functional terms Moreover it would have led to a bad reduction b ehavior For dealing with

xp oint computations involves that we must take head reductions as meaningful

Notice that the condition imp osed to a xp oint for the p ositivity of a variable in this xp oint

can b e deduced from the cases for the application and the abstraction This a strong condition

but there is no way to x a weaker one since we do not know anything on the prop erties of the

calculus Then in order to prove go o d prop erties on the calculus we need to x a condition

invariant under reduction hence under x reduction in the present case

Then b oth reduction is substitutive and the reduction is weakly conuent weakly Church

Rosser

Inference and equality rules

Figures and recall the rules valid in CC The letter S stands for any constant P r op T y pe

P r op T y pe as far as CC is concerned Notice the shortcut f g for any of the constructs and

or h i

The additional rules required in CC are given in gure

Syntax of a well typed term

Any wellformed term M is of one of the following forms mo dulo conversion

M x P y QM R

with

z T M M

M hz T iM

constant or variable

Where x M is for x M x M k

k k

Moreover if M is a well typed term of type N say then we shall say that M is total if

either N T y pe or N is of type T y pe or P r op Otherwise such a term is said to b e partial

We denote CC and CC the two sets of the partition of well typed terms in CC It is easily

tot par

checked that this denition do es not dep end on N hence providing a new invariant for the well

typed terms as exp ected from the section

empty

is valid

M K x V x

varintro

x M is valid

x V

hypothesis

x x

Propintro

P r op T y pe

x P M S

pro dintro

x P M S

x P M N

absintro

x P M x P N

M x P N R Q P Q

appl

M R N xR

M N N N

typeconv

M N

Figure Rules of inference for CC

M P

re

M M

M N

sym

N M

M N N P

trans

M P

P Q x P M N

cons

fx P gM fx QgN

M N P M M N N

eqapp

M N M N

x P M N R P P P

x P M R M xR

Figure Equality rules for CC

Prop intro

P r op T y pe

P r op x P M Q P Q P

P r op xintro

hx P iM P

T y pe x P M P such thatsuch that P os M P

x

xintro T y pe

hx P iM P

x P M P

x

hx P iM x P M hx P iM

Figure Additional rules of inference and equality for CC

Main results

conservativity CC is a conservative extension of CC hence is consistent Hint there is an

obvious extraction function from CC to CC

tot

uniform prop erties The following prop erties are true over the set of well typed terms

Conuence for the reduction f ix

Strong normalisation for reduction

Finiteness of developments and standardisation theorems

For hints see Aud for a complete treatment see Aud Aud

Terms almost in normal form

The set of normal forms NF is to o much restrictive since for example the term x P x

P r opiC P r opX C C or any other xp oint would b e excluded where P hX

otherwise However the type information provided by the abstraction parts of a term has

no computational meaning it is dropp ed down in the pure lambdaterm obtained through the

erasure function

Then we can dene a weaker notion of normal form well suited with an environment of

partial terms The set ANF of terms almost in normal form is dened as the least class of

P r op the set V of variables and closed wellformed terms containing the constants P r op and

by

M ANF x P M ANF

M ANF x P M ANF

N N ANF x N N ANF

k k

Where P b eing any type and x is any constant or variable

We get the obvious facts

any prop ositional type is an ANF

NF ANF HNF

The terms ANF will play the same role as NF terms in CC say as will now b e seen through

the dierent co dings for integers in the extension CC

Internal co dings for integers

This part is devoted to the question how b oth computational and logical expressivity are p ossibly

improved in CC The main originality of this extension is the ability to give an alternate

co ding for integers A complete treatment is already given in Aud Aud for CC and in

Par Par for AF So we would rather like giving a somewhat informal presentation for to

ma jor co dings integers as iterators and as selectors We emphasize our presentation do es not

claim to b e rigorous However we exp ect this approach to show how the computational b ehavior

of co des of integers uniquely dep ends up on a more or less immediate pro of of mathematical

equality

Primitive recursion over integers

Given a A and h N A A the primitive recursion schema says there exists a unique

solution g N A such that

g a and n N g n hn g n

Informally

s

N N

hf g i hf g i

a

R

N A N A

h s hi

As a consequence f N N must satisfy

f and f s s f

Thus in any cartesian closed category with N as a natural number ob ject nno we can

s

N N in the category of conclude f id It works since N is precisely an initial ob ject

N

f

x

diagrams C C

Integers as iterators

In CC in system F already integers are internally co ded in such a way we collect Churchs

integers as normal forms through the prop osition

i

Nat C P r opC C C C P r op

i

Thus this representation mimics as well as p ossible the p osition of Nat as nno in the type

i i

system Let and S b e the closed terms which co de zero and the successor function Then

i k i

the regular integers are co ded through the set fS k Ng The induction principle is

i i i i i i

I nd n Nat P Nat P r opP n Nat P n P S n P n

This principle expresses that any prop erty is true for an integer as so on as it is true on the set

of co des of regular integers

Two ma jor problems are carried out by such a representation

i i

No pro of exists for n Nat I nd n As noticed in PaMoa PaMoc we need the

i i i i

fact that n Nat S equals n But this prop erty means precisely that every n Nat

is actually the co de for a regular integer n b eing a variable this is obviously imp ossible

to know However this equality holds for closed terms at the meta level Here is for the

structural p oint of view as far as logical expressivity is concerned

Now let us have a lo ok at the computational expressivity A solution to primitive recursion

i

schema is provided in CC through the recursor term r ec by

i i

g n Nat r ec n A a h

i

Nevertheless the equality f id can only b e proved for regular integers that is to say

Nat

terms satisfying the induction principle We need the same prop erty n is zero or the

successor of another term but at the level of programs now this is a non dep endent

version for the former problem see PaMoc section

So let us considerer we are dealing with those well built integers We want to consider the

simplest of all primitive recursion schema

p and pn n

giving the predecessor function From the computational p oint of view we get the follow

ing diagram

n n

hf n pni hf n n i

Hence computation of pn forces that of f sn so the computation of s f n to o

n

Eventually the eective computation of that term will have force that of s f n s

f even though we already know the result will b e n Thus this computation takes a

number of reductions in n This simple example makes it apparent the evaluation

mecanism linked to the very nature of Churchs integers there are iterators And at the

level of programs their imp erfection lies in that character

How far is it p ossible to improve these two p oints In CoPa Co quand and PaulinMohring

gave a solution through an extension of CC with inductive types We restrict our attention to

CC

Integers as selectors

In a cartesian closed category any nno N satises another diagram

s

N N N

x

f x f

R

C

Let us consider the predecessor function We note that C N f id and x Then

N

we get

id and id n n

Clearly id is the predecessor function over N Moreover its computation is now immediate

i

Although Nat satises this kind of diagram to o at least as far as we restrict ourselves to

the set of well built terms But then we get rather the existence of two terms such that

out

i i

Nat C P r opC Nat C C with in out id and out in id

in

r

Now through xp oint construction we are able to dene Nat such that

r r

Nat C P r opC Nat C C

It suces to dene

r

P r opiC P r opC N C C Nat hN

Notice that we must work over P r op Then we get

r r

P r opx C f Nat C x C

r r r

S n Nat C P r opx C f Nat C f n

r r r

r

P n Nat n Nat id

Nat

r

where P is the predecessor function

More generally a solution to any primitive recursion schema is easily found using xp oint

at the level of programs

r r

g n Nat n A a p Nat h p g p

This p oint clearly shows that introduction of xp oints is a go o d way to improve the com

putational b ehaviour of integers Moreover xp oints provide more programs that is more

realizations for sp ecications of programs indeed we are not forced to give a solution g as a

xp oint Nevertheless they are required in order to give a solution for recursion schema

given f N N nd the least integer n such that f n If we did not know there is such

an integer no solution exists in CC since any computation terminates In CC the solution is

obvious take g where

g k f k Nat k p Natg p

in a informal syntax

Main results

r

Let us the give here the main results ab out the recursive solution Nat In the following lines

n is for the co de of the nth integer

r r

n N P S n n in a xed number of step indeed

r

The set of closed anf terms of type Nat is the set fn j n Ng

All partial recursive functions over integers are denable in CC Hint the pro of follows

the same lines as Barendregts in

Logical expressivity

There remains the question whether or not CC provides an improvement at the structural

i

level We p ointed out Nat b ehaves as well as a nno provided it is restricted to the subset of well

i

built terms Since then Nat satises the second diagram there must exist a corresp ondance

i r

b etween Nat and Nat And it is actually the case through the terms

i r r r

i n Nat n Nat S

i r

Nat Nat

r i i r i

r n Nat n Nat p Nat S r p

r i

Nat Nat

Precisely these two terms give a onetoone corresp ondance b etween co des of regular integers

i r

in b oth of the types But the fact Nat satises the same diagram as Nat says more If it were

r r i i

to exist a pro of for n Nat I nd n then inevitably n Nat I nd n would b e provable

to o The converse is true of course And indeed we can prove

i i r

i n Nat I nd n I nd i n

r r i

ii n Nat I nd n I nd r n

i i

iii n Nat I nd n n r i n

r r

iv n Nat I nd n n i r n

Of course the very reason why it works is easy to understand The induction principle

when satised lls the gap b etween the subset of regular integers and all integers

We are allowed to conclude the study of integers we to ok as an example shows that our ex

tension cannot b e exp ected to improve the logical expressivity of the Calculus of Constructions

Further developments

The study briey undertaken in the case of the integers through various internal co dings can

b e followed in its main lines as far as we restrict ourselves to the usual data structures such

that lists or trees Actually close connections have b een established b etween simple concrete

types as describ ed in PaMoc and their recusive counterpart in CC see Aud Such

an equivalence emphasizes the main result that introduction of xp oints the way it is done in

CC at least do es not improve the logical p ower of CC but rather gives the user the ability of

realizing more programs and more sp ecicationss

The b etter that kind of limitation is understo o d the more we are able to simplify to relax

the rules previously given for the introduction of xp oints For example Ch PaulinMohring

suggests to allow xp oints within P r op hence dropping out P r op and at the same time to

remove xp oints at the level of pro ofs This idea and other variations clearly deserve further

attention

As a matter of temp orary conclusion let us fo cus the attention on a ma jor theme from

our own p oint of view Where mathematical reasoning usually contents itself with equalities

programming practice thus usage of pro of development systems as well is mostly concerned

with the way mathematical ob jects are computed This dynamic p oint of view seems to b elong

to the core of this domain of research if to b e considered really as a science Hence we think

that this diculty should not b e avoided To give just one concrete example xp oints are

allowed in CC exactly where syntactic transformations already exist in CC We got the feeling

a p osteriori that no xp oint over schema would have b een even conceivable otherwise And

in that case working with recursive schema means forcing the corresp onding transformation to

b e taken as the identity function crcion at least this is true as far as we restrict ourselves

to the set of well built terms within a simple type see PaMoc

References

Aud Audebaud P Partial Ob jects in the Calculus of Constructions In nd Conf

on Logic in Comp Science IEEE Available through anonymous ftp to

geo cubgrecoprogfr in pubPapersAudebaud rep ertory

Aud Audebaud P Extension du Calcul des Constructions par p oints xes These

Universite Bordeaux I Available through anonymous ftp to geo cubgreco

progfr in pubPapersAudebaud rep ertory

Aud Audebaud P Uniform prop erties in the Calculus of Constructions submitted

to TLCA

Bar Barendregt HP The Lambdacalculus its syntax and semantics nd ed

NorhHolland Amsterdam

CoPa Th Co quand and C PaulinMohring Inductively dened types In P MartinLof

and G Mints editors Proceedings of Colog LNCS Springer Verlag

CoSm Constable RL and Smith SF Partial ob jects in constructive type theory

In nd Conf on Logic in Comp Science IEEE

CoSm Constable RL and Smith SF Computational foundations of basic recursive

function theory In nd Conf on Logic in Comp Science IEEE

CoMe Constable RL and Mendler NP Recursive denitions in Type Theory In

Logics of Programs Parikh R editor LNCS Springer Verlag

Gri Grin T A formulastypes notion of control In Conference Record of the

Seventeenth Annual ACM Synposium on Principles of Programming Languages

Kria Krivine JL Operateurs de Mise en Memoire et Traduction de Godel Rap

p ort technique de lEquip e de Logique Universite Paris VI I Janv

Krib Krivine JL Lambdacalcul evaluation paresseuse et mise en memoire A

paratre dans Informatique Theorique et Applications RAIRO

Luo Luo Z ECC an Extended Calculus of Constructions In Information and

Computation

Mend Mendler N Recursive Types and type Constraints in SecondOrder Lambda

Calculus In nd Conf on Logic in Comp Science IEEE

Mur Murthy C Extracting Constructive Content from Classical Pro ofs PhD

Cornell University

Par Parigot M Programming with pro ofs a second order type theory Proceed

ings of ESOP ed H Ganziger Lectures Notes in Comp Science Springer

Verlag Berlin

Par Parigot M Recursive Programming with Pro ofs Theoretical Computer Sci

ence p

PaMoa PaulinMohring Ch Extracting F programs from pro ofs in the Calculus of

Constructions In Proceedings of th ACM Symposium on Principles of Program

ming Languages ACM NewYork

PaMob PaulinMohring Ch Inductive denitions in the Calculus of Constructions

draft In The Calculus of Constructions Rapp ort technique INRIA

PaMoc PaulinMohring Ch Extraction de programmes dans le Calcul des Construc

tions These Paris

Smi Smith SF Partial Ob jects in Type Theory PhD Dissertation Cornell

University

Continuations and Simple Types a Strong Normalization Result

Franco Barbanera

Torino

Abstract

We present a work in which we study the termination problem for a typed lambda

calculus with continuations We do not b ound ourselves to study a particular reduction

strategy like callbyvalue or callbyname Reductions may b e applied to any part of any

term in any order Our main result is that every reduction sequence in the system terminates

Game theory and Program extraction

Stefano Berardi

Torino

Abstract

We interpret each classical formula P as a game GP b etween two players A and B

Player A is committed to show that P is true and player B that P is false We interpret

a pro of as a recursive winning strategy for GP This work is inspired by Co quands last

work diering from it in three asp ects

we interpret linear logic rst

we use p erfect information games

we prove cut elimination in a purely intuitionistic way

Deliverables a categorical approach to program development in

type theory

Ro d Burstall and James McKinna

Lab oratory for the Foundations of Computer Science

y

University of Edinburgh

August

Introduction

This pap er outlines a metho d for constructing a program together with a pro of of its correctness

with resp ect to a given sp ecication The technology used is type theory in fact an extended

version of Calculus of Constructions Luos ECC as implemented in Pollacks Lego sys

tem here program means a primitive recursive description of a function using simply typed

lambda calculus with higher order functions and data types such as numbers and lists

Given a precondition and a p ostcondition we consider pairs consisting of

a program

a pro of that the program satises the p ostcondition given the precondition

We call such a pair together with the pre and p ostconditions a deliverable since it is what

a software house should ideally deliver to its client instead of just a program

Now we observe that various op erations comp osition pairing iteration and so on can b e

used to combine deliverables and that these op erations can b e implemented in ECC Consider

for example comp osition If f p is a deliverable from pr e to post and f p is a deliverable

from post to post then their comp osition is a deliverable from pr e to post thus

f f the comp osition of the functions

a pro of using p and p that f f satises post given pr e

In fact the combining op erations excluding iteration are exactly those of a cartesian closed

category whose ob jects are the pre and p ostconditions and whose arrows are deliverables This

is comforting since it assures us that we have a complete set of combinators They enable us to

build a complicated program together with its correctness pro of Since the resulting expression

of the calculus denotes a pair we can extract the program trivially by evaluating the rst element

of the pair

The authors are gratefully for the supp ort of the EC Logical Frameworks BRA and the SERC

y

JCMB Kings Buildings Mayeld Rd Edinburgh EH JZ UK

email rbdcsedacuk jhmdcsedacuk

We have used the Lego system to dene these combinators and use them to create the

deliverables for several programs as examples

However in many cases a precondition and a p ostcondition do not satisfactorily sp ecify a

desired program For example when developing a sorting program the precondition might ask

for an arbitrary list and the p ostcondition demand that the result b e a sorted list But we

would get little thanks for a program which always returned the nil list even though this is

sorted We need to sp ecify that the output list should also b e a p ermutation of the input one

If we try to replace the pre and p ostconditions by a single statement sp ecifying a relation

b etween input and output there do not seem to b e convenient combination op erators so we

discard that approach Thinking syntactically we could allow the pre and p ostconditions to

share a free variable For example using a free variable l for lists

pr ex x l

posty isP er mutationy l

This ties the pre and p ostconditions together but such free variables should have a denite

scop e

We can think more semantically that l satises some base condition it must b e a list and

the pre and p ost conditions are relations whose rst argument is l Thus we can talk of pre

and p ost conditions relative to l Now a deliverable relative to l is a program which takes the

precondition to the p ostcondition for all l We will refer to these as second order sp ecications

and deliverables in contrast to the original rst order ones

How should we represent sp ecications and deliverables in type theory We choose the

following

A rst order sp ecication is a predicate over a type thus

a type s

a function S from s to P r op the type of prop ositions

and a rst order deliverable from sp ecication s S to sp ecication t T is a program with

pro of thus

a function f s t

Q

a pro of x sS x T f x where is the quantier on prop ositions

Now we can generalise these to work relative to a rst order sp ecication u U which

corresp onds to the free variable l in our example Call u the base type now the second order

sp ecication b ecomes a relation over the base type and another type and the second order

deliverable must resp ect the pre and p ostrelations We leave the details to the b o dy of the

pap er

We might try to characterise the rst order deliverables as a cartesian closed category whose

ob jects are sp ecications and whose arrows are deliverables this is almost correct but we have

to mo dify the CCC to a semicartesian closed category a mild generalisation due to Hayashi

The second order deliverables are then characterised using a bration whose bres are categories

of rst order deliverables In fact this structure constitutes a mo del of type theory

The pap er includes some illustrative examples of program development using deliverables

and brief mention of others of which the most substantial is an algorithm for the Chinese

Remainder theorem

We also discuss the relation to earlier work on extracting programs from pro ofs particularly

the work of MartinLof as developed by Nordstrom Petersson and Smith They dene

a translation from a type theory say S to an underlying type theory U such that the types

in S corresp ond to our sp ecications and the unary terms in S corresp ond to our deliverables

A somewhat similar approach is taken by PaulinMohring in her program extraction using

the realisability interpretation

The virtue of our metho d is that it can quite easily b e co ded up in an existing system and

there is no diculty ab out extracting the program from the pro of since they are built together

but as separate comp onents of a pair normalising the rst comp onent gives us the program

We have mentioned op erations for combining deliverables and this might suggest a b ottomup

approach but we can just as well start with a sp ecication of the desired program and derive

the corresp onding deliverable topdown by renement in Lego

The weakness of our metho d is that we have to use a combinatory notation which is less

p erspicuous than the usual notation of type theory Since deliverables form a mo del of type

theory this might p ossibly b e rectied by extending ECC with an extra kind whose types

would b e sp ecications and whose terms would b e deliverables thus following the insight of

MartinLof but we have not yet worked out this approach

The basic approach was prop osed in an unpublished talk by Burstall at the Bastad Workshop

on type theory in A brief account by the present authors app eared as and a full

treatment of work so far is in McKinnas thesis

Review of ECC and a simple example

Luos Extended Calculus of Constructions ECC is a rich type theory containing Co

quand and Huets Calculus of Constructions as a subsystem together with strong types

and a cumulative hierarchy of predicative universes much as in the systems considered by

MartinLof and his collab orators In MartinLof systems al l types may b e read

as prop ositions and in Co quand and Huets original system all prop ositions may b e read as

types ECC avoids this blurring of distinctions giving us access to full intuitionistic higherorder

logic at a prop ositional level together with a predicative environment for computation and ab

stract mathematics It is precisely this ability to distinguish prop ositional from computational

information within a single framework which underlies our approach to program development

ECC is built out of a calculus of terms with the following ocial syntax

T j V j

V T T j V T T j TT j

V T T j pair T T j T j T

T

where V ranges over some innite collection of variables and ranges over Prop and Type

i

i the socalled kinds of ECC Prop is an impredicative universe as in Co quand and

Huets original systems intended to contain prop ositions while the Type are predicative

i

universes much like a settheoretic hierarchy and very similar to the U of some versions of

i

MartinLofs theories Substitution for free o ccurrences of variables is dened in the

usual way Terms are identied up to renaming of b ound variables The basic conversion relation

is dened on all terms and as usual is the congruence closure of the familiar reductions

xAM N  M N x and

fVTgT corresp onds to x T T

VTT to xT T

VTT to V T T

TT to pair T T

xAB

T to T

and T to T

Table Comparison b etween syntax of LEGO and ECC

pair M M  M i

i i

T

LEGO is Pollacks implementation of a typechecker and renement pro of system for ECC

and a number of related systems based on earlier ideas of Huet de Bruijn and others

The LEGO syntax for terms in the language of ECC is given by

T Prop j Typei i j V

fVTgT j VTT j TT j

VTT j TT j T j T

where the corresp ondence with the ocial syntax is given in Table As usual the non

dep endent types is denoted by an inx

The syntax has recently b een extended to provide arbitrary extensions to the conversion

relation As an example we may add a type of natural numbers by declaring appropriate

constants in an initial context

natType nat S nat nat

nat

natrecd C nat Type C k nat C k C S k nnat C n

together with reductions

natrecd C z s  z

natrecd C z s S k  s k natrecd C z s k

for C z s k of the appropriate types

In this context we may derive the following term

nnat nat Prop k natk S S k n Prop

nat

which represents impredicatively the informal prop osition that n is an even natural number

That is we dene even numbers to b e those n which satisfy al l predicates satised by and

closed under successor of successor the impredicativity of course lies in the fact that evenness

is just such a predicate Moreover in this representation

nat Prop

nat

z

sk nat k S S k

z

nat Prop k natk S S k

1

d for dep endent

is a term representing a pro of that is even

Example In the same way one could dene a predicate representing o ddness

Odd nnat nat PropS k natk S S k n

def

b eing one such representation One might then show that the successor function S transforms

even numbers into o dds and o dds to evens yielding terms sE O of type nnat Evenn

Odd S n and sO E of type nnat Odd n EvenS n the patient reader may care to

exp eriment with the system by doing just such a thing

What is the b ehaviour of the comp osite function x x We may use the pro ofs sE O

and sO E together with modus ponens to derive a term ssE E of type nnat Evenn

Evenn

Now the types of the calculus allow us to pair together these fragments of co de with their

asso ciated pro of terms for example

S sE O f nat nat nnat Evenn Odd f n

and we may see the pair nnat n ssE E arising as a comp osite construction from the

pairs S sE O and S sO E

The pair nnat n ssE E of type

f nat nat nnat Evenn Evenf n

is a very simple instance of the general idea b elow of a rstorder deliverable in this case from

nat Even to nat Even

Denition of rstorder deliverables

We work relative to some wellformed context in ECC

Denition specication

A specication is a pair of terms s S such that s Type and xs S x Prop

We typically write S T U for sp ecications and understand s t u resp ectively S T U as

referring to their underlying type resp predicate Formally there is a type of sp ecications

namely SPEC sTypes Prop so that we may consider op erations which construct

def

sp ecications entirely within the framework of ECC cf the account of sp ecications and

renements in

We will consider a category whose ob jects are the sp ecications Sp ecications dened by

logically equivalent predicates in general dene distinct ob jects The appropriate notion of

b etween sp ecications consists of a pair f where f is a function b etween the

underlying types and is a pro of that f resp ects the predicates We call these

rstorder deliverables

Denition rstorder deliverable

Given sp ecications S s S T t T a rstorder deliverable is a term F such that

F f s tx sS x T f x

The motivation for such a denition go es right back to Hoares original pap er on axiomatic

semantics and like the logic of triples which b ears his name expresses in a formal system

the informal notion of a program together with a certicate of some sp ecied inputoutput

b ehaviour Of course we are concerned with a functional language rather than an imp erative

one so there is no confusion over program variables and logical variables In this framework

moreover the pro of and the program are linked as a pair This denition uses the types in an

essential way to capture this idea We may use all the features of ECC to construct such pairs

but based on our intuitions ab out computational vs prop ositional information we insist up on a

trivial extraction pro cess rst pro jection from the type yields the underlying algorithm f

Indeed this accounts for the name deliverables they are what a software house should deliver

to its customers a program plus a pro of in a b ox with the sp ecication printed on the lid the

type The customer can indep endently check the pro of and then run the program without

the need for a complicated extraction pro cess which may yield an unusual algorithm Indeed

we prop ose this metho d as a style for developing programs in the rst place We usually have

a reasonable idea of the algorithm in advance as opp osed to its pro of of termination or even

correctness and we would like an understanding which reects our intuitions of how to build

up these deliverables from smaller ones for example by renement and comp osition p ossibly

with machine assistance

In terms of LEGO we dene a predicate Del and a type constructor del which describ e

rstorder deliverables within ECC compare Denition ab ove

Lego Del

value stTypeSPred sTPred tfstxsS xT f x

type stTypePred sPred tstProp

Lego del

value stTypeSPred sTPred tfstDel S T f

type stTypePred sPred tType

This is the output from the typechecker after giving the denitions We have exploited the

implicit syntax to enable us to suppress the argument types in the predicate Del and the type

del

With an eye to the categorical asp ects of this denition we typically write

f

F

T del or s S t T del S

when f s t and Del S T f Since s t may b e inferred by the typechecker

and we are in general not interested in save to know that it exists we may even abuse our

notation and write

f

T del S

At this stage we need not have used the types to present these denitions However

internalising the mathematical pair in a type allows us to represent op erations which pro duce

such functionpro of pairs within the calculus This gives us the p ossibility of developing a

structure on these morphisms

2

This accounts for our choice of notation since the types st may b e inferred from ST we relegate them

notationally to the lower case

Denition equality of specications

Given sp ecications s S t T we say s S t T if

s t and xs S x xt T x

Denition equality of deliverables

Given

f

t T del s S

g

we say f g if

xs f x xs g x

and

xs hS x xh xs hS x xh

This denition of equality of deliverables seems to b e the minimal extension of the basic con

version relation which ensures go o d categorical prop erties

Semistructure in categories

The use of cartesian closed categories to give mo dels of the simplytyped calculus is by now

familiar in computer science for example as are various equational presentations of the

structure of a cartesian closed category The basic type and term constructors are dened by

adjunctions In this analysis the unit and counit of the adjunction dening the arrow type

corresp ond lo osely to and conversion resp ectively and similarly for the pro duct type

constructor The absence of conversion and surjective pairing in ECC forces some extra

technical diculty up on us However mo dels of various typed calculi without conversion

and surjective pairing can b e given a rigorous semantic account in terms of semiadjunctions

introduced by Hayashi in Essentially the equations dening an adjunction are relaxed

suciently that under suitable conditions there is a notion of counit which corresp onds appro

priately to conversion without a unit corresp onding to conversion A detailed treatment is

given in the thesis

Denition Semifunctor

Given two categories C D a semifunctor b etween them is a functor which need not preserve

identities that is to say we are given an assignment F of ob jects of D to ob jects of C and

an assignment also called F of arrows of D to arrows of C such that

f F f

B C implies FA FB D A

and

f g F f F g

B C FA FB FC D F A

In a semiadjunction we replace the usual natural bijection on homsets with a pair of maps

which need not b e mutual inverses However we still require them to b ehave naturally The

b eauty of this idea lies in the following lemma

Lemma Hayashi Suppose F G above are in fact functors Then a semiadjunction

between F and G yields an adjunction between F and G

So this concept subsumes the whole of our ordinary understanding of adjunctions and hence all

the constructions of universal gadgets dened by adjunctions In particular in a category C

we may dene the notions of semiterminal object semiproduct and semiexponential exactly

by analogy with the usual cartesian closed structure If C has all the ab ove structure we say C

is a semicartesian closed category or semiccc Hayashis development leads to the following

main results generalising previous accounts of mo dels of the calculus with conversion only

Prop osition Semicccs are sound and complete for interpretations of the calculus

Prop osition Semicccs can be presented algebraically

In the second author used LEGO to prove the following theorem

Theorem del is semicartesian closed

We sketch some of the ideas in the discussion b elow

Identities and comp osition

By considering our slight mo dication of the underlying conversion on the terms of ECC to

remedy the failure of surjective pairing and conversion in the calculus we xed a notion

of equality on arrows With this denition it is now trivial to establish that sp ecications

together with rstorder deliverables as morphisms form a category denoted by del

The identities are given simply by

xs x xs hS x h

s S del s S

in LEGO we have

Lego iddel

value sTypeSPred sxsxxspS xp

type sTypeSPred sdel S S

Comp osition is given by

f g xs g f x xs hS x f xxh

S T U S U

We may now verify that these denitions do indeed yield the structure of a category on del

SemiTerminal ob ject

Unit unit u unit u SPEC

def

denes a trivial sp ecication where we p ostulate the existence of a unit type in the same way

as other inductive types We then obtain for any sp ecication s S the deliverable

xs xs pS x reEQ del S Unit

sS

def

3

However by contrast with adjunctions structure dened by a semiadjunction is not in general unique

4

Indeed we only need the mo died equality to prove the identity laws The conversion relation is sucient

to establish asso ciativity of comp osition

5

Here is the unique term of type unit We write void in LEGO

Binary semipro ducts

To obtain semipro ducts we use the nondep endent type as the underlying type with con

junction at the predicate level

S T s t ps t S p T p

def

That we indeed have a semipro duct structure now follows straightforwardly from this denition

Semiexp onentials

The notion of rstorder deliverable is based on the predicate Del on terms of arrow type

Precisely this predicate denes the sp ecication which yields a semiexp onential ob ject in del

abstraction and evaluation then follow from those op erations in the underlying type theory

on values and implication introduction and elimination at the level of pro ofs

S T s t f s t Del S T f

def

Trivial deliverables

Every function that is to say a term of arrow type gives rise to a deliverable very much

in the manner of the assignment rule of Hoare logic or Dijkstras predicate transformer for

assignment Namely for

f s t P t Prop

we obtain

f xshf P hdel f P P where f P xsP f x

def

We call these deliverables trivial since they come with vacuous pro ofs of correctness

A consequence rule

Logical implication induces a p ointwise ordering on predicates for which we have the following

consequence rule in the manner of Hoare logic

f

T T T S S S

T S

f

In fact this rule is subsumed by comp osition since any logical entailment gives rise to a deliv

erable whose function comp onent is the identity

Pointwise construction

A basic combinator in the theory of deliverables constructs a functionpro of pair from a function

which returns valueproof pairs Mendler in his thesis calls such gadgets p ointwise

6

This just corresp onds to Howards observation that given a strong interpretation of the existential quantier

as type the axiom of choice b ecomes constructively valid

designs for each argument value x the p ointwise existence of a value y of type t satisfying

some prop erty T v yields a deliverable with co domain t T In detail

F xs y t S x T y

f

T S

where f xs F x and xs hS x F xh

def def

Inductively dened types

Provided we accept a weak denition of inductive type it is relatively straightforward to add

inductive types to the categorical structure developed so far Categorical accounts of inductive

types via initial algebras imp ose extra equalities on the iterator due to the uniqueness clause

in the denition of initial algebra As with the semistructures ab ove we only have existence

and not uniqueness of the relevant universal arrows

The basic idea is very simple we add inductive types at the Type level with a strong

elimination rule yielding a simply typed recursor at the Type level and the usual induction

principle at the Prop level This type is then paired with the identically true predicate The

elimination rule for rstorder deliverables is easily derived by packaging primitive recursion at

the type level with induction at the predicate level We illustrate this general idea by considering

the case of natural numbers and lists

Natural numbers

Recall from Section that we may p ostulate the existence of a type of natural numbers with

two constructors zero and successor This yields the wellformed context

natType nat S nat nat

We typically abbreviate S to in informal mathematical language We extend this context

with a dep endent elimination constant natrecd

natrecd C nat Type z C sk nat ihC k C k nnat C n

together with reduction rules dening the redexes in some context where C z s n have the

appropriate types

natrecd C z s  z

natrecd C z s n  s n natrecd C z s n

This is precisely expressed in LEGO as follows

natType

zeronat

succnat nat

natrecdCnatType

7

Strong that is b ecause we can eliminate over types and not merely prop ositions

8

cf MartinLof type theory or Godels earlier system T of functionals We essentially use this language

of primitive recursion in all nite types as our programming language

zC zerosknatihC kC succ knnatC n

nnatCnatTypezC zerosknatihC kC succ k

natrecd C z s zero d

natrecd C z s succ n s n natrecd C z s n

This yields a derived iterator and primitive recursor

natiter Type

and

natrecType nat

where

natiter z s z

def

natiter z s n s natiter z s n

def

natrec z s z

def

natrec z s n s n natrec z s n

def

and an induction principle

natind nat Type z sk nat ihk k nnat n

Our metho dology suggests we examine derived induction principles for the iterator and

recursor since we are interested in programs in this case of the form natiter z s or natrec z s

together with proven prop ositions ab out them For the iterator we obtain

z y y s y

z s

nnat natiter z s n

and for the recursor

z k nat y k s k y

z snat

nnat natrec z s n

Since we are interested in building new deliverables from less complex ones we could of

course use the dep endent eliminator natrecd to construct terms of type del but in doing so

we violate the separation of pro ofs from programs which distinguishes our approach So we

package recursion at the Type level with induction at the Prop level in a pair

We introduce the predicate Nat nnat tr ue on the natural numbers For each

def

constructor of the type we obtain a corresp onding deliverable

Nat Zero uunit uunit hUnit u Unit

def

Nat Succ nnat S n nnat hNat n Nat

def

9

The type is of course inferred by the typechecker

For the iterator we obtain

z Z s S

Unit t T t T t T

t T Natiter z Z s S nat Nat

and the recursor Natrec analogously where the function comp onent of Natiter z Z s S

resp ectively Natrec is natiter z s resp ectively natrec and the pro of comp onent is

obtained from the appropriate derived induction principle ab ove

These terms are easily obtained by renement in LEGO For example here is the signicant

structure of Natiter with the uninformative details of the pro of comp onent suppressed

Lego natiterdel

value tTypeTPred tZZdel Unit TSSdel T T

zZZ voidZZZsSSSSS

natiter z s

natind mnatNat mT natiter z s m

type tTypeTPred tdel Unit Tdel T Tdel Nat T

Example As an example of the use of these combinators we present a correctness pro of of a

doubling function given by

double nnat natiter k nat k n

def

Supp ose we wish to show that double n is even for all natural numbers n Posed in terms of

deliverables we seek a term of type del Nat Even whose function comp onent is double

Using the rule for Natiter ab ove the problem reduces to nding

z Z

nat Even We take z uunit and use the pro of that is base case Unit

def

even from Section

sS

step case nat Even nat Even We simply use the rstorder deliverable which we

constructed by comp osition at the end of Section namely nnat n ssE E

We thus obtain a nontrivial recursive rstorder deliverable

Lists

In much the same way as ab ove we may dene combinators for deliverables over a type of lists

As b efore we extend the context with a type constructor in this case listType Type

together with constructors the usual nil and cons and a dep endent eliminator listrecd Again

we derive an iterator listiter a primitive recursor listrec and an induction combinator listind

When it comes to considering the derived induction principles for the iterator and recursor

however we now have the freedom to sp ecify recursions over lists of elements satisfying some

10

Here is the term corresp onding to trueintroduction

Prop p p

def

of type tr ue Prop

def

predicate rather than over all lists of the parameter type a That is given some sp ecication

a A we obtain a derived sp ecication List a A list a Listof A where

def

Listof A nil a true

def

Listof A cons x l A x Listof A l

def

denes Listof A by primitive recursion

We may then pro ceed in the same way as ab ove obtaining constructors

Nil uunit nil a uunit hUnit u Unit Listof A

def

and

Listof A

ConsA Listof A

with function comp onent

xa l list a cons x l

and pro of comp onent

xa pA x l list a q Listof A l pair p q

Likewise we package together recursion and an appropriate derived induction principle to

obtain the following rules for constructing deliverables an iterator

c C n N

t T

t T a A t T Unit

t T Listiter n N c C l ist a Listof A

and analogously a recursor

Secondorder deliverables

The system which we have describ ed ab ove amounts to a functional version of the well known

invariants used in pro ofs of imp erative programs Unfortunately the sp ecication makes no

connection b etween the input and the output of the function All we say is that if the input

satises prop erty S then the output satises prop erty T but there is no relation b etween them

Recalling the example in the introduction we might sp ecify that a sorting function takes lists

to ordered lists but we cannot sp ecify that the output is a p ermutation of the input The

function might always pro duce the empty list which is indeed sorted but not very interesting

As a matter of fact the classical invariant pro ofs have the same weakness masked by the tacit

assumption that some variable which is carried through the computation do es not change its

value To enforce the constraint that the output b ear some relation to the input we need to

develop a comp ositional theory in which relations are the basic ob jects of study with a notion of

arrow which resp ects relations rather than predicates This gives us a categorical explanation

of the idea that the pre and p ostconditions are linked by having a free variahle in common

that is they are over the same context

A thought exp eriment

Supp ose we are given some sp ecication xs z u R x z and we wish to nd some function

f s u which satises it In what sense may we rene such sp ecications by comp osition

Supp ose we wish to instantiate f via the comp osition f g h of two functions

g

h

s t u

where t is some intermediate type Then following our intuition in the case of predicates we

anticipate some intermediate sp ecication Qx y xs y t such that g solves

xs y t Qx y

and h solves

xs y t Qx y z u R x z

This last is logically equivalent to

xs y t Qx y z u R x z

But now we are left in something of a quandary h our intended solution makes no reference

to the intermediate value of y Also we have introduced an asymmetry b etween the roles of g

and h A remedy which underlies the denitions and b elow is to separate the roles of

the indep endent parameter x and the dep endent variables y z

We consider relations such as Q R as the ob jects of study for a xed type s but allowing

the types t u to vary The following provides an appropriate notion of morphism which re

establishes a symmetry b etween Q and R

Denition An arrow from Qx y xs y t to R x z xs z u consists of the following

data

a function f s t u that is to say a function of two arguments this recovers the

missing dep endence we observed ab ove

a pro of xs y t Qx y R x f x y

The comp osition of two such arrows

h g

Qx y R x z P x w

is denable as

x w s r h x g x w x w s r pP x w x g x w x w p

We have now established a denition which resp ects the symmetry of source and target in

our previous analysis of the decomp osition of the sp ecication xs z u R x z In so doing

we have generalised the notion of sp ecication and our old sp ecication corresp onds in this

new setting to choosing r unit P x w true and f xs f x

old new

def def def

Basic denitions

In view of the ab ove discussion we relativise sp ecications and rstorder deliverables to dep end

on some input type s Indeed by observing that we may uniformly imp ose some condition S on

the input parameter xs without aecting the notion of comp osition we arrive at the denition

of a secondorder deliverable

Denition relativised specication

Supp ose s Type S s Prop Then a relativised specication with respect to s S

is given by a pair of terms t R such that

t Type and

R s t Prop

Denition secondorder deliverable

Supp ose s Type S s Prop Given two relativised sp ecications t Q and

u R a secondorder deliverable over s S is a term F such that

F f s t ux sS x y tQx y R x f xy

We dene Del S QR to b e the predicate

f s t u x sS x y tQx y R x f xy

Denition embo dies the idea that for each xs such that S x holds f x x is a rstorder

deliverable from Qx to R x where F f This suggests that the study of second

def

order deliverables amounts to the study of rstorder deliverables in an extended context In

particular we exp ect to obtain for a given sp ecication S s S a category structure on

def

the secondorder deliverables over S We make a similar denition of equality on secondorder

deliverables to that given in Section ab ove the details of which are left to the reader Then

we can indeed dene identities and comp osition given by

Identities The identity morphism from t Q to itself over s S is given by

xs y t y xs hS x y t q Q x y q

Comp osition This is dened much as in the thought exp eriment ab ove the comp osition

of

g f

Qx y R x z P x w

over s S is denable as

xs w r g x f x w xs hS x w r pP x w x h f x w x h w p

This gives us a category del S

If f is a secondorder deliverable over s S we typically write

f f

t Q u R s S or even Q R S

since as usual the types s t u may b e inferred by the typechecker Our notation is intended

to indicate that we are considering deliverables relative to some assumption dened by the

sp ecication s S This notation is delib erately intended to echo the style of contexts in

MartinLof type theory

Each del S is a semiccc

2

As in Section we work relative to some context We have seen how a secondorder deliverable

f over s S in context may b e viewed as arising from a rstorder deliverable in the

extended context xs hS x The conditions of denitions and are intended to enforce

a hierarchy of dep endencies in this extended context The type t must not dep end on x or h

The relation R considered as a predicate on t in context xs do es not dep end on h The

function comp onent f may not dep end on h but the pro of comp onent may do so

Given these conditions we may lift the structure in del by observing that the various

constructions of Section resp ect this hierarchy of dep endencies The predicates concerned

need to b e mo died to include an explicit hypothesis S x We arrive at the following result

Theorem For each specication S del S has the structure of a semiccc

Pro of We merely sketch some of the constructions on the basis of the ab ove informal intuition

Full details are in

Semiterminal ob ject This is given by the relativised sp ecication

unit xs uunit true

S

def

The map from some relativised sp ecication t Q to has function comp onent

tQ S

xs y t and pro of comp onent

xs hS x y t pP x w

Semipro ducts Supp ose we are given two relativised sp ecications t Q u R Then we

may form the relativised sp ecication

t Q u R t u xs pt u Qx p R x p

def

This denes a semipro duct ob ject in del s S The pairing map is given by

g f

Q S P R S P

P Q R S

f g

where f g and are appropriate pairing op erations on values and pro ofs

resp ectively Pro jections are similarly straightforward to dene

Semiexp onentials Just as the predicate Del dened a semiexp onential ob ject in the cat

egory del we may dene a semiexp onential ob ject in del s S using the relativised

sp ecication to which Del gives rise More precisely supp ose r P t Q u R are

relativised sp ecications We obtain a relativised sp ecication

Q

R t u xs f t u y tQ x y R x f y

def

Q

If f s t u and Del S Q R f then xs x R f x Moreover

given

F

R S P Q

we obtain

F

Q

R S P

by currying in the obvious way if F f then F f where f and

def def

are appropriate currying op erations on values and pro ofs resp ectively We may similarly

dene an evaluation map details of which are left to the imaginative reader it is rather

less taxing to develop this construction by renement in LEGO Likewise the pro ofs

that these data meet Hayashis conditions for a semiexp onential are b est dealt with by

renement



del an indexed category over del

2 1

The categorically minded reader now asks herself what relationships exist b etween the various

categories fdel S jS SPEC g and to what extent we may elab orate up on the structure of this

collection In particular she may ask what is the relationship b etween del S and del T given

a rstorder deliverable from S to T A moments pause should convince her that comp osition

in del should induce an op eration on secondorder deliverables since they somehow are no

more than rstorder deliverables except that they are dened in an extended context In

other words we are groping towards the following theorem

Theorem del is an indexed category over del whose bres are semicccs with

semicc structure strictly preserved by reindexing along arrows in del

Pullback functors

The ab ove theorem dep ends on the existence of pullback functors which translate or reindex

data b etween the categories del S The obvious denition works and moreover trivially resp ects

the equality of ob jects and arrows so we do indeed have pullback functors and they are

functors not merely semifunctors since identities and comp osition are preserved It is then a

straightforward and tedious task to verify that these op erations comp ose and strictly preserve

the structure in each bre

Denition pul lback along a rstorder deliverable

k K

We dene an Supp ose we are given sp ecications S T and a rstorder deliverable S

T

op eration of pul lback along k K where we abuse notation in the standard way by employ

ing the same symbol for the op eration on ob jects and arrows as follows given a relativised

sp ecication Q u Q with resp ect to T let

def

k K Q xs z u Q k x z

def

moreover given a relativised sp ecication R v R and a secondorder deliverable

def

f

R T Q

we dene k K f to b e the pair

xs z u f k x z xs hS x z u pQ k x z k x K x h z p

Lemma k K Q is a relativised specication with respect to S Moreover k K f is

a secondorder deliverable from k K Q to k K R

Lemma k K preserves identities and composition

So indeed we do have the the existence of functors b etween the bres del That they are

a satisfactory notion of reindexing requires us to show that they ob ey the condition H K

K H In fact more is true We have the following

Lemma The reindexing is strict in the sense that

H K K H

We now turn to the remainder of Theorem namely that the pullback functors preserve the

structure of a semiccc in each bre As ab ove we nd that the structure is preserved strictly

We examine only the case of exp onentials the cases of pro ducts and terminal ob ject b eing

exactly similar and rather easier

K

we have Lemma In the notation of Theorem above with V

S

Q K Q

K R K R

Prop osition Suppose r P t Q u R are relativised specications with respect to S

Given

F K

P Q R S and V S

we have K F K F

Secondorder deliverables for natural numbers and lists

In the context of secondorder deliverables the situation regarding inductive types is less well

understo o d We do not regard this section as giving a denitive account but the examples we

have considered suggest that we have a usable set of combinators for reasoning ab out recursive

programs

We take as our guiding motivation the derived induction principles of the last section Since

we now work in the relativised case these will b e subtly altered by the presence of the induction

variable

This means for the case of natural numbers that we now examine pro ofs of statements of

the form

nnat R n natrec z s n

where for some type t z t and snat t t A pro of of this by induction yields

R z and k nat y t R k y R k s k y

as the requisite hypotheses in the base and step cases We may now recognise the second

hypothesis as the logical comp onent of some secondorder deliverable whose function comp onent

is s

11

We only consider natrec since natiter is a degenerate instance of it

The question arises as to how to view the rst hypothesis R z Do we regard it as part of

some rst or secondorder deliverable In a sense neither in the choice we have made in the

current version of deliverables If we examine the derived rule of induction again but this time

rephrased as

k nat y t R k y R k s k y

nnat z t R z R n natrec z s n

this isolates how we currently view recursions at the secondorder level Namely we see the func

tion which recursively applies s to an arbitrary initial value z as the function comp onent of some

secondorder deliverable whose pro of comp onent is the pro of by induction of the conclusion

nnat z t R z R n natrec z s n

As observed ab ove the hypothesis in the step case of induction arises as the pro of comp onent

of a secondorder deliverable

s S

R R

nat

R otherwise written R n n is the relation where

nnat y t R n y

In like manner we write R or R n for the relation

nnat y t R y

We thus obtain the secondorder deliverable constructor for nat recursions as the following

derived rule

s S

R R

nat

R Natrec s S R

nat

where Natrec has function comp onent

nnat z t natrec z s n

The principle reason for making this choice of representation is a pragmatic one based

partly on exp erience and on the b ehaviour of unication in the typechecker If we were to

mimic the construction of rstorder deliverables by induction we would exp ect some rule with

one hypothesis for each constructor of the datatype such as for example

s S z Z

R R R

nat nat

R Natrec z Z s S

We would typically apply such a rule in a topdown pro of to a subgoal of the form

del n m R

In a topdown development where we may construct deliverables using all the constructions

describ ed ab ove we would like the instantiation of m to b e b oth as general as p ossible to allow

for subsequent development and yet to allow unication to constrain m to make the application

valid Our choice of the ab ove rule for Natrec seems to achieve this We do not regard this

choice as necessarily denitive however it merely represents our present view

Lists

We may extend this analysis to the case of lists where as in the case of rstorder deliverables

we nd the richer structure of lists reected in a richer collection of predicates and relations

Firstly if we work in the bre del then we obtain in exactly the same way as ab ove

list a

the following derived rule

F

cons x R xa R

list a

R Listrec F nil R

list a

where

cons x R l l ist a y t R cons x l y

def

and

nil R l l ist a y t R nil a y

def

But already in this rule we nd something new the outermost binding That is to say

the rule has as its premise a dependent family of secondorder deliverables This phenomenon

arises from the parameter type a of the lists in question The rule is susceptible to the same

criticisms as the rule for Natrec ab ove but also the criticism that we have accorded a dierent

status to the parameter type In particular it do es not seem to b e constrained by any predicate

A we might imp ose on a Our justication as ab ove is essentially pragmatic We have found

this rule to b e a useful construction as in the example of minimum nding in a list

We can obtain forms of this rule in which the input list is further constrained We may

for example consider the predicate Listof A for some predicate A on a In fact since we

are now considering secondorder deliverables where we can take into account relations which

dep end on b oth the input variable and the result of some computation step we may extend

this predicate to a dep endent version which we call depListof A dened as follows

depListof nil a true

def

depListof cons x l x l depListof l

def

Here is some relation b etween values of the variable x varying over the parameter type a

and lists over a An example is the predicate Sorted for which we take x l x l the

def

relation that x is less than each element of the list l This crops up in the example of an insert

sort in the next section

This introduces an extra hypothesis into the induction scheme we must consider Supp ose

we wish to prove

l list a depListof l R l listrec n c l

where nt ca t t A pro of by induction generates the following hypotheses for each

constructor

base case tr ue R nil n which reduces logically to R nil n As with the rules for Natrec

we shall fold this assumption into the rule as the initial relation in the secondorder

deliverable we eventually derive

step case Formally we obtain

xa l list a depListof l R l listrec n c l

depListof x l R x l c x l listrec n c l

Two simplications present themselves The rst is to replace the explicit mention of

listrec n c l by an additional universally quantied parameter y The second is to

observe that depListof cons x l depListof l Combining these we obtain as

an induction hypothesis in the step case

xa l list a y t depListof x l R l y R x l c x l y

In this form we see the logical part of a secondorder deliverable emerge

We thus obtain the following derived rule which yields a secondorder deliverable with function

comp onent listrec from a dep endent family of secondorder deliverables

cons x R cons x depListof F xa R

R depListof depListrec F nil R

Examples

In his thesis the second author considered a number of example developments using the

metho dology outlined ab ove culminating in a machinechecked pro of of the Chinese remainder

theorem This last example is to o long to include here although it p erhaps b est exhibits some

of the strengths of our approach We hop e to discuss it in a forthcoming pap er

To illustrate the discussion of the previous sections we give two examples of the use of de

liverables in smallscale program development The use of deliverables may seem heavyhanded

and even counterproductive for these smaller examples The discussion is taken from

where detailed accounts in LEGO of the derivations may b e found

Finding the minimum of a list

An example which is treated several times in the literature In our case it involves a

somewhat unnatural rep eresentation which makes nontrivial use of the semicartesian closed

structure in the bres del

The mathematical sp ecication

Supp ose R is a decidable total order on some type which for the purp oses of this example

contains a maximal element a this avoids having to consider exceptions for the case of the nil

list We distinguish b etween R a boolean valued function and the relation a b R a b tt

denoted Then we may sp ecify the minimum of a list as follows

R

l listl nil mm l aa l m a

R

We abbreviate the second conjunct to m l We may easily express a solution to this

R

sp ecication in SML as follows adds an element to a list

fun min a b if R a b then a else b

fun minelemaux nil fn a a

minelemaux bl fn a min a minelemaux l b

fun minelem nil a

minelem al minelemaux l a

We have explicitly curried the function denition of

fun minelem anil a

minelemabl min a minelem bl

since the type system of ECC is to o strict to allow such a denition based on pattern matching

Our denition is by recursion on the rst argument l of minelemaux the corresp onding pro of

is by induction on l We seek to verify that minelemaux meets the following sp ecication

l list f a f a a l f a a l

R

The pro of for minelem follows by comp osition with a suitably relativised deliverable for ap

plication

The correctness pro of

We just consider the verication of minelemaux As indicated the pro of is by induction

Base case

f a f a a nil f a a nil

R

The condition f a a nil forces us to choose f a a For a reexive R the

def

second conjunct is then satised

Step case Supp ose

f a f a a k f a a k

R

Then for b taking g a min a f b we obtain for all a by cases on

def

R a f b

R a f b tr ue and hence min a f b a Now a a b k and a a b k

R

since a a and a f b b k by hypothesis and the transitivity of

R R R R

R a f b f al se and hence min a f b f b We have f b b k by hypothesis

and hence f b a b k Again by hypothesis f b b k and f b a Hence

R R

f b a b k and we are done

R

The development in terms of deliverables

We give an outline of the pro of in the style of a derivation tree indicating the combinators used

to resolve signicant subgoals

Let

MinAuxSpec l list f a f a a l f a a l

R

def

Abbreviating the trivial sp ecications l list tr ue and l list uunit tr ue to since they

are terminal ob jects resp ectively in del and del list we seek

minelemaux

MinAuxSpec

12

Sannella in fact treats the maximum of the list

We use comp osition to enable us to exploit our recursion combinator for secondorder de

liverables over lists of Section to package up the pro of by induction

step

base

MinAuxSpec

compose

minelemaux

MinAuxSpec

and

F

step

a MinAuxSpec cons a MinAuxSpec

list

Listrec

step

MinAuxSpec

which instantiates subgoal with the sp ecication nil MinAuxSpec

We resolve the base case of our induction using a p ointwise construction and thereafter

exactly the informal reasoning ab ove This is sucient to allow us to completely close this

branch of the derivation

value a a

proof a a a a

R

pointwise

base

nil MinAuxSpec

This leaves the step case We extend the context with a free variable b of type and then

conclude with another p ointwise construction The pro of follows the informal argument ab ove

value a min a f b

proof

pointwise

F b

step

MinAuxSpec cons b MinAuxSpec

Insert sort

We chose insert sort since it is expressible naturally within primitive recursion as opp osed

to more ecient algorithms such as Hoares quicksort which has a natural expression only in

terms of general recursion

The mathematical sp ecication

Informally this is straightforward enough For every list l over some type which carries

a decidable linear ordering there exists a sorted list m which is a p ermutation of l In a

formal treatment we must give explicit representations of the notions of sortedness and

p ermutation We used an impredicative denition of the p ermutation relation which we do

not discuss here The predicate Sorted was dened by recursion

Sorted l a l

a l list

S or tednil Sorted a l

where

a l a b

a b l list

a nil a a b l

As we observed in the section on dep endent list recursion Sorted may b e seen as an instance

of the depListof constructor while the predicate l list a l for a is just an instance of

Listof

A correctness pro of for insert sort

Here is the ML prototype for the sort that we wrote with a view to proving correct

fun listrec n c l fold fn am c a m l n

val swapcons fn b fn p

let val cm p

in maxcb mincb m

end

fun scons a l let val bm listrec anil swapcons l

in bm

end

val sort listrec nil scons

and here is its translation into LEGO co de

swapcons ATypebApA list A

min p pcons max p p m

scons ATypeaAllist A

p listrec anil swapcons lcons p p

sort listrec nil scons

We anticipate two levels of induction in the correctness pro of for this function since sort is

dened by nested recursion We recall the derived induction principles for recursive program

phrases which we used to explain recursive deliverables

for list Prop n c list

l m

l b a l list b

nil n a l c a l b

l list l listrec n c l

a consequence of which is the following induction principle for sorted lists which is just the

pro of comp onent of an instance of the depListrec combinator we considered ab ove

for list Prop n c list

l m

Sorted a l l b a l list b

nil n a l c a l b

Sorted List Induction

l list Sorted l l listrec n c l

This induction principle exemplies the motivation for secondorder deliverables namely that

a relation b etween lists holds only on the condition that one of them is sorted

The correctness pro of pro ceeds by application of the rst induction principle for the outer

most recursion this pro duces as subgoals

a Sorted nil nil nil

b a l mlist Sorted m l m

Sorted scons a m a l scons a m

Now a is immediate and b reduces to

a mlist Sorted m Sorted scons a m a m scons a m

introduction extends the context with the assumption a and in this extended context we

dene the relativised sp ecication

m nlist Sorted n a m n

a

Now we may apply Sorted List Induction to yield the following subgoals in the new context

c a nil a nil Sorted a nil

d b m nlist Sorted b m mn b mswapcons b m

a a

c is trivial and d reduces to

b c m nlist Sorted b m Sorted c n a m c n

Sorted min b c max b c n a b m min b c max b c n

This last goal rests apart from some trivial prop erties of on the following

Lemma Suppose a b c and m n list such that

Sorted c n

c n a m

b m

Then max b c n

The pro of recast in terms of deliverables

We have a double recursion in the denition of our program which translates into a nested

list recursion at the level of deliverables The base case of each induction is resolved with a

simple p ointwise construction So to o is the inner step case for the verication of the swapcons

function with some additional prop ositional reasoning

However there is a p oint of considerable delicacy in the course of this pro of There is a stage

at which we must shift from a secondorder deliverable over the identically true predicate

on lists dened by the outermost recursion to the inner recursion on secondorder deliverables

dened over the predicate Sorted It app ears that we must eliminate the input parameter l

using the p ermutation relation which moves the condition S or tedm from b eing a condition

on a result to b eing a condition on the input to scons This is the reduction in case b ab ove

from

a l mlist Sorted m l m Sorted scons a m a l scons a m

to

a mlist Sorted m Sorted scons a m a m scons a m

This shift allows us to apply the principle of Sorted List Induction

This is rather inconvenient and moreover it seems that only ad hoc solutions exist to resolve

the diculty Rather than attempt a detailed exp osition here we merely remark on the rather

unsatisfactory nature of this step in our derivation The details are in

We outline the signicant renement steps in the derivation

We seek as a toplevel goal

insertsort

SortSpec

where SortSpec l m Sorted m l m

def

The outermost recursion uses the Listrec combinator which we apply after splitting the

initial goal with the comp osition op erator

step

base

SortSpec

compose

insertsort

SortSpec

F

step

cons a SortSpec a SortSpec

list

Listrec

step

SortSpec

instantiates subgoal with the sp ecication nil SortSpec

The base case of this recursioninduction is resolved by a p ointwise construction Moreover

we can prove that any p ermutation of the nil list must b e equal to nil and the nil list is

trivially sorted Hence we obtain the correct instantiation

value nil

proof Sorted nil nil nil

pointwise

base

nil SortSpec

The step case is a little more complicated We rst introduce the parameter a in the

Listrec rule Recall that the algorithm we considered ab ove contains a let construct

fun scons a l let val bm listrec anil swapcons l

in bm

end

Now comp osition of deliverables explicates the let construct For the second comp onent of

this comp osition we just use the secondorder deliverable analogue of the trivial construction

of Section We then fold this function into a relativised sp ecication with which we pursue

the inner recursioninduction

function p list p p

functional SortSpec SortSpec

cons a SortSpec SortSpec

compose

F a

step

cons a SortSpec SortSpec

where SortSpec p list p p cons a SortSpec

def

Eliding the details we massage the goal SortSpec SortSpec into a form in which

we may exploit the principle of Sorted List Induction It turns out that the target sp ecication

remains as SortSpec

SortSpec Sorted

SortSpec SortSpec

As indicated ab ove we are now in a p osition to use the depListrec combinator Again we

preface its application with an app eal to comp osition

step

base

Sorted SortSpec Sorted

compose

SortSpec Sorted

G

step

b SortSpec cons b SortSpec cons b Sorted

depListrec

SortSpec Sorted

endlegolist

The pro of concludes by considering a p ointwise construction in the base case of the induction

value a nil

proof Sorted a a a

pointwise

base

nil SortSpec Sorted

and then an account of the verication of the swapcons function in the step case We omit the

details which exploit the informal argument of Lemma

A settheoretic mo del

In the foregoing discussion our emphasis lay on using and constructing deliverables in the

context of a particular type theory and its machine implementation However the idea of

deliverables need not b e restricted to this particular seeting We observed that one could

mo del deliverables in the framework of elementary set theory The thesis gives a detailed

categorical account of this mo del showing how it supp orts the interpretation of a subtheory of

ECC Indeed the mo del is parametric in the choice of an underlying topos categorical mo del

of set theory We sketch the main ideas We refer the reader to for a complete account

In this interpretation a closed type is given by a pair of sets A A with A A In

particular the type Prop of prop ositions is given by the pair where is the sub ob ject

classier A morphism b etween such ob jects is given by the obvious abstract notion of rst

order deliverable ie an arrow on the underlying sets which resp ects the distinguished subsets

This data gives us an interpretation of contexts and morphisms b etween them

Types in a given context X X are given by the relativised sp ecications ie pairs

of sets A R where now R X A Without going into further detail this structure gives

rise to a bration whose bres essentially consist of the secondorder deliverables describ ed

ab ove Moreover this bration has sums pro ducts and a small subbration and thus supp orts

an interpretation of the PropType Type fragment of ECC In the presence of settheoretic

universes given for example by inaccesible cardinals we may mo del the whole of ECC

Related work

Two approaches to a logical account of formal program development are well known The rst

relies on annotating programs with logical formulae and expressing the correctness of a program

in terms of logical deductions This has its origins in the work of Floyd Hoare and others in the

Sixties for example The idea of a deliverable clearly has echoes of this idea but brought

into the functional setting It also avoids the defect of the FloydHoare style in having ob ject

language and metalogical variables on the same fo oting as ob ject variables of our chosen type

theory

The second approach based on various intuitionistic type theories has b een to develop

constructive pro ofs and use realisability techniques to extract algorithmic information Both

MartinLof type theory and the Calculus of Constructions have b een used in

this style Our work uses ideas from b oth these schools Most inuential has b een the theory

of subsets in MartinLof type theory This has b een given an elo quent treatment in Chap

ter to which the reader is referred for a detailed discussion The central problem in using

constructive pro ofs as a programming discipline is that pro ofs contain redundant information

Dep endent types allow us to express logical predicates as types but do not p ermit the repre

sentation of any more recursive functions For the Calculus of Constructions this has a precise

statement in the result of Berardi and Mohring

Theorem CC is conservative over F

Consequently CC can represent in the standard Church representation of functions on in

ductive types no more functions than F The pro of is based on a syntactic mapping the

socalled BerardiMohring pro jection Mohring used this mapping as an extraction function

which coupled with the asso ciated realisability predicate allows a p owerful and exible ap

proach to program development from pro ofs Under this interpretation an arbitrary type is

interpreted as a type together with a predicate the realisability predicate dened over it

The approach taken in is to separate computationally relevant pro ofs from the purely

logical via a translation of the judgments of the basic formal system into multiple judgments

This translation p ermits the formation of a subset type fx AjB xg for which a reasonable

elimination rule may b e given An attempt to equip the basic theory with such a type which

may b e used to precisely hide the information of the precise nature of a pro of that predicate

B x holds yields very unsatisfactory results

Given the basic theory of types and terms in MartinLof type theory the rst step is to

extend the theory with a notion of proposition and a judgment P true for prop ositions This

is very straightforward using prop ositions as types A prop osition is just a type in the basic

theory A prop osition is true if there is some element inhabiting it again in the basic theory

This seemingly inno cent pro ofirrelevance gives the subset theory its p ower

The subset theory now interprets the basic judgment

A set

of MartinLof type theory as two judgments in the underlying theory prescribing

a set A in the basic theory and

a family of prop ositions A x prop x A again in the basic theory

This corresp onds to our denition of sp ecication in Section

Equality of sets A B is based on equality of the underlying sets A B but uses logical

equivalence of the families A B We rejected such a choice in favour of the decidable relation

of convertibility in ECC

The membership judgment a A is interpreted in the obvious way we may derive a A if

we can derive a A and A a true in the basic theory This captures the essential idea that

the judgments A set and a A should describ e subsets of the terms in A in the underlying

theory In this way the pro ofs of the prop ositions A a are systematically suppressed It is then

relatively straightforward to see how this allows the interpretation of a subsettype constructor

How do es this compare with our approach The resulting expressions for the various type

constructors are very similar compare for example the denition of exp onential for secondorder

deliverables with the type in the subset interpretation We consider explicit pro ofs of the

prop ositional parts of our sp ecications whereas we need only know that some pro of may b e

derived in the subset theory However this seems to b e one of the limitations of their approach

in that we only know that certain derivations in the subset theory arise from certain other

derivations Our use of types by contrast means that we can represent the derivations of

deliverables as actual terms within ECC using the denable combinators which co de up the

explicit translation The price we pay seems to b e that we have to work with a rather clumsy

language for these terms as opp osed to the conceptual elegance of reusing the basic language

of types and terms in the subset theory

The NuPrl system developed by Constable and his coworkers is based on early versions

of MartinLofs type theory In particular the underlying term calculus is untyped and the

system has extensional equality types This has the advantage of suppressing some irrelevant

information in pro ofs It also overcomes the limitations on the use of an explicit subsettype

constructor in a theory with intensional equality exp osed in The sovereign disadvantage

is that the basic judgments of the theory b ecome undecidable coupled with a proliferation of

wellformedness conditions in the application of the rules

Recently Hayashi has also prop osed a system based on realisability which abandons the

usual type constructors on which most work to date on type theory has b een based in

favour of a more settheoretic style with union intersection and singleton types The system

he considers is however ingenious enough to represent dep endent pro ducts and dep endent

sums At the same time the typing rules for union and intersection hide information This

allows a simple translation or extraction into a programming language with a p olymorphic type

discipline Singleton types seem essential in achieving this harmony b etween the type system

and the underlying untyped terms

Pavlovic in his thesis elab orates in categorical terms a theory of constructions in which

programs do not dep end on pro ofs of logical prop ositions As with the mo dels of Constructions

considered by Hyland and Pitts the emphasis is on extensional systems rather than the

intensional system we work with here Pro oftheoretic prop erties seem to b e regarded as some

thing an implementation would have to answer p

Conclusions

We have describ ed a pro of development metho d which takes as its basic entity a program plus

its correctness pro of If the programs are functional these program pro ofpairs admit exactly

the same combination op erators as do functions We have studied the mathematical theory of

such program pro ofpairs and the op erations which combine them and we have considered the

case where the pre and p ostconditions are contextually linked to express a relationship b etween

input and output The combination op erations have b een co ded within the Lego pro of system

a number of examples have b een developed in Lego and some metatheoretic results ab out the

op erations have b een proved in Lego

Acknowledgements

We would like to thank Randy Pollack for the Lego system and Zhaohui Luo for his contribution

to its theoretical underpinning We also thank our colleagues in the Lego Club for friendly

comments and stimulation We thank Per MartinLof Gordon Plotkin and Susumu Hayashi

for helpful comments on presentations of this work

References

JBenabou Fibred categories and the foundations of nave JSL

S Berardi Type Dependence and Constructive Mathematics PhD thesis Dipartimento

di Informatica Torino Italy

NG de Bruijn A survey of the project AUTOMATH in

RMBurstall and JHMcKinna Deliverables an approach to program development in Con

structions in also available as a University of Edinburgh technical rep ort ECSLFCS

RConstable et al Implementing Mathematics with the NuPrl Proof Development System

PrenticeHall New Jersey

TCo quand and GHuet Constructions a Higherorder Proof system for mechanizing

mathematics in Pro ceedings EUROCAL LNCS SpringerVerlag

TCo quand Metamathematical Investigations of a Calculus of Constructions in

PLCurien Categorical Combinators Sequential Algorithms and Functional Programming

Pitman Research Notes in Theoretical Computer Science Pitman London

EWDijkstra Guarded Commands Nondeterminacy and Formal Derivation of Programs

in Communications of the ACM Vol

JYGirard Interpretation fonctionel le et elimination des coupures dans larithmetique de

lordre superieure thesis University of Paris VI I

RHarp er and RAPollack Type checking with universes in Theoretical Computer Sci

ence Vol NorthHolland Amsterdam

SHayashi Adjunction of semifunctors categorical structures in nonextensional lambda

calculus in Theoretical Computer Science Vol NorthHolland Amsterdam

SHayashi Singleton Union and Intersection Types for Program Extraction in Pro ceed

ings of TACS Sendai Japan Springer LNCS SpringerVerlag

CARHoare An axiomatic basis for computer programming in Communications of the

ACM Vol

WAHoward The formulaeastypes notion of construction in

GHuet TCo quand CPaulinMohring et al The Calculus of Constructions Version

Documentation and users manual Rapp orts Techniques no Pro jet Formel INRIA

Ro cquencourt Paris August

GHuet and GPlotkin eds Electronic Proceedings of the First Annual BRA Workshop on

Logical Frameworks Antibes May distributed electronically to participating BRA

sites January

JMEHyland and AMPitts The Theory of Constructions Categorical Semantics and

Topostheoretic models in Pro ceedings of the AMS Conference on Categories in Computer

Science Boulder Colorado

PTJohnstone and RPare eds Indexed Categories and their Applications Springer

LNM SpringerVerlag

JLambek and PJScott An Introduction to HigherOrder Categorical Logic Cambridge

Studies in Advanced Mathematics no Cambridge University Press Cambridge England

ZLuo ECC an Extended Calculus of Constructions in Pro ceedings of the Fourth IEEE

Conference on Logic in Computer Science Asilomar California

ZLuo An Extended Calculus of Constructions PhD Thesis Department of Computer

Science University of Edinburgh June

ZLuo Program Specication and Data Renement in Type Theory Technical Rep ort ECS

LFCS Department of Computer Science University of Edinburgh January

ZLuo and RPollack LEGO Proof Development System Users Manual LFCS Technical

Rep ort ECSLFCS

JHMcKinna Deliverables a categorical approach to program development in type theory

PhD thesis University of Edinburgh

PMartinLof An Intuitionistic Theory of Types Predicative part in Logic Collo quium

NorthHolland Amsterdam

PMartinLof Constructive Mathematics and Computer Programming in pro ceedings of

the Conference on Logic Philosophy and Metho dology of Science VI NorthHolland

Amsterdam

MMendler The Logic of Design PhD thesis University of Edinburgh forthcoming

BNordstrom KPetersson and JSmith Programming in MartinLofs type theory Oxford

University Press

CPaulinMohring Extracting F s programs from proofs in the Calculus of Constructions

in Pro ceedings POPL ACM

CPaulinMohring and BWerner Extracting and Executing Programs developed in the In

ductive Constructions System a Progress Report in

DPavlovic Predicates and Fibrations pro efschrift University of Utrecht

ASalvesen and JSmith On the strength of the subset type in MartinLofs type theory in

Pro ceedings of the Third LICS Symp osium IEEE

ASalvesen On Information Discharging and Retrieval in MartinLofs type theory PhD

thesis Institute of Informatics University of Oslo

DSannella Formal specication of ML programs LFCS technical rep ort ECSLFCS

Dept of Computer Science University of Edinburgh

JPSeldin and JRHindley eds To HBCurry essays in Combinatory Logic calculus

and Formalism Academic Press

SStenlund Combinators calculus and Proof Theory DReidel Dordrecht

Pattern Matching with Dep endent Types

Thierry Co quand

Chalmers University

Preliminary version June

Introduction

This note deals with notation in type theory The denition of a function by pattern matching

is by now common and quite imp ortant in practice in functional programming languages see

for instance We try here to introduce such denitions by pattern matching in MartinLofs

logical framework

Statement of the Problem

A Short Presentation of MartinLofs Logical Framework

For a more complete presentation of MartinLofs logical framework which is implemented in

ALF we refer to the b o ok Programming in MartinLofs Type Theory chapter and

We recall that each type T is of the form x A x A A where A is Set or of the

n n

form E l a If A is of the form E l a we say that T is an small type and it is a large type

otherwise if A is Set If a type of a term is of the form x A x A A we say that n is

n n

the arity of this term An instance of a term u of arity n is a term denitionally equal to a

term of the form uv v

n

A context is a list of type declaration x A x A As in we relativize

n n

all judgements of type theory with resp ect to a context An interpretation or contextual

mapping b etween two contexts x A x A and y B y B is a

n n m m

simulateneous substitution S fy v y v g such that

m m

v B v B v v B v v

m m m

We write in this case S If M is an op en expression in we write by simple

juxtap osition MS the result of the substitution S to M Notice that if A is a type in then

AS is a type in and if a A then aS AS

If T and T we write T T the comp osition of T and T

MartinLofs logical framework is an op en framework the user can add new constants and

new computation rules

co quandcschalmersse

1

If v is denitionally equal to y we omit y v in the writing of the interpretation thus fx g is a

i i i i

contextual mapping from y N to x N y N meaning fx y y g

For instance we get the sets by declaring the constants

X Set X Set Set

pair X Set Y X Set x X Y x X Y

split X Set Y X Set Z X Y Set

x X y Y x Z pair X Y x y

w X Y

Z w

and asserting the equality which can b e read as a computation rule

splitA B Z z pair A B a b z a b Z pair A B x y

where

A Set

B A Set

Z A B Set

a A

b B a

z x A y B x Z pair A B a b

The usual cartesian pro duct is dened by

A B A xB Set A Set B Set

The set of natural numbers is introduced by declaring the constants

N Set

N

succ N N

natrec C x N Set C x N y C x C succx n NC n

and the equalities which can b e read as computation rules

natrec C x z x C

natrec C x z succ a z a natrec C x z a

where

C x N Set

x C

z x N y C x C succx

The computation rules generate the denitional equality b etween terms

2

We allow ourselves to write in general A instead of E l A

Quite imp ortant is the distinction b etween canonical and noncanonical constants In

the examples ab ove pair N and succ are canonical constants but split natrec and are

non canonical

If the type of a canonical constant C is of the form x A x A Set we say that C is

n n

a connective The meaning of a connective C is given by a set of canonical constants of types

of the form y B y B E l C a a that are called constructors of C In the

m m n

case of mutual inductive denitions we can have a set of connectives that are simultaneously

dened by a set of canonical constants By extension we consider also that connectives are

constructors of the type Set

A canonical constant whose type is a small type is considered to b e a primitive notion that

is selfjustifying In the example ab ove and succ are considered to b e primitive notions and

the canonical set N is dened by its set of constructors and succ

We say that a term is in constructor form i it is denitionally equal to a term of the form

cu u where c is a constructor of arity n The constructor c is then uniquely determined

n

We say that a term t is directly structurally smaller than a term u i

b oth u and v are of small types and of arity

u is of constructor form ca a and t is denitionally equal to one a of arity or

n j

one instance of one a of arity

j

Being structurally smaller is dened by taking the transitive closure of this relation

We use in an essential way the no confusion prop erty of constructors This covers two

prop erties The rst is that a denitional equality b etween two terms of the form au u

n

and bv v if a and b are two distinct constructors cannot hold The second is that if c

m

is a constructor of type x A x A A then the equality cu u cv v

n n n n

Au u implies

n

u v A u v A u u

n n n n

The non canonical constant is explicitely dened in term of split

The denitions of split and natrec are not explicit and we refer to these constants as im

plicitely dened constants The meaning of implicitely dened constants is given by their

computation rules

It is an imp ortant problem to give some criteria that ensure the correctness of the addition

of new constants and computation rules We try here to analyse this problem using the pattern

matching notation introduced in functional languages see for instance

Inductively dened connectives

We shall consider only connectives that are inductively dened The relation of b eing structurally

smaller is then exp ected to b e wellfounded We shall take this wellfoundness prop erty as a

fundamental assumption on the constructors without trying to analyse it further here We

simply mention that the constructors presented in satisfy this wellfoundness prop erty

Here are two counterexamples

The set

V Set

with one constructor

A SetAAV

The p olymorphic identity A xx is of type A SetAA and hence the term A xx

is of type V This term is structurally smaller than itself It follows that the relation of b eing

structurally smaller is not wellfounded

Likewise the set

U Set

with one constructor

c SetU

has to b e rejected The reason is however more subtle than for the previous counterexample

We notice rst that were this set accepted so would b e T U Set by T cX X Set We

could then introduce a set W Set with only one constructor sup x U T xW W which

is inductively dened given U T But then supcW xx is structurally smaller than itself

The rst example suggested by a remark of Per MartinLof shows that the wellfoundness

requirement on the relation of b eing structurally smaller is a stronger requirement than mere

normalisation Indeed the set V is dened by a secondorder quantication and it can b e

shown by the usual reducibility metho d that its addition to inductively dened sets preserves

the normalisation prop erty

Some diculties with the usual elimination schemas

It is known how to asso ciate to any inductively dened connective an elimination constant

together with its computation rules This is describ ed for instance in One can check that

all the examples of implicitely dened constants and computations rules describ ed in are

of this form A rst criteria for ensuring the correctness of the addition of new constants and

computation rules is to allow only the addition of such elimination constants Exp eriments with

restricting the addition of implicitely dened constants to b e elimination constants have shown

some drawbacks of this approach

One rst drawback is that we do not quite get the exp ected computational b ehaviour If we

dene for instance add N NN by addx y natrecy x u v succ v then addx succ y

reduces to succ natrec y x u v succ v and one needs to fold back this expression to get the

exp ected succaddx y

One second drawback is readability For instance we want to consider an ob ject such as

half NN dened by

half half succ half succ succ x succhalf x

as given directly by these equations rather than b eing given by an explicit denition which is

a co ding of this ob ject in term of natrec

The second drawback is in practice quite imp ortant The pattern matching notation is

essential in functional programming languages

The next anomaly is the necessity to consider higher sets for dening naturally a function

such as inf N NN It is quite surprising that in order to justify the equations

inf y inf succ x inf succ x succ y succ inf x y

one needs to introduce the set of numerical functions

Another problem app eared for inductively dened families Given a connective with an

arity there are several p ossible elimination constants dep ending on what arguments are

considered to b e parameters For instance there are two dierent elimination constants for the

connective Id A Set x y ASet of unique constructor re A Set x AId A x x In this

case it is yet unknown if these two elimination constants are equivalent

The rst and in particular second drawbacks are strong motivations for allowing the intro

duction of implicitely dened constants dened by computation rules that are pattern matching

equations This seems to solve in general the third anomaly In an unexp ected way this seems

to have some b earing on the fourth problem as we will try to explain b elow

A General Presentation of Pattern Matching

There are two indep endent requirements for the correctness of the introduction of one implicitely

dened constant together with its computation rules These requirements are only sucient in

ensuring that the constant do es dene a total function on the underlying datatype

The rst is the requirement that all denitions that may b e recursive are wellfounded

The second is that the equations cover all p ossible cases of the arguments and do not

introduce ambiguities in the computation We ensure this by imp osing the denitions to b e

exhaustive and mutually disjoint

Wellfounded Denitions

A simple condition ensures the fact that all denitions are wellfounded and seem furthermore

sucient in practice Let n b e the arity of the implicitely dened constant f to b e dened

The condition is that there exists an index i n such that for all equations f u u e

n

and all recursive call f v v of f in e the constant f do es not o ccur in v v and the

n n

term v is structurally smaller than the term u

i i

It would b e p ossible to give a less restrictive condition by considering instead a lexicographic

extension of the structural ordering However this restriction suces to recover the usual

elimination schemas It is also quite simple to ensure that this condition holds

Notice that this condition provides more general equations than the ones provided by the

usual primitive recursive schema In the usual primitive recursive schema indeed the parameters

cannot vary in recursive calls This is not required here

3

The earliest to our knowledge mention of this notation app ears in A prop osal of extending functional

language with an inductive case expression which hence ensures termination is presented in

For instance this will justify directly the following kind of denitions of a a function f

N NN

f m g m f succ n m hn m f n k n m

where g NN h N N NN and k N NN are previously dened functions Notice that the

parameter m changes to k n m in the recursive call of f This can b e done only using the set

of numerical function if we restrict ourselves the usual schema of primitive recursion see

Covering

To analyse further the condition that the denitions are exhaustive and mutually disjoint we

introduce one notion reminiscent of a notion used in Per MartinLofs representation of choice

sequences in type theory

Let us motivate briey what follows We want to add a new implicitely dened constant f

of type x A x A A together with a set of computation rules Let b e the context

n n

x A x A of arguments of f We only consider computation rules for f of the form

n n

f a a e Aa a

n n

with a A a A a a We can think of a a as dening a contextual

n n n n

mapping S and this suggests to introduce the notation f S e AS for such a

computation rule

With this notation the conditions on a system of computation rules f S e AS

j j j j

will b e expressed as conditions on a system of contextual mappings S We want to

j j

express that such a system denes a partition of the space dened by

We are going to analyse this problem in the same way that pattern matching in ordinary

functional languages is reduced to a succession of case expressions over a variable see

We say rst that a system of contextual mapping S S over a

m m

common context x A x A is an elementary covering of i there exists an

n n

index i n such that

all terms x S A S for j m are in constructor form

i j i j j

if S is a contextual mapping such that x S is in constructor form then there

i

exists one and only one j m and T such that S T S

j j

This denition may lo ok complicated but it is a p ossible way of sp ecifying what is a case

expression over the ith argument In the case of a context with only non dep endent types we

recover the usual notion of case expression as in In the general case however we cannot

keep the same notion of patterns of as the examples b elow will show we need for instance

to consider non linear patterns and our abstract denition seems necessary

An instance is the elementary covering dened by x and x succy y N of the

context x N

A second example is the empty set of contextual maps over the context

p IdN succ

This is an elementary covering Indeed the only constructor of the connective Id is re and

a term of the form reA u cannot b e of type IdN succ Otherwise we would have

IdN succ Id A u u

and hence b ecause Id is a constructor u N and succ u N But this implies

succ N which do es not hold b ecause and succ are dierent constructors

A more elab orate example is for the context

x y N p q Id N x y

It can b e checked that if we dene

x N p IdN x x

then the unique contextual mapping

fy x q re N xg

denes an elementary covering of Indeed this follows from the fact that re is the only

constructor of Id and that if reN u is of type Id N v w we have

IdN u u IdN v w Set

and hence since Id is a constructor we have u v N and u w N

We dene now what it means for a system of contextual mapping S into a

i i

common context to b e a covering of

the identity interpretation is a covering of

if S for i p is an elementary covering of and T for j q is

i i ij ij i i

a covering of then T S is a covering of

i ij i ij

For instance x together with x succ and x succ succ y y N dene a

covering of x N

An example of covering of the context x N y N is given by

fx g y N

fx succ x y g x N and

fx succ x y succ y g x N y N

If we take again our last example of an elementary covering it can b e checked that the

unique contextual mapping

fp reN xg x N

is an elementary covering of Hence the unique contextual mapping

fy x p reN x q reN xg x N

is a covering of x y N p q Id N x y

Following Per MartinLofs terminology we call neighbourho o d of a context any con

textual map that is part of a covering of this context The collection of neighbourho o ds of a

covering of a context can b e thought of as dening a partition of the space dened by this

context This notion of neighbourho o d corresp onds to the notion of patterns used in functional

programming languages in the case of a context with only non dep endent types we recover

exactly the notion of pattern matching describ ed in

Sucient Conditions For Correctness

The sucient conditions ensuring the correctness of the addition of a new implicitely dened

constant f of type x A x A A of argument context x A x A and of

n n n n

computation rules of the form f S e AS are that

j j j j

there is no nested o ccurence of f in e and all recursive call of f are done on structurally

j

smaller arguments than the lefthandside arguments which can b e ensured as describ ed

ab ove

the system of contextual maps S is a covering of

j j

Some comments on this metho d

The metho d followed here can b e describ ed as follows When justifying a rule

f x A x A A

n n

we analyse exhaustively the p ossible forms S of the arguments of f and in each p ossible case

S we build a term e of type AS using constructors and already dened constants

S

We allow recursive calls of the constant we are dening provided these calls are on struc

turally smaller arguments

Naturally asso ciated to this justication of an implicitely dened constant

f x A x A

n n

is the following computation rule for f If a given argument a a is an instance of the case

n

S then the value of f a a is the value of the corresp onding instance of e Otherwise

n S

the argument list of f is not instantiated enough and f a a cannot b e head reduced

n

Some Examples

The function inf N NN which is dened implicitely by

inf y inf succ x inf succ x succ y succ inf x y

The recursive call is justied by the fact that it is structurally smaller on the rst or the

second argument

It is standard how to reduce such a denition to the usual elimination rules over the type

N by using the set of numerical functions

By contrast it is not clear how to represent the following computation rule in term of the

usual elimination rules We have seen that the unique contextual mapping

fy x p reN x q reN xg x N

is a covering of x y N p q Id N x y It follows that it is correct to add a new constant

f x y N p q IdN x y Id Id N x y p q together with the computation rule

f x x reN x re N x reIdN x x re N x x N

The next example still concerns the connective Id As we said b efore there are two p ossi

ble elimination rules over this connective dep ending on what arguments are considered to b e

paramaters

The rst one with the rst argument is a parameter is

F A Set C x y A IdA x y Set

d x AC x x re A x a b A c IdA a b

C a b c

of computation rule

F A C d a a re A a da C a a re A a

where

A Set C x y A Id A x y Set d x AC x x re A x a A

The second one with the rst two arguments are parameters is

G A Set a A C y A Id A a y Set

d C a reA a b A c IdA a b

C b c

of computation rule

GA a C d a re A a d C a reA a

where

A Set a A C y A IdA a y Set d C a reA a

It can b e checked that b oth constants satisfy the sucient conditions for correctness given

ab ove Only the covering condition has to b e checked b ecause there is no recursive call

The last example is the wellfounded set connective

W A Set B ASetSet

of unique constructor

sup A Set B ASet a A u B aW A B W A B

4

This problem has b een indep endently suggested by Thomas Streicher

We can introduce the implicitely dened constant

wrec A Set B ASet C W A B Set

f a A u B aW A B x B aC uxC sup A B u t W A B C t

with the computation rule

wrec A B C f sup A B a u f a u xwrec A B C f ux

where

A Set B ASet C W A B Set f a A u B aW A B x B aC ux

This is justied since ux is structurally smaller than supA B a u

How to build coverings

Unication Problem

If is a context A a type in and u v two terms in of type A we dene a solution of the

unication problem

u v A

to b e a nite system of contextual mappings S such that

j j

for all j we have uS v S AS and

j j j j

if S is a contextual mapping such that uS v S AS then there exists one

and only one j and T such that T S S

j j

For a description of the unication problem with dep endent types see and Since

this problem contains already the similar problem for simply typed lambdacalculus describ ed

in we cannot exp ect to have a general algorithm to solve it It is however p ossible to

describ e a simple algorithm that has three p ossible outputs

the system with no contextual mapping this ensures that the unication problem has no

solution

a system with exactly one contextual mapping this ensures that the unication problem

has a most general solution

the algorithm fails which corresp onds to a dicult unication problem

5

This algorithm is similar to the rstorder unication algorithm using the fundamental fact that constructors

are onetoone function

Splitting Contexts

We give rst a way to build elementary coverings as it is implemented in ALF We cannot ensure

that this generates all p ossible elementary coverings but it is not clear yet how to extend this

algorithm and whether such an extension is needed or not in practice

Given a context

x A x A

n n

and an index i n such that A is a small type we describ e an op eration called splitting the

i

context along i This is an algorithm that tries to pro duce an elementary covering of

if A is of arity or if A is not in constructor form then the algorithm fails to pro duce

i i

any covering

otherwise A is of the form E l C u u and we can list all the constructors of the

i n

connectives C For each such constructor c of type y B y B E l C v v

m m m

we apply the previous unication algorithm for the equation

C u u C v v Set x A x A y B y B

n n i i m m

and we collect all the solutions

Given the fundamental no confusion prop erty of constructor this pro duces in case of

success an elementary covering of

General Coverings

General coverings can now b e built interactively Given a context the user chooses an index

i and tries to split along i If the system answers by giving an elementary covering the user

can then choose to split some of the new pro duced contexts and so on until the user stops

eventually pro ducing by comp osition a covering of

This interactive way of building coverings has b een implemented in ALF and seems in

practice to b e quite convenient for the user in ensuring that no cases have b een forgotten during

the denition of a function by pattern matching This is in contrast with the usual presentation

in functional languages where one should write the p ossible cases and the compiler warns the

user that some cases have b een forgotten

The following is a semialgorithm that checks whether or not a system of contextual map

pings S is a covering thanks to G Huet

j j

First the system with only the identity mapping is a covering Otherwise choose an index

i such that all x S are in constructor form Then if p ossible split along i If the answer

i j

is an elementary covering T of this induces a partition of the original system

i i

S into a system of mappings We then recursively check that each of these

j j j i

systems is a covering

6

If we think of a covering as a collection of disjoint pieces that form a partition of a space this semi

algorithm solves a typical puzzle problem We are given some pieces of a space contextual mapping and

we try to see whether or not they form a partition of this space

Addition of Subsets

Kent Petersson and indep endently A Salvesen suggested the following notion of subsets which

seems to t nicely with the present notion of implicitely dened constants We limit here

ourselves to the description of a simple example

The meaning of a connective such as N Set is given by the set of its constructors

N succ NN

It is quite natural to allow the introduction of direct subsets of N that we get simply

by selecting a subset of this set of constructors For instance we can introduce the subset

ISZERO Set with the only constructor and the subset POS Set with the only constructor

succ

This notion of subsets ts well with the present way of dening a function by pattern

matching where one imp ortant step is to list the constructors of a given connective

For instance the unique computation rule denes then correctly an implicitely dened

function p POSN

psucc x x x N

b ecause the context x POS is covered by the contextual mapping x succ x N x N

We can dually allow the introduction of direct sup ersets of N that we get by adding new

constructors Typically the set of ordinals Ord Set extends the set N by the addition of one

constructor

lim NOrd Ord

The following computation rules dene then correctly an implicitely dened function g

OrdN

g g succ x succ x g lim u g u

This denition is justied since u is structurally smaller than limu

We can then dene a general inclusion relation b etween connectives by taking the transitive

closure of the direct inclusion relation dened by the introduction of subsets and sup ersets This

is a decidable relation

As the last example shows the addition of subsets and sup ersets introduces some overloading

facilities These do not however compromise the decidability of the following problems

is the expression A a correct type in the context

given a type A in the context is the expression a a correct term of type A in the context

as we can convince ourselves by noting that the usual algorithm for these problems apply almost

without changes using the decidability of the inclusion relation b etween connectives

It is hop ed that with these new op erations one can represent rather faithfully the example

presented in

A more elab orate notion of subtypings app ears in

Conclusion

As an exp eriment of using pattern matching we have done in ALF the Gilbreath Trick presented

by G Huet last year which is a non trivial inductive pro of This example shows well the

gain in readibility that brings the pattern matching notation While doing other exp eriments

it app eared that a quite useful extension of the system would b e the introduction of case

expressions for pro ofs where the case is over a term that may not b e in variable form More

generally the goal seems to b e to develop nice enough notations that will hop efully help the

analysis of inductive arguments

The metho d we follow here has some similarities with Lars Hallnas notion of partial inductive

denitions see and with the way pro ofs are represented in Elf What we do seems

to corresp ond to a suggestion of to use this notion as a basis for a logical framework

These connections have to b e precised

In the present analysis of pattern matching a crucial role is played by the no confusion

prop erty of constructors In Language and Philosophical Problems p S

Stenlund emphasizes from a philosophical p ersp ective the imp ortance of this prop erty

From a pro oftheoretic viewp oint our treatment can b e characterized as xing the meanings

of the logical constants by the introduction rules This p ossibility is discussed in and

constrasted to the p ossibility which is to x the meanings of logical constants by the

elimination rules

References

Augustsson L Compiling Pattern Matching In Compiling Lazy Functional Languages

Part I I Ph D Thesis Chalmers

Burstall RM Proving prop erties of programs by structural induction Computer Jour

nal p

Burstall RM Inductively Dened Functions in Functional Programming Languages

Journal of Computer and System Sciences vol p

Colson L Ab out Primitive Recursive Algorithms LNCS p

Dummett M The Logical Basis of Metaphysics Duckworth ed

Dyb jer P Inductive Sets and Families in MartinLofs Type Theory Chalmers Rep ort

also p in Logical Frameworks eds G Huet and G Plotkin Cambridge Uni

versity Press

Dyb jer P An inversion principle for MartinLof s type theory Pro ceedings of the

Workshop on Programming Logic in Bastad May Programming Metho dology Group

Rep ort p

Dyb jer P Universes and a General Notion of Simultaneous InductiveRecursive Deni

tion in Type Theory in these pro ceedings

Elliott C M HigherOrder Unication with Dep endent Function Types p

Pro c Rewriting Techniques and Applications

Eriksson LH A Finitary Version of the Calculus of Partial Inductive Denitions SICS

research rep ort also to b e published in LNCS Pro ceedings of the Second Workshop on

Extensions of Logic Programming

Freeman T and Pfenning F Renement Types for ML to app ear in ACM SIGPLAN

Conference on Programming Language Design and Implementation

Hallnas L Partial Inductive Denitions Theoretical Computer Science p

Huet G A unication algorithm for typed calculus Theoretical Computer Science

p

Huet G The Gilbreath Trick A Case Study in Axiomatization and Pro of Development

in the COQ Pro of Assistant Technical Rep ort INRIA September

Kahn G Natural Semantics INRIA Technical rep ort

Nordstrom B Petersson K Smith J M Programming in MartinLof Type The

ory Oxford Science Publications Clarendon Press Oxford

Pfenning F Logic Programming in the LF logical framework in GHuet and G Plotkin

Logical Frameworks Cambridge University Press

Pym D Proofs Search and Computation in General Logic Thesis University of Edin

burgh November

Ranta A Constructing p ossible worlds Mimeographed University of Sto ck

holm to app ear in Theoria

Stenlund S Language and Philosophical Problems Routledge ed

A pro of of normalization for simply typed lambda calculus

written in ALF

Catarina Co quand

Preliminary version august

Abstract

We will in an semantic way dene a normalization function by sructural induction for

simply typed lambda calculus First we write a function that evaluates the semantics of a

term and then we dene a co ding that gives a term on normal form back The work has

b een done in a fragment of type theory using the pattern matching of ALF

Keywords and Phrases Type Theory Normalization Pro of Theory Lambda Calculus

Introduction

One aim of this work has b een to show completely formally a pro of of normalization of simply

typed lambda calculus in such a way that it can hop efully b e extended to type theory with

dep endent types Another aim has b een to gain exp erience in working in ALF and for example

has this work suggested the pattern matching now implemented in ALF

We will in this pap er present a function by structural induction that computes the normal

form of a term This function is build up by two functions one that evaluates the semantics of

a term and one that from the semantics gives an etaexpanded term on normal form back The

idea that one could write an evaluation function like this was p ointed out to me by Th Co quand

and P Dyb jer and Th Co quand also p ointed out that it was p ossible to write the co ding back

function

The denitions b elow are all as in the implementation in ALF but the monomorphic type

information has b een taken away when this improves the readability In ALF as it stands now

there is no control that the functions are dened by structural induction but it should b e clear

from the denitions that this is the case It should also b e clear that the denitions follows the

schema presented in

The theory

The theory used is Martin Lofs type theory with intensional identity Id pro duct with the

pairing constructor a b one element set T with constructor tt and cartesian pro duct of

Programming Metho dology Group Department of Computer Sciences Chalmers University of Technology

and University of Goteborg S Goteborg Sweden email catarinacschalmersse

dep endent types with constructor For a full description of this see NPS Observe

that we do not dene the elimination rules instead we will use the pattern matching of ALF

We will overload the notation and in the text b elow in fact we dene a each for

the number of abstractions we make A A B We will also write t t instead of

n n

IdA t t

The syntax

The syntax of the lambda terms are standard except for that we have explicit substitution on

the terms Having explicit substitution is not essential in this pap er but is probably usefull for

future extensions

Denitions of types

The types we have are base type and function type The set of types

T y pe Set

is introduced by

A B T y pe

o T y pe AB T y pe

Types will b e named A B

Denition of contexts

A context is a list of types and the set of context

C ontext Set

is introduced by

C ontext A T y pe

C ontext A C ontext

Context will b e named and in the text b elow

We also dene the relation of extensions b etween contexts

C ontext C ontext Set

with the constructors

e A T y pe e A T y pe

ext ext e A ext e A A

1

Please do not b e confused by this

Notice how the third constructor simplies the denition of shift b elow

Extensions will b e named e b elow

We will now dene the transitivity function or if one wants show the transitivity of

tr ans e e

The denition or pro of is done by induction rst on e and in the case ext by induction on

e

tr ansext e e

tr ansext e e ext tr anse e

tr ansext e ext ext e

tr ansext e ext e ext tr anse e

tr ansext e ext e ext tr anse e

We have that tr ans is asso ciative ie

tr anse tr anse e tr anstr anse e e

we also have that

tr anse ext e

Denition of variables terms and substitutions

As said ab ove the terms are dened in a standard way except for the explicit substitution A

substitution from a context to a context denoted S ubst is inuitively a list that

asso ciates to each variable of type A in a term of type A in The substitutions we will

have are the empty up dating identity comp osition monotonicity and pro jection substitution

Variables are dened in a deBruijnindex style

We will dene the sets of variables terms and substitutions

V ar T y pe C ontext Set

T er m T y pe C ontext Set

S ubst C ontext C ontext Set

where the constructors of V ar are

v V ar A

v ar V ar A A v ar v V ar A B

and the constructors of T er m are

t T er mA e

mont e T er mA c T er mo

v V ar A t T er mB A

v ar v T er mA l amt T er mAB

t T er mAB t T er mA t T er mA s S ubst

appl y t t T er mB substt s T er mA

and the constructors of S ubst are

s S ubst t T er mA

none S ubst fs tg S ubst A

s S ubst s S ubst

s id S ubst s comps s S ubst

s S ubst e s S ubst e

s mons e S ubst s pr oj s e S ubst

Variables terms and substitutions will b enamed v t s resp ectively

Denition of normal terms

We will now dene the set of normal terms Simultaneously we dene the set of applicative

n

terms that is terms on the form appl y t t t where t is a variable or a constant and

n

t t are normal and the set of normal terms where a normal term of base type is an

n

applicative term and normal term of function type is l amt where t normal

NF T y pe C ontext Set

NF T y pe C ontext Set

with the constructors

v V ar A

nf c NF o nf v ar v NF A

t NF AB t NF A

nf appl y t t NF B

t NF B A NF o

nf o NF o nf l amt NF AB

It is easy to see that there are a direct injection from the normal terms to the ordinary terms

Here one would have liked a notion of subsets but this do es not exist in ALF yet

We will now dene a shift function on normal terms Roughly shift on a variable takes

n

v V ar A to v ar v V ar A A A

n

v ar V ar A V ar A shif t

shif t NF A NF A

shif t NF A NF A

In the denition b elow we will overload shift it should b e clear from the typing which is

which Notice in the last case of l am the crucial role of ext

shif tv ext v

shif tv ext e v ar shif tv e

shif tv ar A ext e v ar A

shif tv ar v ext e v ar shif tv e

shif tnf c e nf c

shif tnf v ar v e nf v ar shif t v ar v e

shif tnf appl y t t e nf appl y shif tt e shif tt e

shif tnf ot e nf oshif tt e

shif tnf l amt e nf l amshif tt ext e

We have

shif tshif tt e e shif tt tr anse e

and

shif tt ext t

Semantics

The semantics of a term of base type is a term on normal form for a term of function type it

is for any extension of the context to take a value in the bigger context to a value in the bigger

context This denition is inspired by Kripke semantics seeing contexts with the relation of

extension as p ossible worlds

V T y pe C ontext Set

V o NF o

V A B V A V B

We will name values by v and u b elow

We dene an environment in which a term will b e evaluated The environment asso ciates a

value for each variable in a context

E C ontext C ontext Set

E

E A E V A

Environments will b e named b elow

We dene a function that takes a value in to a value in an extension of the context

mon A T y pe V A V A

V

The function is dened by induction on the type

mon o t e shif tt e

V

mon AB f e e v V A f tr anse e v

V

In the second case we obtained f by pattern matching on the value that for the function

type is a

We have a corresp onding function for the environment dened by induction on the rst

context

mon E E

E

mon e tt

E

mon A e u mon e u

E E

In the second case we obtained u by pattern matching since the environment is of type

E A which is dened as a pro duct

We dene the pro jection of a context that takes out a part of the environment

pr oj E E

E

pr oj ext

E

pr oj exte u pr oj e

E E

pr oj exte u pr oj e u

E E

Now we are ready to dene the semantics of a variable term and substitution

V ar A E V A

V ar

T er mA E V A

T er m

S ubst E E

S ubst

We will only use b elow it should b e clear from the typing which is which

The semantics of a variable is its value in the environment The semantics of a substitution

is a new environment where we intuitivaly have that if ft t g is a substitution from

n

to A A and an environment of type E then we get the new environment

n

t t The semantics of a term should b e clear from the denition b elow

n

In the denitions b elow has the type E

v ar u u

v ar v u v

mont e t pr oj e

E

c nf onf c

v ar v v

l amt e v V A t mon e v

E

appl y t t t ext t

substt s ts

none tt

fs tg s t

s id

s comps s ss

s mons e spr oj e

E

s pr oj s e pr oj e s

E

We will now dene the co ding back function g et ter m that takes a value and returns a term

v al that takes an applicative term on normal form We will simultaneously dene a function g et

ter m gives back a term that is etaexpanded on a syntactical level to a value Intuitively g et

and g et v al gives back a value that is etaexpanded on a meta level

g et ter m A T y pe C ontext V A NF A

v al A T y pe C ontext NF A V A g et

Both are dened by induction on the type

g et ter m u u

o

g et v al t t

o

g et ter m f nf l amg et ter m A f ext ext

AB B

g et v al A nf v ar v ar

A

v al t e v V A g et v al g et

AB B

nf appl y shif tt e g et ter m v

A

We are now ready to dene the function that computes a term to its normal form For this

we dene the identity environment

id C ontext E

E

that for each variable in the context give its value which we compute with the g et v al function

ab ove

id tt

E

id A mon ext ext id

E E E

v al A nf v ar v ar g et

A

To compute the normal form

nf T er mA NF A

is now only to compute the semantics of the term in the identity environment and then co de

the result back

nf t g et ter m t id

A A E

Conclusions

We have dened a normalization function by structural induction using the pattern matching

of ALF I feel that using the pattern matching has b een essential for the practical p ossibility

to do this kind of pro ofs What I would have liked to have is a notion of subsets and pattern

matching inside an expression ie some kind of case statement Ovarloading of names would

have b een nice but not essential

Future work

We will dene a conversion on terms and show that a term converts to the injection of its

normal form We also want to show that if two terms converts then their semantical values

are extensionally equal and that their normal forms are identical thereby getting a decision

algorithm for conversion just check that their normal forms are identical

It might also b e intresting to change this pro of to use named variables

Acknowledgements

I want to thank Thierry Co quand for giving me the idea of this work and for patiently answering

all my questions

References

U Berger and H Schwichtenberg An inverse of the evaluation functional for typed

calculus Pro ceedings of LICS

Th Co quand and J Gallier A proof of strong normalization for the theory of construc

tions using a Kripkelike interpretation Pro ceedings of the rst workshop in Logical

Frameworks

Th Co quand Pattern Matching with Dependent Types In this pro ceedings

P Dyb jer An inversion principle for MartinLof s type theory Pro ceedings of the

Workshop on Programming Logic in Bastad May Programming Metho dology

Group Rep ort p

L Magnusson The new implementation of ALF In this pro ceedings

B Nordstrom K Petersson and J Smith Programming in MartinLofs Type Theory

An Introduction Oxford University Press

Virtual reduction

Vincent Danos Laurent Regnier Paris

Abstract

We present a reduction of graphs whose edges are lab elled by co ecients in the dynamical

algebra Lambda the socalled virtual reduction We show that the virtual reduction enjoys

the ChurchRosser prop erty We give a semantic of the virtual reduction by applying the

execution formula of Girard

We then apply the preceding results to the case of purenets and introduce the notion

of virtual cut We end by relating the virtual cut elimination pro cedure with the family

reduction of lambdaterms in the sense of Levy

Natural Semantics in Co q First exp eriments

DRAFT

Joelle Desp eyroux Andre Hirschowitz

INRIA SophiaAntipolis University of Nice

August

Abstract

In this pap er we discuss a p ossible implementation of a Natural Semantics of MiniMl

into the Co q system The aim of this exp eriment was to study to which p oint the Co q

theorem prover is well suited to p erform pro ofs in Natural Semantics To represent our

semantics we have used the LF enco ding of logics which do not always meets the Co q

requirements for denitions of inductive types We prop ose here a p ossible solution to that

problem which will b e developped in the nal version of the pap er

Introduction

In a generic programming environment such as Centaur BCD there is a need for a p owerful

theorem prover to b e used for describing and for reasoning on ob ject languages and programs

In the current version of Centaur the available theorem prover Theo Des is rstorder

and not p owerful enough for many standard tasks As b enchmarks let us ask for mechanical

pro ofs of b oth the sub ject reduction theorem for MiniMl and the translation from MiniMl

to cam A natural to ol to consider for such tasks is the programming language Elf Pfe

based on the logical framework LF AHM Indeed the implementation of mini ml in Elf has

b een carefully studied in MP where a corresp onding pro of of the sub ject reduction theorem

has b een given However this pro of relies on an induction principle which is dened at the

metalevel A natural to ol to consider then is the theorem prover Co q DFH based on the

Calculus of Constructions CoC enriched with inductively dened types Indeed on one hand

Co q fully encompasses LF and on the second hand it oers a p owerful notion of inductive type

hence it should b e able to provide for instance a fully mechanical pro of of the sub ject reduction

theorem for MiniMl In this context we raise three questions

Is co q p owerful enough to p erform for instance the b enchmarks mentioned ab ove

What could b e an ecient programming style for the implementation of natural semantics

in co q

Which to ols or facilities should b e coined and added to co q or build over it in order to

make it more suitable for semantics of programming languages more precisely to make it

available in Centaur as a privileged ecient and userfriendly theorem prover to b e used

for describing and for reasoning on languages and programs

In this pap er we rep ort on our rst attempt to derive under co q a fully mechanical pro of

of the sub ject reduction theorem for MiniMl

This attempt is based on an implementation of MiniMl directly translated from the one

given in LF in MP The main feature of this implementation is that the chosen syntax is

higher order

Let us describ e the outcome of this rst attempt in terms of the questions listed ab ove

We have pro duced under co q a fairly simple pro of of the sub ject reduction theorem for

MiniMl relying up on two sets of axioms The rst one expresses that equality for terms

of the ob ject language is of a syntactic nature The second one expresses the only if

part of our semantic denition in other words it inverts our denition We were not able

to prove these axioms b ecause the chosen higherorder syntax cannot b e dened as an

inductive type which deprives us the suitable induction principle and the corresp onding

match constructor Hence co q will b e p owerful enough for the ab ove mentioned goal when

we will solve the following puzzle inside co q we shall provide our higher order syntax

with some kind of induction principle over the structure of the terms and with a match

constructor and this raises three problems what is the right induction principle in

this case is not evident any match constructor will enlarge the syntax with new terms

which should b e excluded through an appropriate selection pro cess once designed the

induction principle the match constructor and the selection pro cess have to b e legitimated

and packed in a userfriendly way We prop ose b elow the basis of a unied solution for

this puzzle

As for programming style the main choice we have considered concerns syntax There

are clearly two dierent approaches higherorder syntax as we have exp erienced Here

the higherorder features of the ob ject language are directly implemented as such in the

metalanguage hence and this is the main advantage of this approach the semantic rules

are very simple The main drawback for this approach is that some of the various ob jects

of are not inductively dened in co qs sense we wish to dene for instance exp or type

While this do esnt aect the simplicity of semantic rules it aects seriously as explained

ab ove the way pro ofs concerning the ob ject language can b e built Our current conclusion

here is this for a user friendly study of languages describ ed by a higherorder syntax co q

at least need b oth an extension of the induction principle to some class to b e introduced

of weaklyinductive denitions and the automatic lazy generation of some standard

consequences of this stronger induction principle

rstorder syntax this is the opp osite choice Its main advantage is that it allows the

ob ject language to b e introduced as an inductive type so that we can express the semantics

through recursive denitions and build our pro ofs uniformly by recursion on the sub ject

Here the problem is no more with pro ofs but with the description of the semantics

The natural solution seems to b e through a suitable co ercion of rstorder terms once

introduced as an inductive type to higherorder Our conclusion here is the need for such

a generic co ercion We do not explore further this approach since the next seems simpler

in any resp ect

We prop ose a new intermediate approach which we call midd leorder syntax In rst

order syntax ob ject lambdaexpressions are of type say exp exp exp while in

higherorder syntax they are of type exp exp exp and this rules the type exp

out of inductive types Our intermediate solution here is to type ob ject lambdaexpressions

with ident exp exp In this approach the type exp is still inductive hence it

shares the advantage of the rstorder syntax with resp ect to pro ofs As for the description

of the semantics it still needs a generic co ercion to higher order but this co ercion is

much easier since bindings are already understo o d by middleorder syntax Indeed here

we only need to transform terms of type ident exp into the corresp onding terms of

type exp exp This is the basis of our solution for the ab ove mentioned puzzle

The solution sketched ab ove is far from reaching the current standards of userfriendliness

under Centaur Hence it seems necessary to build a toplevel over co q designed for the

ab ove mentioned tasks We now list some of the features which would b e welcome for this

toplevel

at rst we mention manmachine interface issues the toplevel should integrate cur

rent progress p erformed in our team on manmachine interface for theorem provers

pro ofs prettyprinted in english and search directed from this prettyprinted pro of

through the mouse

next the toplevel should accept higherorder syntax and generate the corresp onding

middleorder syntax together with the asso ciated induction principle match op erator

and selection pro cess The middleorder syntax and the selection pro cess should b e

hidden to the user

moreover for each syntactic denition a unicity package of rules should b e gener

ated expressing that equality for terms of the dened type is of a syntactic nature

nally for each denition an inverse package of rules should b e generated expressing

the only if part of the denition This program raises corresp onding theoretical

issuesnamely

generic translation of higherorder to middleorder

The rest of the pap er is organized as follows Section is devoted to our pro of of our sub ject

reduction theorem Section is devoted to middleorder syntax In section we develop the

discussion started ab ove on the planned toplevel

A rst exp eriment

The MiniMl language

MiniML CDDK consists in the purely applicative part of ML more precisely a simply

typed calculus with p olymorphism constants pro ducts conditionals and recursive function

denitions We consider here the slight variation of MiniMl dened in MP where patterns

are replaced with explicit pro jections

Simple programs in MiniML are for example in concrete syntax

let u xx

in u u

or the following simultaneous recursive denition

letrec even odd xif x then true else odd x

xif x then false else even x

in even

The abstract syntax of MiniMl is as follows identiers and naturals are predened sorts

sorts exp ident

subsorts exp ident

constructors

id identiers ident

number naturals exp

tr ue f al se exp

nul l f st snd exp exp

appl y ml pair exp exp exp

l ambda ident exp exp

l et l etr ec ident exp exp exp

if exp exp exp exp

Numerous descriptions of the semantics b oth static and dynamic semantics of MiniMl can

b e found in the litterature The type inference system of MiniMl has b een rst describ ed by

Damas and Milner DM In Har R Harp er consider several presentations of this type

system together with their enco ding in LF An implementation of b oth static and dynamic

semantics of MiniMl has b een given b oth in the rstorder language Typol in CDDK and

in the higherorder language Elf in MP

The MiniMl implementation in Elf

Since our Co q implementation is based on the Elf implementation we very briey review this

Elf implementation MP in this subsection The Co q implementation is describ ed in the next

subsection Both implementations will b e given in annex in the nal version of the pap er

Higherorder abstract syntax

The Elf implementation of MiniMl describ es the MiniMl language using higherorder ab

stract syntax The idea of this approach is to use metalevel variables to represent the ob ject

level variables The metalevel binder is then naturally used to represent the ob jectlevel

binding op erators This could seem nonnatural at rst sight but has decisive advantages The

user can use the metalevel application to implement substitutions The user can avoid the

problem of conversion that the metalanguage has solved for him once for all

The syntax of MiniML is implemented in Elf by the following higherorder abstract syntax

exp type

true exp

false exp

zero exp

succ exp exp

If exp exp exp exp

nul l exp

lam exp exp exp

app exp exp exp

mlpair exp exp exp

fst exp exp

snd exp exp

let exp exp exp exp

l etr ec exp exp exp exp exp

x exp exp exp

In the case of MiniMl we can mechanically translate a program from the MiniMl syntax

to the Elf syntax The two examples given ab ove will b ecome in the Elf implementation a

expression is denoted in Elf as

let lam xx uapp u u

and

letrec

odd lam x if x true app app snd even odd x even

odd x lam x if x false app app fst even

even odd

The type inference system in Elf

The evaluation rules in Elf

A MiniMl implementation in Co q

It is now well known Henk Barendregt GTS that the Edinburgh Logical Framework can b e

viewed as a subsystem of the Calculus of Constructions Since we shall use it in this subsection

the injection from Elf to Co q that is induced by this view The implementation let us call

we consider here is this natural translation from the Elf implementation into Co q except

maybe for b o olean and natural expressions All the prop ositions written in this subsection

should b e more formally stated and proved in the nal version of the pap er

Syntax

Let us rst translate the Elf syntax into Co q without changing it In the denition of the

constructor lam exp exp exp the rst o ccurrence of exp is negative Such kind of

type is not allowed in Co q as an inductive type We must dene the type exp by a list of

Parameters We obtain the following syntax from which we only give here the rst lines

Parameter exp Set

Parameter true exp

Parameter false exp

Parameter zero exp

Parameter succ exp exp

Parameter lam exp exp exp

Parameter app exp exp exp

The following informal prop osition states that this Co q implementation of the MiniMl

syntax is adequate with resp ect to the corresp onding Elf implementation given ab ove

Prop osition For all closed normal term t in Elf such that t exp we have

E lf

t exp For all closed normal term t in Co q such that t exp there exists a term

C oq C oq

t in Elf

with t t such that t exp

E lf

Now it seems more convenient to use the predened Co q inductive set bool and nat to

represent the MiniMl b o olean and natural expressions rather than redening them Here is

the implementation that we have chosen

Parameter exp Set

Parameter mlbool bool exp

Parameter mlnat nat exp

Parameter lam exp exp exp

Parameter app exp exp exp

The variation introduced is not a minor variation vThe term l am succ z er o for example

is an expression accepted by the rst syntax and refused by the second syntax On the contrary

induction on b o oleans andor on naturals is allowed by the second syntax and not allowed by

the rst syntax Another adequacy prop osition of the new syntax with resp ect to the original

language is necessary

The type inference system

MiniMl types are represented as rst order terms which are exactly the same terms as in the

Elf implementation

Inductive Set ml ty pe

tbool ml ty pe

j tnat ml ty pe

j ar r ow ml ty pe ml ty pe ml ty pe

j cr oss ml ty pe ml ty pe ml ty pe

Our typeinference rules of MiniMl only dier from the Elf version in the treatment of the

b o oleans and naturals The rules are as follows

Parameter ty pe exp ml ty pe Prop

Parameter ty pe bool e bool ty peml bool e tbool

nat e natty peml nat e tnat Parameter ty pe

Parameter ty pe I f e e e expt ml ty pe

ty pe e tbool ty pe e t ty pe e t ty pe I f e e e t

nul l ty pe nul l ar r ow tnat tbool Parameter ty pe

Parameter ty pe l am E exp expt t ml ty pe

x expty pe x t ty pe E x t

ty pe l am E ar r ow t t

app e e expt t ml ty pe Parameter ty pe

ty pe e ar r ow t t ty pe e t ty pe app e e t

Parameter ty pe ml pair e e expt t ml ty pe

ty pe e t ty pe e t ty pe ml pair e e cr oss t t

Parameter ty pe f st e expt t ml ty pe

ty pe e cr oss t t ty pe f st e t

snd e expt t ml ty pe Parameter ty pe

ty pe e cr oss t t ty pe snd e t

Parameter ty pe l et e expE exp expt t ml ty pe

ty pe e t

x expt ml ty pety pe e t

ty pe x t ty pe E x t

ty pe l et e E t

l etr ec E E exp expt t ml ty pe Parameter ty pe

ty pe f ix E t

x expt ml ty pety pe f ix E t

ty pe x t ty pe E x t

ty pe l etr ec E E t

Parameter ty pe f ix E exp expt ml ty pe

x expty pe x t ty pe E x t ty pe f ix E t

lam type let type letrec and type x b oth contain an o ccurrence of type in a Rules type

negative p osition that forbids us to dene the judgement type as an inductive type

Prop osition For all closed normal terms e and t in Elf such that e exp

E lf

and t ml ty pe we have ty pe e t ty pe e t

E lf E lf C oq

For all closed normal terms e and t in Co q such that e exp t ml ty pe

C oq C oq

and ty pe e t there exist two terms e and t in Elf such that e e t t

C oq

and ty pe e t

E lf

The evaluation rules in Co q

Here again our denitions of b oth the semantic values of MiniMl and the evaluation rules for

MiniMl only diers from the Elf denition on the b o oleans and naturals

Inductive Denition v al ue exp Prop

v al bool e bool v al ue ml bool e

nat e natv al ue ml nat e j v al

j v al nul l v al ue nul l

l am E exp expv al ue l am E j v al

j v al ml pair E E expv al ue E v al ue E v al ue ml pair E E

The evaluation rules for MiniMl are as follows

Inductive Denition ev al exp exp Prop

ev al bool e bool ev al ml bool eml bool e

nat e natev al ml nat e ml nat e j ev al

j ev al I f t e e e v exp

ev al e ml bool tr ue ev al e v ev al I f e e e v

j ev al I f f e e e v exp

ev al e ml bool f al se ev al e v ev al I f e e e v

nul l ev al nul l nul l j ev al

j ev al l am E exp expev al l am E l am E

app E exp expe e v v exp j ev al

ev al e l am E ev al e v ev al E v v ev al app e e v

j ev al app nul l t e e exp

ev al e nul l ev al e ml nat O ev al app e e ml bool tr ue

j ev al app nul l f e e expn nat

ev al e nul l ev al e ml nat S n ev al app e e ml bool f al se

j ev al ml pair e e v v exp

ev al e v ev al e v ev al ml pair e e ml pair v v

j ev al f st e v v exp

ev al e ml pair v v ev al f st e v

snd e v v exp j ev al

ev al e ml pair v v ev al snd e v

j ev al l et e v v expE exp exp

ev al e v ev al E v v ev al l et e E v

j ev al l etr ec v v expE E exp exp

ev al f ix E v ev al E v v ev al l etr ec E E v

j ev al f ix v expE exp exp

ev al E f ix E v ev al f ix E v

Prop osition For all closed normal terms e and v in Elf such that e exp

E lf

and v exp we have ev al e v ev al e v

E lf E lf C oq

For all closed normal terms e and v in Co q such that e exp v exp

C oq C oq

and ev al e v there exist two terms e and v in Elf such that e e v v

C oq

and ev al e v

E lf

Pro of of the sub ject reduction theorem

The Sub ject Reduction Theorem for our MiniMl example can b e stated as follows

Theorem e v expev al e v t ml ty pety pe e t ty pe v t

The complete pro of of the theorem is given in annexB It pro ceeds by induction on the

denition of eval It uses b oth the unicity axioms on exp presented later on in the section

toplevel and the inversion of the type denition presented as axioms in annexB

Comparaison with the Elf pro of

Middleorder implementation of miniml

Syntax

Our syntax uses the empty type for b ound variables

I nductiv e S et empty

This type has no value but it has an identity x empty x More generally it has a natural

morphism towards any Set

Denition init T S etempty T

T S etx empty T M atch x w ith

Further examples of functions related to the empty type are

Denition pr x empty x empty x

Denition pr x empty x empty x

Our middleorder syntax for the MiniMl language is as follows

Inductive Set mexp

ml bool bool mexp

jml nat nat mexp

jl am empty mexp mexp

japp mexp mexp mexp

jl et mexp empty mexp mexp

j

For instance the term l et u xx in u u is enco ded as

l et init mexp x empty app x x In order to express that our syntax is correct we need

the type denoted l ist t n of lists of length n of terms of a given type t together with the

corresp onding cons car and cdr op erators

Now our syntax is correct in the following sense there is a unique natural collection of

bijections bij n b etween l ist exp n exp and l ist empty n mexp This prop osition

would b e false for a l am op erator of type

l am id mexp mexp

This collection of bijections is natural in the sense that the following prop erties hold we only

give here only one of these prop erties

f l ist exp S n expbij n x l ist exp nl am y exp f cons y x

x l ist empty nl am y empty bij S n f cons y x

The bijection bij is the desired bijection b etween exp and mexp This is the rst instance

where in order to understand higherorder syntax we enlarge our scop e to terms dep ending on

a list of variables This feature is recurrent in our work

Co ercion

Thus the middleorder syntax is adequate but not suited for semantics In order to express

the semantics for the term for instance app l am u v it is desirable to have u b eing of

type mexp mexp For u of type empty mexp we would like to dene inside co q the

corresp onding coer u of type mexp mexp More generally we lo ok for a co q term coer

of type

n natl ist empty n mexp l ist mexp n mexp

We were not able to construct this term b ecause the Match op erator is not p owerful enough

Fortunately we were able to construct the inverse co ercion which is sucient for our purp oses

thanks to higherorder unication

Now we would like higherorder unication to op erate smo othly when asked for a solution

of the equation l ist empty n mexp coer X f namely we would like it to nd the

single natural solution the only one which do es not use more than f the Match constructor

For that the only way seems to dene a predicate restr which rules out the nonnatural solutions

The predicate r estr f means that f has no Match op erator except p ossibly in its subtrees of

type nat or b o ol

Semantics

We dene here the corresp onding type inference rules and evaluation rules of MiniMl using

the new middleorder syntax

Toplevel

We discuss here some features of the toplevel we plan to built over Co q

Unicity package Inverse package

Co q pro ofs in Natural Semantics seem to b e relatively short terms provided that two to ols are

given The rst to ol we need is the ability to generate some intuitive facts ab out an inductive

or not denition of a syntax in the case where the user asks for them The intuitive facts ab out

the exp syntax simply say that the type exp dene trees With the help of a Match on exp we

could easily prove those facts But since in our example exp is not an inductive denition we

must give them as axioms

Axiom uniq ml pair x y x y exphexp imlpair x y mlpair x y

hexp ix x hexp iy y

Axiom uniq ar r ow x y x y mltype hml ty peiarrow x y arrow x y

hml ty peix x hml ty peiy y

Axiom l am ml pair E exp exp x y exp hexp ilam E mlpair x y

ml pair e bool x y exp hexp imlbool e mlpair x y Axiom bool

Axiom nat ml pair e natx y exphexp imlnat e mlpair x y

ml pair x y exp hexp inul l mlpair x y Axiom nul l

The second to ol we need is the compilation of the inversion of a set of inference rules

declared as an inductive or not denition In the case of an inductive denition there is work

in progress in the Formel team at InriaRo cquencourt Samuel Boutin The simplest example

is the inversion of the v al ue judgment which reduces to the inversion of rule v al ml pair

inv ml pair e e expv al ue ml pair e e v al ue e v al ue e Theorem v al ue

As an example we give in Annex A a pro of of the ab ove inversion rule As another example

the inversion of the MiniMl type denition is given in AnnexB

Pro ofs in english

Prettyprint from Co q pro of terms into pro ofs written in english in a more conventional math

ematical style

As an example let us give a short pro of in Co q Given the previous semantic denitions we

can prove that the evaluation of a MiniMl expression returns a value

E V expev al E V v al ue V

The pro of pro ceeds by induction on the length of the pro of of ev al E V It uses b oth the

unicity and the inverse packages given as an example in the previous subsection

Goal EVexp eval E V value V

Induction

b o ol Intro Apply val

nat Intro Apply val

Trivial Trivial

Apply val null

Intro Apply val lam

Trivial

b o ol Intros Apply val

Intros Apply val b o ol

mlpairAssumptionAssumption Intros Apply val

Intros Apply pro j with value v Apply value inv mlpair Assumption

inv mlpair Assumption Intros Apply pro j with value v Apply value

Trivial

Save ml eval returns value

From higherorder to middleorder and the selection pro cess

Generalisation of the work done on the MiniMl example

Induction Match op erator

In the denition of the constructor lam exp exp exp the rst o ccurrence of exp is

negative Such kind of type is not allowed in Co q as an inductive type The reason for that is

that whenever the user dene an inductive type Co q generates an iteration op erator Match on

that type together with an induction principle for that type in a framework which do es not

naturally extend to that case

The problem concerning the Match function is that exp exp dene al l functions from exp

to exp including those that use a Match With the help of a Match function we could build a

nonnormalisable term or at least a term which has no counterpart in the mo del we have in

mind In the case of exp we could write for example an analogue of which was given to us

by Christine Paulin

d l amx exp match x w ith l am f f x

where d d rewrites to d d

The problem concerning the induction is that an induction principle is not derivable from

such denition at least in the usual sense A straightforward induction principle for exp might

b e written as

P exp P r op

a b exp P a P b P app a b

f exp exp a exp P a P f a P l am f

x exp P x

This principle can b e written in Co q but it seems dicult to use it in Co q b ecause of the

nondenotational lam case

We prop ose here a less readable but more usable principle This principle originates in the

remark that a MiniMl expression dep ends on n variables The principle is thus dened on an

expression dep ending on a list of expressions of length n denoted as exp n

n nat P expn exp P r op

n nat a b expn exp P n a P n b P n xapp a x b x

n nat f expn exp expn exp

P S n f P n y l am x f cons x y

x expn exp P x

We have discussed here the problem of induction on the type exp example The discussion

naturally extends to the case of a type representing a judgment

Conclusion

To implement our logical systems in the Calculus of Constructions we have chosen the enco ding

dened in the LF framework However as it is p ointed out in PMP we know that in some

cases as for example the cases from our MiniMl example or simply the I rule of rst order

logic

I A B termtrue A true B true A B

this enco ding cannot b e directly used in an inductive denition Despite that fact as in the Elf

implementation of MiniMl we would like to use this LF enco ding which seems very natural

to us

Our rst idea has b een to write a toplevel to Co q or an interface for Co q rather than

mo difying it The basis of this toplevel is a new programming style for syntax which we call

midd leorder syntax This style is suciently higherorder for handling bindings and never

theless denes ob ject syntaxes as inductive types The cost for that is that since the match

op erator enlarges the syntax with new terms which have to b e excluded we have to write an

appropriate selection pro cess We hop e this to b e hidden in the toplevel This idea will b e

developped in the nal version of the pap er

Another idea is to add a new op erator in the Co q language called a restrictive arrow that

we denote here Roughly sp eaking exp exp will denote those functions from exp to exp

that are only built from the constructors of exp Similarly true A true B will denote

those pro ofs that are only built from the constructors of tr ue There is work in progress on that

sub ject by Joelle Desp eyroux Chet Murphy and Frank Pfenning

In the future we would like to build pro ofs in Co q for example under Centaur An interface

for Co q is under development in our team Our aim is to write Natural Semantics denitions in

an extended Typol so as to translate them into Co q terms A natural continuation of this work

will b e to see pro ofs as pro of trees in Natural Semantics as well as pro of terms in the Calculus

of Constructions

Annex A Pro of of an inversion rule

We give here the pro of of the following theorem

Theorem v al ue inv ml pair e e expv al ue ml pair e e v al ue e v al ue e

In this pro of we follow the metho d suggested in the Co qs users manual We rst dene a

suitable constant Then we prove a general prop erty from which the desired inversion rules will

b e derivable as simple pro ofs or even just instanciations

Denition inv eeeexp h exp iemlpair e e value e value e

Goal eeeexp value e inv e e e

Induction

Intro Red Intro Absurd h exp imlb o ol emlpair e e

Apply b o ol mlpair Assumption

Intro Red Intro Absurd h exp imlnat emlpair e e

mlpair Assumption Apply nat

Red Intro

Absurd h exp inullmlpair e e

Apply null mlpair Assumption

Intro Red

Intro Absurd h exp ilam Emlpair e e

mlpair Assumption Assumption Apply lam

Intros Red Intro Cut h exp iEe h exp iEe

Intro Apply conj

Replace e with E Assumption

Apply pro j with h exp iEe Assumption

Replace e with E Assumption

Apply pro j with h exp iEe Assumption

mlpair Assumption Apply uniq

inv Save value

Goal eeexpvalue mlpair e evalue e value e

Intros Cut h exp imlpair e emlpair e e

Change inv mlpair e e e e

Apply value inv Assumption

Trivial

Save value inv mlpair

Annex B Pro of of the Sub ject Reduction Theorem

We rst give the inverse denition of type that we need for the pro of of our theorem The

listing of the pro of itself follows

inv bool e bool t ml ty pety pe ml bool e t hml ty peit tbool Axiom ty pe

Axiom ty pe inv bool e bool t ml ty pehml ty peit tbool ty pe ml bool e t

inv nat e natt ml ty pety pe ml nat e t hml ty peit tnat Axiom ty pe

Axiom ty pe inv I f e e e expt ml ty pety pe I f e e e t

ty pe etbool ty pe e t ty pe e t

Axiom ty pe inv nul l t ml ty pety pe nul l t hml ty peit ar r ow tnat tbool

inv l am E exp expt t ml ty pety pe l am E ar r ow t t Axiom ty pe

x expty pe x t ty pe E x t

Axiom ty pe inv l am E exp expt ml ty pety pe l am E t

hml ty peiE xt ml ty pe

hml ty peiE xt ml ty pehml ty peit ar r ow t t

inv app e e expt ml ty pety pe app e e t Axiom ty pe

hml ty peiE xt ml ty pety pe e ar r ow t t ty pe e t

Axiom ty pe inv ml pair e e expt t ml ty pety pe ml pair e e cr oss t t

ty pe e t ty pe e t

Axiom ty pe inv ml pair e e expt ml ty pety pe ml pair e e t

hml ty peiE xt ml ty pe

hml ty peiE xt ml ty pehml ty peit cr oss t t

inv f st e expt ml ty pety pe f st e t Axiom ty pe

hml ty peiE xt ml ty pety pe e cr oss t t

Axiom ty pe inv snd e expt ml ty pety pe snd e t

hml ty peiE xt ml ty pety pe e cr oss t t

Axiom ty pe inv l et e expE exp expt ml ty pety pe l et e E t

hml ty peiE xt ml ty pety pe e t

x expt ml ty pety pe e t ty pe x t

ty pe E x t

inv l etr ec E E exp expt ml ty pety pe l etr ec E E t Axiom ty pe

hml ty peiE xt ml ty pety pe f ix E t

x expt ml ty pety pe f ix E t ty pe x t

ty pe E x t

inv f ix E exp expt ml ty pety pe f ix E t Axiom ty pe

x expty pe x t ty pe E x t

Goal evexpeval e v tmltypetype e ttype v t

Induction

Trivial Trivial Do Intro Intros ve te ve te t tIf Apply te

Apply pro j with type e t Apply pro j with type e tb o ol

Apply type inv If Assumption

Do Intro Intros ve te ve te t tIf Apply te

Apply pro j with type e t Apply pro j with type e tb o ol

inv If Assumption Apply type

Trivial Trivial Do Intro Intros vlam tlam ve te vApp tApp t tapp Apply tApp

Cut h mltype iExtmltypetype e arrow t ttype e t

Intro Ext Elim Ext Intro t Intro tEtE Apply type inv lam with t

Apply tlam Apply pro j with type e t Assumption

Apply te Apply pro j with type e arrow t t Assumption

inv app Assumption Apply type

Do Intro Intro te Do Intro Intro tapp

Cut h mltype iExtmltypetype e arrow t ttype e t

inv b o ol Intro Ext Elim Ext Intro t Intro tee Apply type

Apply pro j with h mltype ittnat Apply uniq arrow Apply type inv null Apply te

inv app Assumption Apply pro j with type e t Assumption Apply type

Do Intro Intro te Do Intro Intro tapp

Cut h mltype iExtmltypetype e arrow t ttype e t

inv b o ol Intro Ext Elim Ext Intro t Intro tee Apply type

Apply pro j with h mltype ittnat Apply uniq arrow Apply type inv null Apply te

inv app Assumption Apply pro j with type e t Assumption Apply type

Do Intro Intros ve te ve te t tee

Cut h mltype iExtmltypeh mltype iExtmltypeh mltype itcross t t

Intro Ext Elim Ext Intro t Intro Ext Elim Ext Intro t Intro tc

mlpair Replace t with cross t t Apply type

inv mlpair Elim tc Apply tee Apply teApply pro j with type e tApply type

Apply teApply pro j with type e tApply type inv mlpair Elim tc Apply tee

inv mlpair with e e Assumption Apply type

Do Intro Intros ve te t tf Cut h mltype iExtmltypetype e cross t t

Intro Ext Elim Ext Intros t tec Apply pro j with type v t

inv mlpairApply teAssumption Apply type inv fst Assumption Apply type

Do Intro Intros ve te t ts Cut h mltype iExtmltypetype e cross t t

Intro Ext Elim Ext Intros t tec Apply pro j with type v t

Apply type inv mlpairApply teAssumption Apply type inv snd Assumption

Do Intro Intros ve te vApp tApp t tlet Apply tApp

Cut h mltype iExtmltypetype e t

vexptmltypetype e ttype v ttype E v t

Intro AElim AIntroIntro BApply BDo IntroApply teAssumption

inv let Assumption Apply type

Do Intro Intros vx tx vApp tApp t tletrec Apply tApp

Cut h mltype iExtmltypetype x E t

vexptmltypetype x E ttype v ttype E v t

Intro AElim AIntroIntro BApply BDo IntroApply txAssumption

inv letrec Assumption Apply type

inv x Assumption Do Intro Intros vApp tApp t tx Apply tApp Apply type

Save ml sub ject red

References

AHM A Avron F Honsell and A Mason Using typed calculus to implement formal

systems on a machine Technical Rep ort ECSLFCS Edinburgh University

Edinburgh July

BCD P Borras D Clement T Desp eyroux J Incerpi G Kahn B Lang and V Pascual

Centaur the system In Proceedings of the rd Symp on Software Development

Environments November Boston USA also available as a Technical

Rep ort InriaSophiaAntipolis France December

CDDK D Clement J Desp eyroux Th Desp eyroux and G Kahn A simple applicative

language Miniml In Proceedings of the Symposium on Lisp and Functional Pro

gramming

Des J Desp eyroux Theo an interactive pro of development system Scandinavian Jour

nal on Computer Science and Numerical Analysis BIT special issue on Program

ming Logic containing the Proceedings of the Workshop on Programming Logic

Bastad Sweden May a preliminary version is available

as a Research Rep ort RR InriaSophiaAntipolis France August

DFH G Dowek A Felty H Herb elin G Huet Ch Paulin and B Werner The co q

pro of assistant users guide version Technical Rep ort Inria Ro cquencourt

France December

DM L Damas and R Milner Principal typeschemes for functional programs In Pro

ceedings of the POPL ACM Conference on Principles of Programming Languages

pages

Har R Harp er Systems of p olymorphic type assignment in LF Technical Rep ort CMU

CS Carnegie Mellon University Pittsburgh Pennsylvania June

MP S Michaylov and F Pfenning Natural semantics and some of its metatheory in elf

In Lars Hallnas editor Proceedings of the Second Workshop on Extentions of Logic

Programming SpringerVerlag LNCS also available as a Technical Rep ort

MPII MaxPlanckInstitute for Computer ScienceSaarbrucken Germany

August

Pfe F Pfenning Elf A language for logic denition and veried metaprogramming In

Proceedings of the fourth ACMIEEE Symp on Logic In Computer Science Asilo

mar California USA June

PMP Ch PaulinMohring and F Pfenning Inductively dened types in the calculus of

constructions In Proceedings of the Fith International Conf Mathematical Foun

dations of Programming Semantics New Orleans Luisiana USA pages

Universes and a General Notion of Simultaneous

InductiveRecursive Denition in Type Theory

Draft

Peter Dyb jer

Chalmers University of Technology

August

Abstract

In MartinLofs type theory we may dene new sets and families of sets inductively

and new functions by recursion on the way the elements of these sets are generated The

schema for such denitions that we considered b efore includes all the standard set formers

of type theory with the exception of universes

Here we give an extended schema which also covers universes a la Tarski These consist

of simultaneous inductive denitions of sets of co des for small sets and recursive denitions

of deco ding functions This extension is a small mo dication of the old schema and includes

a general formulation of the notion of a simultaneous inductiverecursive denition

There are several interesting applications of this extension Here we show how to obtain

an external universe hierarchy where each level in the hierarchy faithfully reects the previ

ous level We also show how to obtain the universe constructions of Grior and Palmgren

These include an internal unfaithful universe hierarchy and a sup er universe

Other examples are the construction of Frege structures in type theory and various

constructions relevant to the formalization of type theory inside type theory

Introduction

The rst universe a la Tarski consists of the simultaneous inductive denition of the set U

of co des for small sets and the recursive denitions of the deco ding function T We have the

following rules of formation using MartinLofs term

U set

T U set

We also have introduction and equality rules for constructors reecting and Eq formation

u U u x T uU U

T u u T u xT u x

eq u U b b T uU

p eterdcschalmersse

T eq u b b Eq T u b b

This denition do es not t the schema for inductive and recursive denition in Dyb jer

since T app ears in the introduction rules for U Note that it even app ears negatively in the

rule for

In spite of this simultaneity we can argue that it is a predicative denition For example

the rules for stipulate the following way of constructing new elements of U

At a certain stage we may have constructed the element u Since T is dened by U

recursion we immediately construct the set T u Hence it is p ossible to construct a function

u with domain T u and range the presently constructed elements of U Hence it makes

sense to construct an element u u Moreover we can dene the T u u in terms of

the already constructed sets T u and T u x for x T u

For similar reasons we shall accept a certain general notion of simultaneous inductive

recursive denition The formulation of this notion will app ear as a minor mo dication of

the schema for inductive and recursive denitions in type theory which was presented in Dyb jer

The main change is that we allow the simultaneous inductive denition of a family of sets

P and the P recursive denition of a function f

The idea to consider such a general notion was inspired by Nax Mendlers pap er on the

categorytheoretic semantics of universes in type theory

Note that this generalization is only p ossible if we adopt a schematic approach to recursive

denitions since elimination rules only apply to recursive denitions on a previously dened

set For example T is dened by a recursive schema and not in terms of U elimination

Moreover it is also essential that we do not require functions dened by recursion to take

their values in a particular set as in the traditional elimination rules but allow them to take

their values in an arbitrary type For example the values may b e in the type of sets itself so

we have recursively dened families of sets

So the conceptual priority of certain concepts have b een reversed as compared to the stan

dard formulations of MartinLof

elimination rules recursion schemata

typevalued recursion universes

MartinLof has previously considered a formulation of type theory in terms of recursion

schemata Other arguments for viewing recursive denitions schematically and allowing more

general forms of pattern matching can b e found in Thierry Co quands pap er in this volume

The idea to obtain typevalued recursion in MartinLofs type theory by formulating typed

valued large elimination rules rather than by using the ordinary elimination rules in con

junction with universes is due to Bengt Nordstrom Smith gave an interpretation of a theory

with such large elimination rules in a theory with ordinary elimination rules and universes

Schema for simultaneous inductiverecursive denitions

The reader is referred to Dyb jer for a presentation of the old schema which uses Martin

Lofs theory of logical types Alternative presentations can b e found in Dyb jer of a schema

for MartinLofs type theory which do es not use the theory of logical types and Co quand and

Paulin of a schema for the Calculus of Constructions I have tried to use similar notation

in order to highlight the similarity b etween the new and old schemas In particular there is the

notation a meaning that a is a sequence of ob jects tting the sequence relative context

telescop e of dep endent types The notion of an stype setlike type is also essential it is a

type which is built up by the function type construction from base types which are sets The

reason for requiring that certain types o ccurring in the schema are stypes rather than sets is

to cover MartinLofs preface rules for

I present the case with one inductive and one recursive denition simultaneously There are

obvious generalizations to the case with several such simultaneous denitions Furthermore I

assume that there are no parameters but the discussion of these in Dyb jer can b e extended

in a straightforward way

A denition is always relative to a theory containing the rules for previously dened concepts

Thus the requirements on the dierent parts of the denitions p q b elow are always

judgements with resp ect to that theory

Formation rules

Consider introducing a family of sets P together with a function f dened by P recursion

P a set

f a c P a a

Here we require that is a sequence of stypes and a type a

Introduction rules

A premise of an introduction rule is either nonrecursive or recursive

A nonrecursive premise has the form

b

where stype dep ending on the previous premises see b elow

A recursive premise has the form

u x P px

where is a sequence of stypes and px x dep ending on the previous premises

see b elow If is empty the premise is ordinary and otherwise generalized as in ordinary

and generalized induction

The type of the conclusion of the introduction rule has the form

P q

where q dep ending on the previous premises see b elow

We write b u etc to indicate explicitly the dep endence on previous

nonrecursive premise b and recursive premises u x P p x This notation is not

intended to indicate that nonrecursive premises always come b efore recursive premises

We require that

b u b x f p x u x

where b v stype b v x p x Note that the context

of is obtained from the context list of previous premises of by replacing each recursive

premise of the form u x P p x by v x p x

The dep endence of p and q on previous premises are obtained in the same way as for

Equality rules for the simultaneously dened function

Let intro b e a constructor constant and b indicate a typical nonrecursive premise and

u x P px indicate a typical nonrecursive premise of the corresp onding introduction

rule The form of the equality rule for f and intro is

f q intro b u e b xf px ux

where e b v q b v x px

The analogue of universe elimination

Universe elimination expresses denition by U recursion after U and T are dened

We express this schematically for the general case Let P and f b e dened by a simultaneous

inductiverecursive denition as ab ove We may then dene a new function

f a c P a a c

by P recursion after P and f have b een dened Here we require that a c a c P a

The equality rule has the form

f q intro b u e b u xf px ux

where

e b u v q intro b u

b u x P px v x px ux

Note that in contrast to and e in the schema for f dep ends on c as well as on a and

e on u as well as on v in the schema for f

A simple example lists with distinct elements

The following example illustrates how the schema can b e used It is a simplication of an

example of a simultaneous inductiverecursive denition used by Catarina Co quand in her work

in progress on formalizing the typed calculus in type theory She dened the notion of a

correct context and the notion of a fresh variable in this way

Let

A set

AAset

b e parameters to this denition A is the set from which the elements of the list are taken and

is an arbitrary relation which we interpret as distinctness

We then simultaneously dene the set Dlist of lists with distinct elements and the relation

Fresh which expresses that a new element is distinct from all elements in a list

Formation rules

Dlist set

Fresh c Dlist a Aset

We see that this is an instance of the schema with empty and a Aset

Introduction and equality rules

nil Dlist

Fresh nil a

cons b Au Dlist b Fresh u bDlist

Fresh cons b u aba Fresh u a

Let us describ e in detail how to obtain the rule for cons from the schema

The rst premise b A is nonrecursive with A which is a set and hence an stype

The second premise is recursive but ordinary so there is nothing to check The third premise

is nonrecursive with

b u Fresh u b b F r eshu

where b v v b which is a set and hence an stype in the context b A v a Aset Note

that here we have a dep endency of a nonrecursive premise on the previous b oth nonrecursive

and recursive premises

The conclusion has the right form since is empty there is nothing more to check

A function dened by the analogue of universe elimination

We can dene a function which computes the length of a Dlist by using an instance of the

general schema corresp onding to universe elimination

length c Dlist N

Here N

The equality rules are

length nil

length cons b u b slength u

which easily can b e seen to b e instances of the general schema

Universes a la Tarski faithful reection

The rst universe

We return to the rst universe and show how it is obtained by instantiating the schema The

formation rules are

U set

T U set

Here is empty and set

The introduction rule reecting formation is

u U u x T uU U

It has a rst ordinary recursive premise and a second generalized recursive premise with

T u Thus we have an example where a recursive premise dep ends on an earlier recursive

premise

The corresp onding equality rule is

T u u T u xT u x

The introduction rule reecting Eq formation is

eq u U b b T uU

It has a rst ordinary recursive premise and a second and third nonrecursive premise with

T u Thus we have another example when a nonrecursive premise dep ends on an earlier

recursive premise

The corresp onding equality rule is

T eq u b b Eq T u b b

The second universe

The formation rules are

U set

T U set

Here is empty and set

There are analogous rules for the constructors and eq to those of the rst universe for

reecting and Eq formation resp ectively There is also a rule reecting U formation

u U

It has no premise

The corresp onding equality rule is

T u U

Since T is dened by U recursion it is natural to reect it as a function

t U U

which is dened by U recursion

t u u t u xt u x

t eq u b b eq t u b b

This denition comes after the denition of U and T so it is an instance of the schema

corresp onding to universeelimination

This is the rst version of the universe hierarchy in the pap er on Transnite hierarchies

of universes in Palmgren since t is not a constructor Palmgren motivates the recursion

equations for t by the principle that T a T b should imply that a b which is also the

reason for calling it faithful reection

Higher universes

We can continue in an analogous way and dene U and T U and T etc Thus for each set A

denable in a theory T there is an extension of T which contains a universe U which contains

n

a co de for A So we get an external universe hierarchy

Unfaithful reection and its internalization

The second universe

The second version of the second universe in Palmgren treats the co de

t U U

for T as a constructor instead of a recursively dened function Hence we need an extra equality

rule for T

T t b T b

This makes the reection unfaithful since in this case dierent co des may denote the same set

The next universe construction

Grior and Palmgren showed that the second version of the construction of U from U

n n

can b e internalized We introduce the new set formers Nextu and Nextt such that U

sn

Nextu U T and T Nextt U T This construction also falls under the schema in

n n sn n n

section

Let

U set

T U set

b e parameters of the denition we need to construct a universe on top of an arbitrary family

U T

Formation and typing

Nextu set

Nextt Nextu set

Introduction and equality rules corresp ond to those of the rst universe but we also need

to reect the co de set U as

Nextu

Nextt U

and the deco ding function T as

t b U Nextu

Nextt tb T b

The sup er universe

The sup er universe in Palmgren this idea was also originally presented in unpublished

work together with Ed Grior is obtained by reecting the nextuniverse construction viewed

as the set formers

Nextu U set T U set set

Nextt U set T U set Nextu U T set

as well This sup er universe also falls under the schema in section

Formation and typing rules

U set

T U set

Introduction and equality rules corresp ond to those for the rst universe but we also need

to reect the rst universe U

u U

T u U

and the nextuniverse construction Nextu

nextu u U u x T uU U

T nextuu u Nextu T u xT u x

as constructors for U

As b efore there is a choice as to reect T and Nextt either faithfully as recursively dened

functions or unfaithfully as constructors The details are similar to the situation for U presented

ab ove

Other applications

Other notions which seem to b e obtainable by a simultaneous inductiverecursive denition are

the following

The propositions and truths in a Frege structure In Dyb jer this metho d is used for

constructing a Frege structure inside MartinLofs type theory

The computability predicates for types and terms in a theory with dep endent types

The generalization of logical relations to the case of dep endent types

The details of the two latter constructions are not yet developed

References

P Aczel Frege Structures and the Notions of Proposition Truth and Set pages in

The Kleene Volume NorthHolland

T Co quand Pattern matching with dep endent types This volume

T Co quand An Algorithm for Testing Conversion in Type Theory pages in

Logical Frameworks Cambridge University Press

T Co quand and C Paulin Inductively dened types preliminary version In LNCS

COLOG International Conference on Computer Logic SpringerVerlag

P Dyb jer An inversion principle for MartinLofs type theory In Proceedings of the

Workshop on Programming Logic Programming Metho dology Group Rep ort Chalmers

University of Technology and University of Goteborg May

P Dyb jer Inductive sets and families in MartinLofs Type Theory and their settheoretic

semantics pages in Logical Frameworks Cambridge University Press

P Dyb jer Constructing a Frege structure in predicative type theory Draft pap er

P MartinLof An intuitionistic theory of types Unpublished rep ort

P MartinLof An intuitionistic theory of types Predicative part In Logic Col loquium

pages NorthHolland

P MartinLof Constructive mathematics and computer programming In Logic Method

ology and Philosophy of Science VI pages NorthHolland

P MartinLof Intuitionistic Type Theory Bibliop olis

P F Mendler Predicative type universes and primitive recursion In Proceedings Sixth

Annual Synposium on Logic in Computer Science IEEE Computer So ciety Press

E Palmgren On Fixed Point Operators Inductive Denitions and Universes in Martin

Lofs Type Theory PhD thesis Uppsala University

J Smith Prop ositional functions and families of types Notre Dame Journal of Formal

Logic

Formalizing Prop erties of WellQuasi Ordered Sets in ALF

DRAFT

Daniel Fridlender

University of Goteborg and Chalmers University of Technology

June

Abstract

To prove termination of an algorithm taken from p olynomial theory some general

prop erties of ordered sets must b e proved With the aim of deriving this algorithm in ALF

constructive pro ofs of these prop erties and their formalization in ALF are presented

Introduction

This pap er presents some preliminary work on the line of completely formalizing in ALF a

constructive pro of of a prop osition taken from p olynomial ideal theory In the classical pro of of

this prop osition a classical argument is used to prove the unexistence of innite sequences of

tuples of natural numbers

m m

t t t t

n n

such that

j

i

i j N i j k nt t

k k

Next section explains the prop osition taken from p olynomial ideal theory and the role this clas

sical argument plays in the classical pro of The following section formulates ways of expressing

the unexistence of such innite sequences in a constructive setting After that the formalization

of two constructive arguments is describ ed To conclude we discuss some problems that arose

with the formalization and show how they may b e solved with the patternmatching facility of

ALF describ ed in

Motivation

The prop osition taken from p olynomial ideal theory states the existence of Grobner bases for

nitely generated p olynomial ideals over discrete elds More precisely the prop osition says

that

given a eld K with decidable equality a natural number n an admissible order

n

over N and a nitely generated p olynomial ideal I there exist p olynomials

g g such that fg g g is a Grobner basis of I with resp ect to

s s

fritocschalmersse

The eld K is the set from which the co ecients of the p olynomials are taken The number n is

n

the number of indeterminates for the p olynomials and so N is the set of exp onents Given an

n

exp onent e N and i n e is the ith co ordinate of e We dene de e e The

i n

notions of admissible order and Grobner basis involved in the prop osition are introduced b elow

After that we briey explain how the need of proving the unexistence of innite sequences

satisfying arises

The reader is referred to and for detailed descriptions of the prop osition and to

and for its applications

Admissible orders

When dealing with p olynomials with only one indeterminate the way to write them is very nat

ural we use the usual order over natural numbers and we write the monomials in decreasing

order of their exp onents It might b e irrelevant when we just want to write them but it turns

out to b e imp ortant when we want to write a pro cedure to divide a p olynomial by another

b ecause it grants the pro cedure to terminate

There is not such a natural way or may b e there are many when we sp eak of p olynomials

with many indeterminates For instance the lexicographical order b etween tuples

e f j ne f i j e f

l j j i i

or the degree lexicographical order

e f de df de df e f

d l

or the reverse order

e f de df

r

de df j ne f i j ne f

j j i i

are suitable ways of determining this way of writing p olynomials By suitable we mean

that pro cedures like the division will terminate

We precise the notion of b eing suitable by dening admissible orders A total order

n

over N is admissible i

n

e N e

n n n

e f g N e f e g f g

n

where is the comp onentwise addition

Grobner bases

Consider the case of p olynomials with only one indeterminate To compute the remainder of

n n

the division of f by g a X a X a where a is a nonzero element in the eld

n n n

K we can consider g as a rewriting rule

n n

a X a a X

n n

which transforms p olynomials of the form

mn m

f p b X b X q

mn m

into

b b

mn mn

mn m

f p b a X b a X q

mn n m

a a

n n

where

mno mn

p b X b X

mno mn

m

q b X b

m

The usual algorithm to compute the remainder r of the division of f by g consists of a sequence

of such transformations It can b e seen that any sequence f f such that

t

f f

i t f is transformed to f and

i i

f can not b e further transformed

t

pro duces the remainder of the division of f by g which is f

t

Once we have an admissible order this can b e generalized to the case of n indeterminates

Given a nonzero p olynomial g we dene e g to b e the greatest exp onent of g with resp ect

e g

to c g the co ecient with which it app ears in g and m g the monomial c g X

e

e e

1

n

We can lo ok at g as a rewriting rule X Notice that we use the notation cX for cX

n

m g m g g

n

If a p olynomial f has no monomial m with exp onent e such that e g e we say that f

e

is in normal form with respect to g and In the case that f has a monomial cX such that

n

e g e we say that f reduces to f by g and using the monomial of exponent e and we

eg

f where write it f

e

cX

g f f

m g

n

c

e e g

X g f

c g

n

where is the comp onentwise subtraction

G

Now we can think of having a set of p olynomials or rules G fg g g By f f

s

eg

n

f and we say that f we mean that there is some e N and some g G such that f

reduces to f by G and The p olynomial f is in normal form with respect to G and if for

all g G it is in normal form with resp ect to g and

G

Again we can think of several steps of as a division of a p olynomial f by a set of

p olynomials G The fact of b eing an admissible order grants the pro cedure to terminate But

the dierence is that now there is not such a unique remainder b ecause in each step we have

G

many p ossible rules to apply and in general is not conuent A set G of p olynomials is

G

called a Grobner basis with respect to i is conuent

There are many other characterizations of Grobner bases see and

Notice that the notion of b eing a Grobner basis dep ends on the admissible order and so a

set may not b e a Grobner basis with resp ect to an admissible order in spite of b eing a Grobner

basis with resp ect to another admissible order

We say that G is a Grobner basis of an ideal I with respect to i it is a Grobner basis

with resp ect to and the ideal generated by G is I

Classical Pro of

The classical pro of of the prop osition see and and consists of

A pro cedure that computes a sequence g g of p olynomials

s

A pro of of absurdity from the assumption that the sequence of p olynomials computed by

the pro cedure is innite that is a classical pro of of termination

n n

To lo ok at the classical pro of with more detail we dene the relation over N by

n

e f i ne f

i i

With this the classical pro of consists of

A pro cedure that computes a sequence g g of nonzero p olynomials with greatest

s

s

exp onents e e ie e e g such that

i i

i n j

i j N i j e e

A pro of of absurdity from the assumption that an innite sequence of exp onents satisfy

ing exists

The second p oint which is the classical pro of of termination states exactly the unexistence

of an innite sequence satisfying b ecause of the equivalence b etween and A sequence

s

e e nite or innite satisfying is called a bad sequence

Thus in what follows we will formalize constructive pro ofs of the unexistence of innite

bad sequences

Constructive Formulations

Two approaches have b een taken to express termination in a constructive way

s

The rst one was inspired in the fact that the innite sequence e e is bad i the

s

nite sequences e e e are all bad sequences Thus instead of sp eaking of

the unexistence of innite bad sequences we can sp eak of the wellfoundedness of the relation

@ on nite bad sequences dened by

s s i i

1 2

e e @ f f s s i s e f

The second approach is dual to this one and is essentially the one chosen in A sequence

s i n j

e e is good i there exist i j N such that i j and e e The decidability of

n

implies that the sets B and G of all the nite bad and good sequences resp ectively form a

partition of the set of nite sequences Thus instead of sp eaking of the unexistence of innite

bad sequences we can sp eak of the existence of a good initial segment of any innite sequence

We follow expressing this universal quantication over innite sequences by means of bar

induction

Thus given a set A and a relation on it we will have two dierent denitions of the

predicate wel l According to the rst one is wel l i the relation @ dened by

a a @ b b n m i ma b

n m i i

1

The prop erties we are interested in hold for any wel l relation This is why we dene the notion of wel l

instead of the more known notion of wel l quasiorder suggested by the title of this pap er

is wellfounded on the set of nite bad sequences of elements of A According to the second

one is wel l i the predicate to be good on nite sequences of elements of A is a bar

In b oth approaches the strategy taken was to prove as a lemma that if and are wel l

A B

on A and B resp ectively so is on A B where

AB

a b c d a c b d

AB A B

This together with a pro of that the usual order on natural numbers is wel l will give a pro of

n n

that is wel l on N and by induction that is wel l on N for any natural number n

n

Thus in spite of b eing interested only in the relation we proved the lemmas in a more

general level involving any relation on any set

Formalizations

The formalizetions were done in ALF see The new features for making denitions in

contexts were used extensively We briey show the syntax for dealing with contexts and

substitutions

To give a name to a context

name context

To make denitions in a context we show as an example the denition of tsil lists in reverse

order where the context is ASet

tsil Set A Set

tsil A Set

tsil Atsil A Set

tsilrec P tsilSet

P

l tsil a A PlPla

l tsilPl A Set

tsilrecP d e d

tsilrecP d e la el a tsilrecP d e l

Substitutions can also b e given a name

name fx t x t g C C

n n

where the context C contains a typing for x x and the free variables in t t are

n n

typed in the context C The syntax of the application of a substitution to a term t is tf g

In the denitions that follow we use contexts to represent the structure we work with a

relation on a set

First Approach

With the denition of tsil ab ove we say that an order on a set A is wel l i the relation @

dened by

l @ k a Al k a

is wellfounded on the subset of the bad tsils Thus the denition of wellfoundedness must b e

dened not just for a relation but for a relation on a subset

In the pro of that is wel l on A B provided that and are wel l on A and B

AB A B

resp ectively we followed where this result is proved for wel l quasiorders wel l relations that

are quasiorders The main lemma in is that is wel l on A i for all a A its restriction

is wel l on Aa which is dened there as a subset of A

These arguments led us to dene relations with a context having the relation itself the set

on which it is dened and the subset on which the b ehavior of the relation is interesting

REL A Set As ASet A ASet

We dene for a relation to b e wellfounded as it is frequently done in constructive mathe

matics We dene the accessible part of a set by a relation slightly mo died here to consider

the case of a relation on a subset

acc ASet REL

acc a A Asa b A Asb b aaccbacca REL

I

acc P a A accaSet

E

a A

as Asa

q b A Asb b aaccb

b A bs Asb r b aPb qb bs rPa acc a as q

I

a A

p accaPa p REL

acc P d a acc a as q da as q b bs racc P d b qb bs r

E I E

Finally a relation is wellfounded if all the elements of the subset are in the accessible part

wf a AAsa acca Set REL

We informally said that a relation is wel l i the relation @ dened ab ove is wellfounded

on the subset of bad tsils

well wffA tsil As bad @g Set REL

The set tsil was already dened To dene the subset or predicate bad a more elementary

notion seems to b e necessary the one of b eing a bad element for a tsil Given a relation on

A a tsil a a and a A a is a bad element for a a i

s s

i sa a

i

where is the reexive closure of and not AA SetSet

Two p ossible denitions of bad element have b een analized by an inductive denition or

by an implicit denition We have chosen the latter b ecause the former though b eing more

elegant and clear seems not to b e strong enough to prove some prop erties Some comments on

this are presented in the last part of this pap er

badelem tsil ASet REL

badelem a Asa

badelemlb a badeleml a b a

The same arguments led us to use implicit denitions to dene bad and @

bad tsilSet REL

bad

badla badl badeleml a

@ tsil tsilSet REL

@ l

lb @ l l l

tsil

In given a relation on A and a nite sequence a a the subset of A Aa a

n s

is dened by

Aa a fa Aji sa ag

s i

The main lemma there is that is wel l on A i for all a A it is wel l on Aa This is stated

in ALF with two lemmas

lemma well l tsilwellfAs badelemlg REL

lemma a AwellfAs badelemagwell REL

b eing lemma a more general statement than the only if part of the main lemma

What follows presents a formalization of the statements proved in Lemma states

that if a relation is wel l on a subset it is also wel l on a subset of it lemma that if a relation

is wel l on two subsets it is well on their union

lemma Bs ASet a A BsaAsa wellwellfAs Bsg REL

lemma Bs ASet

well

wellfAs BsgwellfAs aAsa Bsag REL

The theorem saying that if is a decidable relation wel l on A and is wel l on B

AB

is wel l on A B

theorem a b Aa b a b well well wellf g REL REL

B B

where the substitution is

fA A B

As pAsfstp Bssndp

p q fstp sndp fstq sndqg REL REL REL

AB B

and

REL B Set Bs BSet B BSet

B

well wellfA B As Bs g Set REL

B B

a b c da c b d

AB B

a c b d

A

a c b d A B A BSet REL REL

B

The formal pro of follows the arguments in The formalization is not dicult but has

many details that make it lab orious

Second Approach

Contrary to what happ ened in the rst approach now there is no need to consider subsets The

notion of wel l is now dened as a prop erty that the whole set of tsils has to satisfy which is

that the predicate good is a bar Thus the structure we need is represented by the context

REL A Set A ASet

We dene the dual notion to bad to be good which uses a previous notion of b eing a good

element Given a relation on A a tsil a a and a A a is a good element for a a

s s

i

i sa a

i

This time we chose an inductive denition b ecause at the time this pro of was done the new

facilities with patternmatching were already under development and they solved the weakness

of this denition

goodelem tsil ASet REL

goodelem l tsil a b A a bgoodelemla b REL

I

goodelem l tsil a b A goodeleml bgoodelemla b REL

I

goodelem b A

E

P l tsil goodeleml bSet

l tsil a A r a bPla goodelem l a b r

I

l tsil

a A

g goodeleml b

Pl gPla goodelem l a b g

I

l tsil

g goodeleml bPl g REL

goodelem b P d e la goodelem l a b r dl a r

E I

goodelem b P d e la goodelem l a b g el a g goodelem b P d e l g

E I E

The same argument led us to use inductive denitions for the predicate good

good tsilSet REL

good l tsil a A goodeleml agoodla REL

I

good l tsil a A goodlgoodla REL

I

good P l tsil goodlSet

E

l tsil a A g goodeleml aPla good l a g

I

l tsil a A g goodl Pl gPla good l a g

I

l tsil

g goodlPl g REL

good P d e la good l a g dl a g

E I

good P d e la good l a g el a g good P d e l g

E I E

With this approach we express the unexistence of innite bad sequences by saying that every

innite sequence has an initial segment which is good Following we express this universal

quentication over innite sequences through the notion of being a bar We say that a predicate

P on tsils bars a tsil l either when Pl holds or when for all a in A it bars la For an analysis

of bar induction as a constructive principle we refer to

This is formalized in ALF by the inductive denition

bar tsilSet tsilSet A Set

bar P tsilSet l tsil PlbarP l A Set

I

bar P tsilSet l tsil a AbarP labarP l A Set

I

bar P tsilSet

E

Q l tsil barP lSet

l tsil p PlQl bar P l p

I

l tsil

q a AbarP la

a AQla qaQl bar P l q

I

l tsil

p barP lQl p A Set

bar P Q d e l bar P l p dl p

E I

bar P Q d e l bar P l p el p abar P Q d e la pa

E I E

With this we say that a relation is wel l when good bars the empty tsil

well bargood REL

The pro of that if two relation and are wel l on A and B resp ectively so is their pro duct on

A B pro ceeds by dening a ary predicate P whose arguments are tsils of elements of A B

and A B resp ectively Informally we dene P by

P a a b b c d c d

n m l l

g ooda a i nj l a c

n i j

g oodf gb b i mj l b d

B m i j

g oodf gc d c d

l l

where the denition of and are the intuitive ones

B

With this what is proved is that if and are wel l on A and B resp ectively P is a

bar on the sequences of pairs What remains to prove is that g ood do es not hold

Some Comments on the Formalizations

In b oth approaches some inductive denitions seemed to b e to o weak for our purp oses In the

rst one an inductive denition of bad element would not allow us to prove a b from the

fact of b eing b a bad element for a sequence whose last element is a which is intuitive from

the informal denition of b eing a bad element The diculty comes from the imp ossibility of

dening the function last on tsils or head on lists An analogous problem arises in the second

approach in which an inductive denition of good is not strong enough to prove that the empty

tsil is not good

In b oth problems the diculty comes from having to consider in the pro ofs while using

the elimination rule of the inductive denition impossible cases The patternmatching feature

presented in eliminates from the case analysis these imp ossible cases

References

Bruno Buchberger Grobner Bases An Algorithmic Method in Polynomial Ideal Theory In

NKBose editor Multidimensional Systems Theory pages DReidel Publishing

Company DordrechtBostonLancaster

Bruno Buchberger Applications of Grobner Bases in Nonlinear Computational Geometry

In Pro c Workshop on Scientic Software IMA Minneap olis USA Springer

Bruno Buchberger Ein algorithmus zum Aunden der Basiselemente des Restklasseringes

nach einem nul ldimensionalen Polynomideal Ph D Thesis Univ Innsbruck

Thierry Co quand Patternmatching with dependent types These Pro ceedings

Michael Dummett Elements of Intuitionism Oxford

Monique LejeuneJalab ert Eectivite de calculs polynomiaux DEA Thesis Inst Fourier

Univ Grenoble I

Carl Jacobsson Clas Lofwall Standard bases for general coecient rings and a new con

structive proof of Hilberts basis theorem Journal of Symbolic Computation Vol

pg

Lena Magnusson These Pro ceedings

Per MartinLof Notes on Constructive Mathematics Almqvist Wiksell Sto ckholm

Fred Richman and Gabriel Stolzenberg Wel l QuasiOrdered Sets To app ear in Advances

in Mathematics

Formal Pro ofs of Combinatorial Completeness

Veronica Gasp es

University of Gothemburg and Chalmers University of Technology

June

Abstract

Formal pro ofs of the combinatorial completeness of two combinator calculi are presented

The formal language used to write the calculi and the pro ofs in is MartinLofs set theory

The formalization was machine checked in Alf Another Logical Framework where the set

theory and the notions involved in the pro ofs were implemented The rst pro of concerns

untyped combinators where unrestricted combinatorial completeness holds The presenta

tion of the calculus as well as the pro of of combinatorial completeness are from Curry and

Feys b o ok Combinatory Logic CF The second pro of concerns simply typed combinators

where a typed restricted version of combinatorial completeness holds

An app endix is attached with the implementation in Alf of the formalization

Introduction

This pap er describ es formalization of pro ofs of some theorems involving combinators The

theorems state the ability of combinators to describ e functions without the use of variables To

express these statements known as combinatorial completeness the notion of intuitive function

is formulated so that it can b e stated that any such function can b e dened by means of the

combinators First an untyped version of the combinators is considered taken from Curry and

Feys b o ok Combinatory Logic CF the denitions and the pro ofs follow the ones presented

there and have b een formalized in MartinLofs set theory and machine checked using the Alf

system Next a typed version with types formed from arbitrary atoms by is presented and

a type restricted version of the combinatorial completeness is proved Two approaches to the

typed calculus are analyzed Currys one where arbitrary combinators may b e formed which

are then assigned types and Churchs one where combinators are dened as b elonging to some

type this approach is used in the pap ers by Tait Tai and Sanchs San

The work was intended as an exercise in developing a concrete example in MartinLofs

set theory A description of this theory may b e found in the b o ok Programming in Martin

Lofs Type Theory by Nordstrom Petersson and Smith NPS from which we b orrow the

notational conventions The implementation of the logical framework provided by Alf was

of crucial imp ortance in actually completing this development It provides a straightfoward

implementation of the set theory and the sets that are added for the particular problem and

in checking the denitions and pro ofs it helps you by keeping track of a lot of information A

description of an earlier version of Alf may b e found in ACN The set theory was used by

dening new sets that corresp ond to this particular problem These denitions usualy introduce

verocschalmersse

new primitive notions which are provided by making an inductive denition but there are also

some abbreviations which are stated using denitional equality

All the informal denitions statements and pro ofs are to b e found in the literature They

are presented here only as an introduction to the formalization which then is interleaved with

the text and is presented as so on as the notions are introduced The pap er b egins with some

references to the presentation of formal systems as given in the rst chapters of CF em

phasizing the relation of that approach to the formalization of theories in MartinLofs set

theory

Formal Systems

The aim of this section is to show some connections b etween the way formal systems are analyzed

in chapters and in CF and the way one formalizes theories in MartinLofs set theory

In CF a language the Ulanguage and a theory the epitheory are describ ed which are

assumed to b e understo o d and are used to comunicate notions and to prove statements In this

context the description of a formal system consists of extending the Ulanguage in a particular

way which also extends the theory in the sense that it provides it with more principles of pro of

A formal system is describ ed by a collection of sets a set of ob jects introduced by the formal

system a set of statements or formulae formulated by the formal system called the elementary

statements which could b e understo o d as the forms of judgement introduced by the formal

system and a set of theorems proved by the formal system called the elementary theorems

which may b e understo o d as the evident judgements The Ulanguage is thus enriched with

the new ob jects and predicate formers All these sets are introduced by inductive denitions

and hence the epitheory is enriched with principles of pro of by induction over these sets The

principles that arise from dierent inductive denitions are carefully explained in CF

It is required that the epitheory is constructive so that pro ofs of elementary theorems or

construction of elementary ob jects can b e pro duced from the pro of of an epitheorem stating

their existence If one understands the epitheory and the Ulanguage as MartinLofs set

theory then the description of a formal system consists of extending the set theory with some

sets The extended theory may b e used to prove elementary statements ie to use the formal

system dened or epistatements ie to prove statements ab out the formal system dened

The sets that characterize the formal system are given by inductive denitions there are rules

to introduce the elements of each set and an elimination rule that expresses the principle of

pro of or denition by induction over that set The explanation of the induction techniques in

CF may b e used as a justication of the elimination rules Most of the epitheorems in the

b o ok are then proved by induction which can easily b e expressed in set theory

This approach diers from the more usual one in the presentation of formal systems Kle

describ ed as more syntactical in CF For this other view the rst step in the setting of

a formal system consists of dening a new language as formed by the strings over a certain

alphab et This new language is then called the ob ject language and is never used The language

in which the formulation is made is called the metalanguage where there are names for the

expressions of the ob ject language All the use that is done of the formal system introduced is

through the metalanguage In the more abstract approach ab ove ob jects are introduced by an

inductive denition thus b eing formed through sp ecic constructors not merely by sequencing

of characters This approach is followed also in the denition of the forms of judgements and

the set of theorems where the constructors corresp ond to the axioms and rules of inference In

this case the ob jects introduced are used thus constituting an extension of the used language

This corresp onds exactly to the way one introduces new sets in MartinLofs set theory one has

then an extended language and theory to use

Variables

When considering the denition of a formal system as extending a language and a theory

with some constants and rules it remains to b e said how variables are to b e handled The

original primitive language will contain variables in CF called the intuitive variables which

in setting up a formal system are used to express generality for instance when describing

a schematic rule or stating some epitheorems It may b e the case that the formal system

introduced needs to describ e functional ob jects This is usually done by introducing a category

of ob jects the formal variables for which a rule of substitution is formulated These sp ecial

ob jects are then introduced as new constants that extend the primitive language The aim

of combinatory logic is to provide a formal system that analyzes the role of variables and

substitution in such a way that it may b e used in the presentation of other formal systems when

describing functional ob jects Hence once combinatory logic has b een introduced neither

variables nor substitution rules need to b e considered

The theory of combinators itself do es not contain variables It will b e the case however

that to state the theorems ab out the combinatorial completeness epitheorems concerning the

formal systems we will present for the combinators we will have to consider formal systems

which do contain variables namely extensions with variables of the original theory In these

extensions the ob jects will b e understo o d as functions from ob jects of the original theory to

ob jects of the original theory These variables added in the extensions will b e introduced by

only saying that they are ob jects no rule of substitution will b e stated for them nor will they

take part of any statement but as arbitrary ob jects In CF these formal variables are called

indeterminates They have the prop erty that they may b e replaced by an arbitrary ob ject and

thus the statements involving them are equally valid as general epistatements using an intuitive

variable instead The theories for combinators will b e formalized in MartinLofs set theory by

dening new sets for the ob jects statements and theorems the variables of an extension will

b e implemented by a particular set

Untyped Combinators

The theory of combinators provides an analysis of the pro cess of substitution through the

notions of function and application In Schonnkels original pap er Sch a theory of func

tional ob jects is introduced to represent incomplete ob jects without using variables to indicate

the places for the argument These functional ob jects called combinators are obtained from

certain atomic combinators by means of application as the only op eration Substitution is rep

resented by application and there are rules that say which ob ject results when the substitution

is p erformed The atomic combinators and the rules that dene them express the basic ways

of building expressions which contain holes namely building an arbitrary constant expression

not dep ending in what is provided as argument and the incomplete expression resulting from

application of an incomplete expression to another

Following CF the theory of combinators called H is dened as a formal system in the

sense ab ove by inductively dening the ob jects the statements and the theorems The ob jects

are formed from the atoms K to express constant functions and S to express the function

which results from the application of a function to another one Application will b e denoted by

juxtap osition f a asso ciating to the left The statements are of the form f g where f and g

are arbitrary ob jects The theorems are dened by the following axioms and rules

K ab a K

S f g a f ag a S

f f

f g

g f

f g g h

f h

f g

f a g a

a b

f a f b

As an example of an ob ject of this theory consider SKK which according to the rules

b ehaves like the identity function ie the function representing the incomplete ob ject which

when completed with any other ob ject as argument pro duces the same ob ject as result let x

b e an arbitray ob ject then

S K K x K xK x x

The result we will analyze is the ability of this calculus of functions to describ e as an ob ject

any intuitive incomplete ob ject These incomplete ob jects are understo o d to b e describ ed as

a combination of previously dened functions and variables It will b e shown that any such

ob ject is already present as an ob ject a function of the calculus This prop erty is known

as combinatorial completeness and we need to introduce some way of describing the intuitive

incomplete ob jects in order to state it more precisely This result makes it p ossible to work

with this calculus instead of using variables and introducing substitution when dening other

formal systems We will follow Currys formulation of intuitive incomplete ob jects and of what

it means for them to b e describ ed by a function in the calculus

A p ossible way of understanding the intuitively denable functions from ob jects to ob jects is

by considering combinations formed not only from K and S but involving also certain arguments

x x This may b e done by considering a theory similar to the original one where certain

n

unsp ecied ob jects x x have b een added If we let H b e the theory that results by

n

adjoining the indeterminates x x to H then an ob ject h in H can b e understo o d as

n

an incomplete ob ject which when completed with ob jects a a of H yields an ob ject of

n

H Thus what must b e shown is that for every h an ob ject h of H may b e dened so that it

represents the incomplete ob ject h as a function from ob jects in H to ob jects in H The way

of proving that this term h represents h as a function is done by showing that

h x x h

n

is a theorem of H This means b ecause h do es not contain any of the indeterminates x x

n

that for every tuple a a of ob jects of H the application h a a is equal to the ob ject

n n

that results by replacing the indeterminates in h by a a Before showing how to dene

n

h in H from h in H we will show how to formalize in MartinLofs set theory the theory H

and its extensions

To pro ceed the notion of extension by adjoining indeterminates must b e formulated more

precisely While a theory is characterized by the set of ob jects the set of statements and the set

of theorems an extension is dened by the set of indeterminates adjoined Thus a theory and

its extensions may b e describ ed as a family of theories indexed by the sets of indeterminates

ie by a family of ob jects a family of statements and a family of theorems all indexed by the

sets of indeterminates All theories in the family are dierent however there is a natural way of

identifying an arbitrary ob ject of a theory with the one built in the same way in an extension

This is made explicit by injections of a theory to an extended one When considering this the

statement ab out hx x h must b e formulated more precisely considering these injections

n

b ecause h is a term in H it must b e injected into H for the application to x x to b e an

n

element in the corresp onding set of ob jects and the statement to make sense

The formalization consists of dening sets and families of sets in the set theory to represent

the notions b eing formalized The following is a presentation of such a formalization for the

families of theories of combinators ab ove

Each set of indeterminates is a nite set hence it will b e represented by the nite sets

of MartinLofs theory N These sets will b e dened as a family indexed by the length

n

n The introduction rules for this family corresp ond to a nite set b eing formed by

injecting all the elements in the previous one and putting one element more There is no

introduction rule for the nite set of length

ISformation

ISn Set n N

ISintroduction

n N

putn ISsn

ISintroduction

n N x ISn

inject n x ISsn

An elimination rule is given for each set ISn which allows pro of of statements under

the assumption of having an element in the corresp onding segment The set IS has no

introduction rule thus its elimination lo oks like elimination

ISelimination

P x Set x IS p IS

ISE P p P p

The ISsn has the two introduction rules ab ove thus

ISeliminations

n N

P x Set x ISsn

e P putn

dq P inject n q q ISn

p ISsn

ISsE n P e d p P p

This constant is dened by the equalities

ISsE n P e d put n e

ISsE n P e d I nj ectn q dq

The family Ob indexed by the sizes of the initial segments represents the family of ob jects

indexed by the extensions

Obformation

Obn Set n N

The introduction rules corresp ond to the formation of the ob jects in an extension with n

indeterminates

Obintroduction

n N

Kn Obn

Obintroduction

n N

Sn Obn

Obintroduction

n N x ISn

Varx n Obn

corresp onding to the variable x in an extension with n variables

Obintroduction

n N f a Obn

Appf a n Obn

There is an elimination rule for the set of ob jects in each extension

Obelimination

n N

P x Set x Obn

k P Kn

s P Sn

v y P Vary n y ISn

ah z ih iz P Apph z n h z Obn ih P h iz P z

o Obn

ObE n P k s v a o P o

This constant is dened by the equalities

ObE n P k s v a K n k

ObE n P k s v a S n s

ObE n P k s v a Var y n v y

ObE n P k s v a App h z n a h z

ObE n P k s v a h

ObE n P k s v a z

The family Form of the statements or formulae

Form formation

Form n Set n N

There is only one kind of statement equality b etween ob jects

Form introduction

n N a b Obn

a b Form n

n

Form elimination

n N

P x Set x Form n

ea b P a b a b Obn

n

f Form n

Form E n P e f P f

Form E n P e a b ea b

n

The family of the theorems

formation

f Set n N f Form n

n

The introduction rules corresp ond to the axioms and inference rules for asserting equality

b etween terms Only some of them are exhibited here the ones corresp onding to K

and the rest are co ded in the same way

introductionK

n N a b Obn

kk a b n AppAppK a n b n a

n n

introduction

n N a Obn

a n a a

n n

introduction

n N f g a Obn p f g

n n

f g a n p Appf a n Appg a n

n n

We have thus dened the sets that describ e a family of theories each set of each theory de

ned inductively The elimination rules which close the denitions are used whenever denition

by recursion or pro of by induction on a given set is required

There is a natural way of understanding an ob ject of a theory as an ob ject of an extension

built in the same way but in the extended theory When formalizing the theorem ab out combi

natorial completeness this injection is required and thus must b e stated formally This is done

by means of a function

O m n Nm n Obm Obn

which given m n with m n will take an ob ject in an extension with m indeterminates into

itself in an extension with n indeterminates The denition of O is based on the injection of

an initial segment of length m into the one of length n To implement this denitions will b e

dened by rst dening as follows

formation

m n Set m n N

The introduction rules state that is the transitive closure of the relation that a number is less

than its succesor

introduction

n N

OneStepn n sn

introduction

m n o N m n n o

m n o m o

The elimination rule closes the denition by stating the principle of pro of or denition which

allows us to use the knowledge that a number is less than another one according to this denition

elimination

P x y z Set x y N z m n

ex P x s x OneStep x x N

s t u N

q s t

ds t u q r i h P s u s t u r t u

i P s t q

h P t u r

m n N

p m n

E P e d m n p P m n p

E P e d m s m OneStepm em

E P e d m o m n o q r dm n o q r E P e d m n q E P e d n o r

With this the denition of O is by cases on m n m n m n If m n it is the

identity If m n it follows by induction on this fact by using the elimination rule for the set

The two cases that must b e considered are

n is the succesor of m By induction on Obm each case of ob ject formation is

considered and translated to the corresp onding element in Obn

there is a number o such that m o and o n O is dened to b e the comp osition of

the functions the induction hypothesis yields for m o and o n

In a similar way the formulae of a theory may b e injected as formulae of an extension by

means of a function

F m n N m n Form m Form n

which is dened in the same way as O

Denition of Abstraction

We now dene for any ob ject h in H an ob ject h in H that represents it as a function

from ob jects in H to ob jects in H and prove this fact The denition and the pro of are by

induction on the size of the extension the inductive step b eing based on the denition and pro of

corresp onding to passing from a theory with at least one indeterminate to one with the extra

indeterminate removed In order to describ e the denition we will use the notation of bracket

abstraction for the ob ject dened if h is an ob ject in H we shall write x x h for the

n

h in H With this notation the induction step in the denition may b e expressed as

x x xh x x x h

n n

The denition of x h is by induction on h For each way of building ob jects in an extension

containing x it is analyzed what function of x is intended and so an ob ject which represents

such a function in a theory without x is dened The following cases arise

h is K When thought of as a function of x from ob jects of H to ob jects of H it is the

constant function with value K Thus we dene xK to b e KK

h is S With the same argument as for K we dene xS to b e KS

h is a variable of the extension Then there are two cases to consider either the variable

is x or some other variable y In the case it is y the same argument as for K and S yields

the denition of xy to b e K y In the case it is x the denition is such that the function

is the identity function This is b ecause x is the identity function when considered a

function of x Thus for this case we dene xx to b e SKK which was shown ab ove to

b ehave as the identity

h is an application f g Both f and g may contain x and thus are to b e considered as

functions of x The induction hypothesis yields the denitions of the two functions xf

and xg The ob ject that results when p erforming the substitution of an ob ject of H for

x in f g may b e analyzed as formed by the application of the ob ject that results from

p erforming the substitution in f to the one that results from p erforming it in g In terms

of x f and xg this is expressed by the application of x f o to x g o where o is the

ob ject substituted for x We thus dene xf g to b e S xf x g

The formalization of these denitions pro ceeds by rst dening xh by induction on the

construction of h an ob ject in a theory that contains at least one variable ie by applying the

elimination rule for Ob to h Obsn for some natural number n Thus by assuming that

one has such an h an ob ject in Obn is dened as the abstraction of the extra variable from

h The cases that arise in the induction on h are the following

h is Ks n Then dene the abstraction as the constant function with value K in Obn

AppKn K n n

h is Ssn Then dene the abstraction to b e the constant function with value S in

Obn AppKn Sn n

h is Var x sn where x ISsn Then one must analyze whether x is the variable to

b e abstracted the variable that extends the theory from n to sn or any other variable

already present in the theory for n This is realized by making an induction on x ie

by applying the elimination rule for IS to x ISsn The two cases that arise are

x is putn Then dene the abstraction to b e the identity function in Obn

AppAppSn Kn nK n n

x is inject y n where y is in ISn Then dene the abstraction to b e the constant

function with value y in Obn AppKn Var y n n

h is an application Appf a s n Then the induction hypothesis yields a value for f

in Obn say f h and a value for a in Obn say ah then dene the abstraction to b e

AppAppSn f h n ah n

We have thus dened an element in Obn assuming n N and h in Obs n We will

now dene by induction on n an element in Ob from an element h in an extension with n

indeterminates the abstraction of all the variables in the extension Using induction on n two

cases arise

If n is then h is already an element in Ob

If n is the succesor of some natural number t the induction hypothesis yields a metho d

for dening an element in Ob for every h in Obt Then take the element in Obt

which results from appliyng the denition ab ove and nally apply the metho d yielded by

the induction hypothesis to this element

One must now prove that the abstractions so dened b ehave as planned ie that hx x

n

h This pro of follows the same lines as the denition of h again it is carried out by induction

on n the crucial case b eing the pro of that xh x h which again is an induction on the

construction of h

h is K S or a variable y dierent from x the denition of xh is the same for these

three cases K h Then we have xh x K h x h

h is the variable x Then we have xx x S K K x x

h is the application f g Then we have

xf g x S xf x g x x f x x g x

The induction hypothesis yields xf x f and x g x g and hence by application of

the rules and

x f x x g x f g

With the denitions for the theories of combinators ab ove and letting h b e the ob ject in

an extension with n indeterminates and h b e x x h in the original theory an extension

n

with no indeterminates the fact that h represents h as a function is formalized by

app O h n h

n n

where app x n is dened by induction on n as the application of x Obn to all the indeter

minates of the extension The injection of h into the extension with n indeterminates is needed

for the application to x x to make sense As in the informal pro of ab ove this is shown

n

by induction on n the induction step b eing based on the pro of of

AppO h put n n h

sn sn

where h is an ob ject in an extension with sn indeterminates and h is the corresp onding xh in

an extension with n indeterminates the abstracted variable b eing the last element of the initial

segment ISsn ie putn The induction on h used in the informal pro of is implemented

by an application of the elimination rule for Obn The that are said to hold in the informal

pro of hold by denitional equality while the require the application of the rules that dene

n

The denition of x x h together with the pro of of app O h n h constitute

n n n

a pro of of

n Nh Obnh Ob app O h n h

n n

which formalizes the combinatorial completeness for untyped combinators This formalization

of the theories and the pro ofs was edited in Alf the co de of this implementation is attached as

an app endix

Typed Combinators

In this section we shall introduce a theory of typed combinators and show that a restricted ver

sion of combinatorial completeness holds After a short motivation for the introduction of types

the theory and the notion of extension by adjoining indeterminates will b e presented together

with a formalization in MartinLofs set theory Next a typed version of the combinatorial

completeness will b e proved followed by the corresp onding formalization

Dierent analysis of combinatory logic as a formalism to express the pro cess of substitu

tion in formalized theories end in the introduction of types to classify combinators in dierent

categories In Curry and Feys CF the types are asso ciated with semantical categories The

co ding of prop ositional logic as an extension of combinatory logic with a constant P for form

ing implication P f g co des f g a new statement constructor for derivability f

co des f is derivable and rules for proving that certain ob jects are derivable P f P g f

co des the axiom f g f results in an inconsistent theory in the sense that for every ob ject

f it is a theorem that f This inconsistency is avoided by restricting the arguments of

to b e prop ositions This implies classifying the ob jects to isolate the category of prop osi

tions This gives rise to the theory of functionality presented in CF where from the type

of prop ositions a functional hierarchy is built MartinLof presents an argument for classifying

the combinators in syntactical categories The untyped combinators are rejected as a basis for

the presentation of formal systems due to the fact that equality b etween them is not decidable

and thus cannot b e used as denitional equality and that abbreviations may not b e eliminable

consider the term SII SII The solution comes from analyzing expressions into saturated

and unsaturated as Frege Fre did This is expressed by means of types starting from a

type for saturated expressions and building a functional hierarchy from it for the unsaturated

expressions according to the kind of argument they exp ect This system is presented in chapter

of NPS for the calculus

Dierent notions of meaningfullness led Curry and Church to dierent ways of considering

the typed versions of their calculi Currys approach consists of assigning types to the un

typed ob jects while Churchs consists of designing a new calculus where only typed ob jects are

formed We will consider the typed version of the combinatorial completeness statement in b oth

approaches

In Currys approach a new set of ob jects is dened namely the types and a new judgement

form that a combinator has a type There are axioms and rules dening the provable judgments

of this form Thus the notions and theorems involving the combinators are left as they were

and new theorems are stated involving the types In the case of the combinatorial completeness

it is said that if after assigning types to the variables of the etension an ob ject can b e assigned

a type then the abstraction of that ob ject dened for untyped combinators can b e assigned a

type namely the function type from the types of the variables to the type of the original ob ject

Following Churchs approach everything must b e done again from the very b egining Once

the types are dened for each type it is said which are the combinators of that type hence

instead of a set of combinators there is a family of sets indexed by the types The equality

judgement is then stated for typed combinators The extensions considered in order to dene

abstraction are extensions with typed variables and the abstraction is dened among typed

combinators

What follows presents the formalization of the denitions of abstraction and the pro ofs that

it b ehaves as intended for the simply typed combinators following b oth approaches Churchs

version is presented rst in full detail while Currys approach is only sketched Both were

checked in Alf and the app endix contains the Alf implementation for Churchs version

Types a la Church

The types are formed from arbitrary atomic types by means of the function arrow The

ob jects are not introduced as a single set but as a family indexed by the types so there is a set

of ob jects for each type The elementary statements are equalities b etween ob jects of the same

type The restricted version of combinatorial completeness that can b e proved takes the types of

the incomplete ob ject and the variable to b e abstracted into account and forms a function of the

adequate type In order to describ e the incomplete ob jects we must again consider extensions

of the original theory by adjoining indeterminates in this case typed indeterminates

In the following denition of the theory of typed combinators let b e variables

of the epitheory ranging over types The ob jects of each type are dened from typed versions

of K S and application For all types there is a constant

K

For all types there is a constant

S

And for all types there is an op eration of application

M N

MN

The formulae are equalities b etween ob jects b elonging to the same type so if f and g are ob jects

in the same type then f g is an elementary formula The theorems are characterized

by essentially the same rules as in the untyped theory but also considering the typing of the

ob jects involved

K ab a K

S f g a f ag a S

f f

f g

g f

f g g h

f h

f g

f a g a

a b

f a f b

As an example of the ob jects denable in this theory consider S K K

the typed identity function let x b e any ob ject of type then

S K K x K xK x x

We will have to consider extensions of this theory by adjoining indeterminates to express

the intuitive incomplete ob jects In order for an indeterminate to b e adjoined it must b e

introduced as an ob ject of some type and thus must have a type asso ciated to it We will use

the notation x for an indeterminate x which has b een assigned type In an extension with

1

n

the ob jects of a given type are built as ab ove with the addition x the indeterminates x

n

of letting variables of type b e ob jects of type An extension is then no longer a nite set

but a nite set together with an assignment of types to each of the elements of this set

The formalization in set theory pro ceeds by considering that each theory consists of a

family not only a set as in the untyped case of ob jects formulae and theorems and by

considering a family of such theories indexed by extensions Again the notion of extension

must b e made precise in this case to take into account that there is no longer a set of ob jects

to which indeterminates are adjoined but a family of them An extension of the theory of

typed combinators may b e characterized by a set of indeterminates together with a way of

adjoining them to some sets of ob jects thas is together with a way of assigning types to them

Thus not only the sets of indeterminates must b e formalized by the initial segments of the

natural numbers but also the type assignments to these sets These will b e formalized by nite

sequences of types of length n for the type assignements for the initial segment of length n The

formalization which is roughly as for the untyped case requires the denition of the following

sets

A set Type for the types of the combinators

Typeformation

Type Set

The set Type is inductively generated and there are two introduction rules one for the

atomic types that is the type variables and one for function types We let the type

variables b e indexed by some given set Atom

Typeintroduction

Atom

var Type

Typeintroduction

Type Type

Type

Typeelimination

P t Set t Type

bat P var atat Atom

i I I P Type I P I P

Type

TypeRecP b i P t

TypeRecP b i var at bat

TypeRecP b i i TypeRec P b i TypeRec P b i

ISn Set n N

The nite sets the sets of indeterminates The same sets as for the untyped case

A family TA for the type assignements to the sets of indeterminates

TAFormation

TAn Set n N

Each element in TAn formalizes a type assignement for ISn as a sequence of length n

of elements of Type

TAintroduction

Nil TA

TAintroduction

n N ta TAn Type

Consn ta TAsn

TAelimination

P x y Set x N y TAx

e P Nil

dm t i P sm Cons m t m N t TAm Type i P m t

n N

ta TAn

TAEP e d n ta P n ta

TAEP e d Nil e

TAEP e d s n Cons n t dn t TAE P e d n t

The family of ob jects of each type in each extension is dened by means of Ob The set

Obn ta denes the set of ob jects of type in an extension with n variables and a type

assignement ta to the indeterminates of the extension The introduction rules corresp ond

to the formation of the terms

Obformation

Obn ta Set n N ta TAn Type

Obintroduction

n N ta TAn Type

Kn ta Obn ta

Obintroduction

n N ta TAn Type

Sn ta Obn ta

Obintroduction

n N ta TAn Type x ISn p VarType n ta x

Varn ta x p Obn ta

In this last rule which corresp onds to introducing an indeterminate as an ob ject of type

when the extension is given by n and ta the premise p VarTypen ta x corresp onds

to a pro of that the indeterminate x an element in ISn has the type in ta The set

VarType which formalizes this statement is dened b ellow

Obintroduction

n N ta TAn Type f Obn ta a Obn ta

Appn ta f a Obn ta

Obelimination

n N

ta TAn

P x y Set x Type y Obn ta x

k u v P u v u K n ta u v u v Type

su v w P u v w u v u w S n ta u v w u v w Type

v u v w P u Var n ta u v w u Type v ISn w VarTypen ta v u

u v Type

w Obn ta u v

au v w x iw ix P v Appn ta u v w x x Obn ta u

iw P u v w

ix P u x

Type

p Obn ta

obE n ta P k s v a t P t

obEn ta P k s v a K n ta k

obEn ta P k s v a Sn ta

s

obEn ta P k s v a Var n ta x p v x p

obEn ta P k s v a App n ta f x a f x

obE n ta P k s v a f

obE n ta P k s v a x

In order to formalize the variable x we will dene a set of pro ofs of a variable an element

in some IS b eing assigned a type by a type assignement ie a set that formalizes that

the type of the ith element in an initial segment is assigned the type in the ith p ossition

of the type assignment VarTypen ta x denes the predicate stating that the type

assigned to x by the type assignement ta is

VarTypeformation

VarType n ta x Set n N ta TA x ISn Type

VarTypeintroduction

n N ta TAn Type

PutTypen ta VarType sn Cons n ta put n

VarTypeintroduction

n N ta TAn Type y ISn p VarType n ta y

InjectType n ta y p VarTypes n Cons n ta inject n y

The rst introduction rule states that the type assigned to the last variable in an initial

segment of length n is the last type in a type assignement of this length The second one

states that the type of a variable present already in the previous initial segment has the

type given to it in the corresp onding shorter type assignment

VarTypeelimination

n N

ta TAn

x ISsn

y z Type P x y z t Set

t VarTypes n Cons n ta z x y

ex P putn x x PutType n ta x x Type

x y Type

z ISn dx y z t P inject n z x y InjectType n ta x y z t

t VarTypen ta z x

i ISsn

Type

p VarType sn Cons n ta i

VarTypeE n ta P e d i p P i p

VarTypeEn ta P e d put PutType n ta e

VarTypeEn ta P e d inject n x InjectType n ta x p d x p

There is a set which formalizes the formulae of the typed combinators with only one

introduction rule corresp onding to the only way of building formulae ie equality b etween

ob jects of the same type in a given extension

Form formation

Form n ta Set n N ta TAn Type

Form introduction

n N ta TAn Type f g Obn ta

f g Form n ta

nta

Finally there is a set describing the theorems ie the provable equalities The introduc

tion rules corresp ond to the axioms and inference rules As in the untyped case we shall

only present some of them the ones corresp onding to K and

formation

f Set n N ta TAn Type f Form n ta

nta

introductionK

n N ta TAn Type a Obn ta b Obn ta

kkn ta a b AppAppn ta K a n ta al pha b a

nta nta

introduction

n N ta TAn Type a Obn ta

n ta a a a

nta nta

introduction

n N

ta TAn

Type

f g Obn ta

a Obn ta

p f g

nta nta

n ta f g a p Appn ta f a Appn ta g a

nta nta

As for the untyped case there is a natural way of thinking of an ob ject in a theory as an

ob ject in an extension as built up in the same way This is made explicit by a function O as

b efore which takes an ob ject in a theory and builds up the corresp onding one in the extension

For this typed theory we will only consider the abstraction of one variable the induction on n

required to abstract all the n variables of an extension is essentially the same as for the untyped

theory Thus we will only require the injection of a theory into the next one which is provided

by the function

O n N ta TAn TypeObn ta Obsn Cons n ta

The function O takes a natural number n a type assignment ta of length n a type to extend

the type assignment and a type which is the type of the ob ject in question It then takes

an ob ject of type in an extension with n indeterminates which are assigned types by ta and

pro duces an ob ject of type built in the same way in a theory with sn indeterminates assigned

types by Consn ta The denition is by induction on Obn ta formally by application

of the elimination rule for this set

This concludes the formalization of the theory of simply typed combinators the next section

considers the denition of the typed version of abstraction

Typed Abstraction

1

n

By adding one more indeterminate x Consider an extension with n indeterminates x

n

x the ob jects h in this new theory are such that when replacing an ob ject of type for x

in them they yield an ob ject of type We will show that these ob jects were already present

in the theory without x as functions h This will b e done by denining for each h

an ob ject x h and then showing that

x h x h

sn

Both the denition of x h and the pro of of x h x h are by induction on h b eing

sn

1

n

x Except for the type information x an ob ject of type in the extension with x

n

involved the denition pro ceeds in the same way as for the untyped case in all cases but

the one for the variable In the untyped case the analysis of which variable is considered

is by induction on the denition of b eing in the corresp onding initial segment which alone

characterizes the extension In the typed case the analysis is an induction on the denition

of which type is assigned to the variable in the extension b ecause it is this denition which

follows the construction of the extension it takes into account b oth the initial segment and the

type assignement The denition of x h will b e done by analyzing what function of x h is

for each of the forms of constructing h

h is K is When thought of as a function of x it is the

1 2

constant function with value K Thus we dene x K to

1 2 1 2

b e K K

1 2 1 1 2

h is S is With the same argument

1 2 3

as for K we dene x S to b e

1 2 1 2 3

K S

1 2 3 1 2 1 3 1 2 3

h is a variable of the extension Then there are two cases to consider according to

whether the variable is x is or some other variable y is In the case it is

y by the same argument as for K and S the denition of x y is

1 2 1 2 3

K y In the case it is x the denition is such that the function is the identity function

as x is when considered a function of x Thus for this case we dene x x to

b e S K K which was shown ab ove to b ehave as the identity

h is an application f g where b oth f and g may contain x and thus

are to b e considered as functions of x The induction hypothesis yields the denitions

of the two functions x f and x g The ob ject that results

when p erforming the substitution of an ob ject of type for x in f g may b e analyzed

as formed by the application of the ob ject that results from p erforming the substitution

in f to the one that results from p erforming it in g In terms of x f and x g this is

expressed by the application of x f o to x g o where o is the ob ject substituted for

x We thus dene x f g to b e S x f x g

1 2 1

The formalization of this denition is as follows Given n N ta TAn Type and

h Obsn Cons n ta ie an ob ject of type in an extension with sn indeterminates

the last of which is assigned type apply the elimination rule for Ob to h to nd an element in

Obn ta according to the denition ab ove The premises of this rule yield the following

cases

h is Ksn Cons n ta Then dene the abstraction to b e the constant function

with value K in Obn ta

Appn ta Kn ta K n ta

note that we did not write the type parameters of App They may b e restored by lo oking

at the types of the arguments We will continue with this convention along this denition

h is Ssn Cons n ta Then dene the abstraction to b e the constant func

tion with value S in Obn ta

Appn ta K n ta S n ta

h is Varsn Cons n ta x p where x ISsn and

p VarTypesn Cons n ta x

is a pro of that the type assigned to x in the extension is Then one must analyze whether

x is the variable to b e abstracted the variable that extends the theory from n to sn

or any other variable already present in the theory for n This is done by making an

induction on p ie by applying the elimination rule for

VarType sn Cons n ta x

on p The two cases that arise corresp ond to whether x is the last variable of the extension

the one we are abstracting or some other

p is PutTypen ta Then dene the abstraction to b e the identity function in

Obn ta

Appn ta Appn ta Sn ta K n ta K n ta

p is InjectType n ta y q where y is in ISn a variable already present in the

extension with only n variables and q VarTypen ta y is a pro of that the type

assigned to y in this theory is Then dene the abstraction to b e the constant

function with value y in Obn ta

Appn ta Kn ta Var n ta y q

h is an application Appsn Cons n ta f a where

f Obs n Cons n ta

a Obsn Cons n ta

In this case the elimination rule provides also induction hypothesis for f and a which

for this denition yield that b oth the abstraction for f and a are dened say f h

Obn ta and ah Obn ta Then the corresp onding ob ject for

the application is

Appn ta Appn ta S n ta f h ah

The next step is to prove that the dened function has the intended b ehaviour ie that

x h x h This pro of is again by induction on h and as for the untyped case

sn

follows the denition of x h It is formalized by an application of the elimination rule

for Obsn Cons n ta and also follows the denition of the function From b oth the

denition of the function and the pro of ab out its b ehaviour we obtain a pro of of

n Nta TAn Typeh Obsn Cons n ta

h Obn ta App O h putn ta PutType n ta h

sn

where putn ta PutTypen ta is the variable added with type

The formalization of this pro of as it was edited and checked with the Alf system may b e

found in the app endix

Types a la Curry

This approach is based on analysing which untyped combinators may b e assigned a type

Consider the theory of untyped combinators and dene a set for the types as in the previous

section A new judgement form is introduced M where M is an untyped combinator and

is a type The axioms and rules dening the provable judgments of this form are

For any types it is provable that

K

For any types it is provable that

S

For any types

M N

MN

As opp osed to the system a la Church where there is a dierent constant K for each dierent

types here there is only one constant K which may b e assigned many types

The extensions and the denition of abstraction are the ones for the untyped combinators

It remains to b e said when a combinator in an extension with indeterminates x x may

n

b e assigned a type To do this we consider again type asignments to the indeterminates and

extend the notion of having a type to having a type in an extension given a type assignment

The formalization pro ceeds by dening the set TypeOf

TypeOfformation

TypeOfn ta M Set n N ta TAn M Obn Type

TypeOfintroduction

n N ta TAn Type

Ktn ta TypeOfn ta K

TypeOfintroduction

n N ta TAn Type

Stn ta TypeOfn ta S

TypeOfintroduction

n N ta TAn x ISn Type p VarType n ta x

vartn ta x p TypeOfn ta var n x

TypeOfintroduction

n N

ta TAn

f a Obn

Type

p TypeOfn ta f

q TypeOfn ta a

apptn ta f a p q TypeOfn ta Appn f a

That abstraction b ehaved as intended was already shown for the untyped combinators

it is shown now that it also b ehaves adequately with resp ect to the types We show that

if M is a combinator in an extension with indeterminates x x then if given a type

n

assignment it is the case that M then it is the case that x x M

n n

This is proved by induction on n based on the pro of that if M is a

n

combinator in an extension with indeterminates x x x which can b e assigned type

n

under the type assignment then xM is assigned type in the extension

n

x x under the type assignment This in turn is proved by induction on

n n

TypeOfsn Cons n ta M This theorem stating the well b ehaviour of abstraction with

resp ect to types is a sp ecialization of Currys stratication theorem as presented in CF

Remarks

The typed combinators constitute the CurryHoward interpretation of minimal logic as pre

sented in the Hilb ert style The types are interpreted as the prop ositions the arrow corresp onds

to implication and the terms as co des for the pro ofs in the system Thus the constants K

and S co de the pro ofs of the axioms given by their types and application co des a pro of

formed using mo dus monens The indeterminates in an extension should then b e interpreted

as pro ofs of assumptions which are given by the type assigned to them The theorem ab out

the restricted combinatorial completeness can b e read under this interpretation as stating the

deductive completeness of the logical system It states that if there is a pro of of prop osition

under the assumption of prop osition then there is a pro of of the prop osition The

argument ab ove for the typed combinators may b e seen as a pro of of this statement by providing

a pro of for given the hypothetical pro of of

There is a much simpler way suggested by several p eople to formalize the typed extensions

when following Churchs approach An extension is charachterized by a list of types then a

variable of a given type in such an extension is identied with the pro of that that type is in a

given p osition in the list This approach was also veried in Alf The formalization is based in

changing all denitions so that the parameter charachterizing the extension is only one a list

of types

Acknowledgments

I am most grateful to Bengt Nordstrom and Jan Smith for their guidance encouragement and

go o d disp osition I also owe thanks to Daniel Fridlender and Nora Szasz for many helpful ideas

and the careful reading of this work and to the Programming Metho dology Group for providing

a very stimulating environment

References

ACN L Augustsson T Co quand and B Nordstrom A short description of Another Logical

Framework In Proceedings of the First Workshop on Logical Frameworks Antibes

pages

CF H B Curry and R Feys Combinatory Logic volume I NorthHolland

Fre G Frege Function and Concept In B McGuinness editor Gottlob Frege Col lected

Papers on Mathematics Logic and Philosophy pages Basil Blackwell

Kle S C Kleene Introduction to Metamathematics NorthHolland Amsterdam

NPS Bengt Nordstrom Kent Petersson and Jan M Smith Programming in MartinLofs

Type Theory An Introduction Oxford University Press

San L E Sanchs Functionals dened by Recursion Notre Dame Journal of Formal

Logic

Sch M Schonnkel Ub er die Bausteine der Mathematischen Logik Mathematische An

nalen

Tai W W Tait Intensional interpretation of functionals of nite type I Journal of

Symbolic Logic

App endix

This app endix contains the result of editing in Alf the formalizations of the untyped and typed

combinators and the pro of of combinatorial completeness for them In Alf there is a basic type

of sets Set and it is p ossible to form function types by means of the construction x AB where

B may dep end on x The elements of such types are formed by abstraction xb is a term in

x AB for b B under the assumption that x A These elements may b e used by application

f a

The implementation in Alf consists of declaring a new constant of type Set for every set

former or of a function type with values in Set for every family former Then corresp onding

to each introduction and elimination rule a constant is declared with its type corresp onding to

the type of functions from the types corresp onding premisses to the type corresp onding to the

conclusion The denitional equalities are introduced as equalities in Alf

In MartinLofs set theory there is the type of sets and then for every set there is type of

elements of that set Alf provides an implementation of this by letting every constant of type

Set to b e a type

The co de for the pro of in Alf for b oth the untyped and typed combinators b egins with the

co de for the basic sets of MartinLofs set theory

Basic Sets

The set for absurdity

Set

P x Setbott P bott

e

The set of natural numbers

N Set

N

s N N

natrec P NSetb P i x NP xP s xn N P n

natrec P b i b

natrec P b i s n in natrec P b i n

The set for the order relation b etween natural numbers

NN Set

OneStep n N n sn

MoreSteps m Nn No Nm n n o m o

P m Nn N l m n Set

e

e n NP n s n OneStep n

d m Nn N o N

l mn m n

l no n o

imn P m n l mn

ino P n o l no

P m o MoreSteps m n o l mn l no

x N

y N

l xy x y

P x y l xy

P e d x s x OneStep x ex

e

P e d x z MoreSteps x y z l l

e

dx y z l l P e d x y l P e d y z l

e e

The set corresp onding to disjunction

SetSetSet

inl A SetB Seta AA B

inr A SetB Setb B A B

A Set

e

B Set

P A B Set

el a AP inl A B a

er b B P inrA B b

p A B

P p

A B P el er inl A B a el a

e

A B P el er inr A B b er b

e

Note that is used as inx A B is an abbreviation for A B The same is done for

the conjunction and the implication

The set corresp onding to the universal quantier

A SetB ASet Set

A SetB ASet f x AB xA B

A SetB ASet f A B a AB a

e

A B A B f a f a

e

The set of functions corresp onding to implication

A SetB SetSet

A SetB Setf AB A B

A SetB Setf A B a AB

e

A B A B f a f a

e

The set for prop ositional equality

A Set a b ASet

id A Set x Ax x

A

J A Set C x Ay Az x y Set d x AC x x id A x a b A p

A

a bC a b p

A

JA C d a a id A a da

where we use a b as an abreviation for A a b

A

The initial segments of natural numbers

IS N Set

put n NISsn

inject n N i ISnIS sn

IS n N

e

P ISsnSet

e P put n

d i ISnP inject n i

p ISsn

P p

IS n P e d put n e

e

IS n P e d inject n i di

e

The pro of that an initial segment may b e injected into one of greater length

ISInjection m N n Np m n m nISm ISn

N

ISInjection m n p m n

e

m n

N

p ISm ISn

a m n aIS m IS n

e

n ISn ISs n hinject n h

m n o l mn l no hl mn hl no

ISm IS o

h ISn

e

ISo

hl no

ISm ISn hl mn h

e

m

n

a

bJN x y pIS x ISy x IS x IS x hh m n b

p

Untyped Combinators

The ob jects

Ob n NSet

K n NOb n

S n N Obn

var n N a ISnOb n

app n N f a ObnObn

Ob n N

e

P x ObnSet

e P K n

f P Sn

g x ISnP var n x

h x Obny Obnz P xt P y P app n x y

o Obn

P o

Ob n P e f g h K n e

e

Ob n P e f g h S n f

e

Ob n P e f g h var n a g a

e

Ob n P e f g h app n a b ha b Ob n P e f g h a Ob n P e f g h b

e e e

The term that co des the Identity

I nappn appn Sn K n K n n N Obn

The formulae

form n NSet

n N f g Obnform n

form n N

e

P form nSet

e x Obny ObnP x y

n

f form n

P f

form n P e f g ef g

e n

Where we use a b as an abreviation for n a b

n

The theorems

n Nf form nSet

Keq n N M P Obn appn appn Kn M P M

n n

Seq n N M P O Obn

appn appn appn Sn M P O appn appn M O app n P O

n n

n NM O P Obnp M O appn M P appn O P

n n n n

n N M O P Obnp M O appn P M appn P O

n n n n

n NM Obn M M

n n

n NM O Obnp M O O M

n n n n

n NM O P Obnp M O q O P M P

n n n n n n

n N

e

C x form ny xSet

n

ek x Obny ObnC n appn appn Kn x y x Keq n x y

es x Obn

y Obn

z Obn

C appn appn appn Sn x y z appn appn x z app n y z

n

Seqn x y z

emu x Obn

y Obn

z Obn

t x y

n n

u C x y t

n

C appn x z appn y z n x y z t

n

enu x Obn

y Obn

z Obn

t x y

n n

u C x y t

n

C appn z x appn z y n x y z t

n

er o x ObnC n x x n x

esig ma x Obn

y Obn

z x y

n n

t C x y z

n

C y x n x y z

n

etau x Obn

y Obn

z Obn

t x y

n n

u y z

n n

v C x y t

n

w C y z u

n

C x z n x y z t u

n

f form n

p f

n

C f p

n C ek es emu enu er o esig ma etau

e

appn appn K n x y x Keq n x y

n

ek x y

n C ek es emu enu er o esig ma etau

e

appn appn appn Sn x y z appn appn x z app n y z Seqn x y z

n

esx y z

n C ek es emu enu er o esig ma etau app n x z appn y z n x y z t

e n

emux y z t n C ek es emu enu er o esig ma etau x y t

e n

n C ek es emu enu er o esig ma etau app n z x appn z y n x y z t

e n

enux y z t n C ek es emu enu er o esig ma etau x y t

e n

n C ek es emu enu er o esig ma etau x x n x er ox

e n

n C ek es emu enu er o esig ma etau y x n x y z

e n

esig max y z n C ek es emu enu er o esig ma etau x y z

e n

n C ek es emu enu er o esig ma etau x z n x y z t u

e n

etau x y z t u

n C ek es emu enu er o esig ma etau x y t

e n

n C ek es emu enu er o esig ma etau y z u

e n

The following two derived rules were proved

Ieq n N x Obn appn I n x x

n n

Ieq n x n

appn In x

appn appn Kn x app n Kn x

x

Seqn Kn K n x

Keqn x app n Kn x

n N f g a b Obn f g a b appn f a appn g b

n n n n n n

n f g a b h h n

appn f a

appn g a

appn g b

n f g a h

n a b g h

The injection of a theory into an extension

O m Nn N p m n m nf ObmOb n

N

O m n p f

Ob m

e

xObn

Kn

Sn

xvarn ISm IS n ISInjection m n p x

e

x y hx hy app n hx hy

f

F m N n Np m n m nf form mform n

N

F mn p f

form m f form n x y O m n p x O m n p y f

e n

T m Nn Np m n m nf form m f F m n p f

N m n

T mn p f h

m

e

f h F m n p f

n

x y Keq n O m n p x O m n p y

x y z Seq n O m n p x O m n p y O m n p z

x y z t h n O m n p x O m n p y O m n p z h

x y z t h n O m n p x O m n p y O m n p z h

xn O m n p x

x y z h n O m n p x O m n p y h

x y z t u h h n O m n p x O m n p y O m n p z h h

f

h

The denition of abstraction of one variable

The denition consists of an application of the rule Ob We rst show the terms that corresp ond

e

to the premises of that rule and then plug them into it to build the denition

KAbstAlg n NOb n

KAbstAlg nappn K n K n

SAbstAlg n N Obn

SAbstAlg nappn Kn Sn

varAbstAlg n Nx ISsnOb n

varAbstAlg n xIS n xObn I n iapp n K n var n i x

e

appAbstAlg n N x Obsny ObsnOb nObnOb n

appAbstAlg n x y h h appn appn Sn h h

AbstAlg n NOb snOb n

AbstAlg n hOb sn

e

h Obn

KAbstAlgn

SAbstAlgn

xvarAbstAlgn x

x y h h appAbstAlgn x y h h

h

The pro of of the combinatorial completeness

We rst abbreviate the statement with the set CombComp and then prove it using Ob As in

e

the denition of AbstAlg we prove all the cases corresp onding to the premises and then plug

them into the rule We will not write all the arguments to the injections of a theory into another

one we will only keep what is injected and the extensions involved Thus O m n p f will b e

abbreviated with O m n f

CombComp n N X Obs nSet

CombComp n X appsn O n sn AbstAlgn X var sn put n X

sn sn

KCombComp n NCombComp n Ks n

KCombComp nKeqsn K sn var sn putn

SCombComp n NCombComp n Ssn

SCombComp nKeqsn Ss n var sn putn

varCombComp n N x ISsnCombComp n varsn x

varCombComp n xIS n

e

hCombComp n varsn h

Ieq sn var sn put n

iKeq sn var sn inject n i var sn put n

x

appCombComp n N

f Obsn

g Obsn

f h CombComp n f

g h CombComp n g

CombComp n apps n f g

appCombComp n f g f h g h sn

appsn

O n sn AbstAlgn appsn f g

vars n putn

appsn

appsn O n sn AbstAlgn f varsn putn

appsn O n sn AbstAlgn g var sn put n

appsn f g

Seqsn

O n s n AbstAlgn f

O n s n AbstAlgn g

var sn putn

sn

appS uccn

O n S uccn AbstAlg n f

varsn put n

f

appsn O n sn AbstAlgn g var sn putn

g

f h

g h

ObCC n NX ObsnCombComp n X

ObCC n X Ob sn

e

X CombComp n X

KCombComp n

SCombComp n

xvarCombComp n x

x y h h appCombComp n x y h h

X

The abstraction of all the variables of an extension

EAbstAlg n NOb n Ob

EAbstAlg nnatrec nObn Ob

Ob Ob hh

x h Obsx Ob h Obx Ob h AbstAlgx h

e

n

We need the denition of the application to all the indeterminates of an extension

Eapp n NOb Obn

Eapp nnatrec nOb Obn

Ob Ob hh

x h Ob Obsx h appsx

O x sx Ob Ob x h h

e

varsx put x

n

the two following terms make the pro of more readable

app n NOb Ob n

app n h Ob Obn Eapp n h

e

AbstAlg n NOb nOb

AbstAlg n h Obn Ob EAbstAlgn h

e

ObCC n NOb n X app n AbstAlg n X X

n n

ObCC nnatrec nObn X app n AbstAlg n X X

n n

Ob h app AbstAlg h h x x

x h Obsx

h app sx AbstAlg sx h h

sx sx

x sx

appsx

O x s x app x AbstAlg sx x

vars x put x

appsx

O x s x AbstAlgx x

vars x put x

x

sx

O x s x app x AbstAlg sx x

O x s x AbstAlgx x

var sx put x

T x

sx

app x AbstAlg x AbstAlgx x

AbstAlgx x

x

Obx

e

X app x AbstAlg x X X

x x

h

AbstAlgx x

ObCCx x

n

Typed Combinators

Types

types Set

atoms Set

at a atomstypes

types typestypes

types P types Set

e

atc a atomsP ata

ar r c types types P P P

h h

types

P

Type assignments

TA N Set

nil TA

cons n N ta TAn typesTA sn

TA P n NTA nSet

e

nil c P nil

consc n Nta TAn typesP n taP s n cons n ta

n N

ta TAn

P n ta

The typing of a variable

The sets corresp onding to the typed combinators First the set co ding the typing of a variable

in a type assignement

VarType n N ta TAnx ISn typesSet

PutType n Nta TAn typesVarTypes n cons n ta put n

InjectType n N

ta TAn

types

types

y ISn

p VarTypen ta y

VarTypesn cons n ta inject n y

VarType n N

e

ta TAn

P x ISsn

types

types

p VarType sn cons n ta x

Set

e typesP putn PutType n ta

d types

types

y ISn

p VarTypen ta y

P inject n y InjectType n ta y p

x ISsn

types

types

p VarTypesn cons n ta x

P x p

VarType n ta P e d put n PutType n ta e

e

VarType n ta P e d inject n y InjectType n ta y p d y p

e

The ob jects

ob n N ta TAn typesSet

K n N ta TAn types types

obn ta

S n Nta TAn types types types

ob n ta

var n N ta TAn typesx ISnp VarTypen ta x

obn ta

app n Nta TAn types typesf ob n ta a ob n ta

ob n ta

ob n N

e

ta TAn

P typesob n ta Set

k c types typesP K n ta

sc types types types

P Sn ta

v ar c typesx ISnp VarType n ta x P V ar n ta x p

appc types types

f obn ta

a ob n ta

f h P f

ah P aP app n ta f a

types

t obn ta

P t

ob n ta P k c sc v ar c appc Kn ta k c

e

ob n ta P k c sc v ar c appc Sn ta

e

sc

ob n ta P k c sc v ar c appc var n ta x p v ar c x p

e

ob n ta P k c sc v ar c appc app n ta f a

e

appc f a

ob n ta P k c sc v ar c appc f

e

ob n ta P k c sc v ar c appc a

e

We dene the identity combinator

I typesob n ta

I app n

ta

app n

ta

Sn ta

Kn ta

Kn ta

The injection of ob jects

The Injection of the ob jects of one theory into an extension with one more variable is realized

by the term

ObInj n N ta TAn types types t obn ta ob sn cons n ta

which is dened as

ObInj n ta tob n

e

ta

t obs n cons n ta del ta

K sn cons n ta

S sn

cons n ta

x p var sn

cons n ta

inject n x

InjectType n ta x p

f a h h appsn cons n ta h h

t

The formulae

form n Nta TAn typesSet

n N ta TAn typest ob n ta u obn ta form n ta

The theorems

n Nta TAn typeseq form n ta Set

In what follows we will use t u for n ta t u and eq for n ta eq as

nta nta

abbreviations

Keq n N

ta TAn

types

types

a ob n ta

b ob n ta

appn ta app n ta Kn ta a b a

nta nta

Seq n N

ta TAn

types

types

types

f obn ta

g ob n ta

a obn ta

appappappSn ta f g a appappf a app g a

nta nta

where I have removed all the type and context information from the applications to

make it more readable but it can b e restored by lo oking at the rules of ob ject formation

n N

ta TAn

types

types

f obn ta

g ob n ta

a obn ta

f g

nta nta

appn ta f a appn ta g a

nta nta

n N

ta TAn

types

types

a ob n ta

b ob n ta

f obn ta

a b

nta nta

appn ta f a appn ta f b

nta nta

n Nta TAn typest obn ta t t

nta nta

n Nta TAn typest obn ta u ob n ta

t u u t

nta nta nta nta

n Nta TAn typest obn ta u ob n ta v obn ta

t u u v t v

nta nta nta nta nta nta

The following derived rules were proved which are then used in the pro of of combinatorial

completeness

n N ta TAn

types types

f obn ta

g ob n ta

a obn ta

b obn ta

f g

nta nta

a b

nta nta

appn ta f a appn ta g b

nta nta

n ta f g a b h h n

ta

appn ta f a

appn ta g a

appn ta g b

n ta f g a h

n ta a b g h

IdEq n N ta TAn types a ob n ta

appn ta I n ta a a

nta nta

IdEq n ta a n

ta

appn ta I n ta a

app n ta

appn ta Kn ta a

appn ta K n ta a

a

Seqn ta K n ta K n ta a

Keq n ta a appn ta Kn ta a

Denition of Abstraction

The denition is by using the elimination rule for ob jects of a given type in a given extension

We dene separately each of the premisses of this rule and then plug these denitions into the

main one The typings of these terms are

KAbstAlg n Nta TAn types types types

obn ta

SAbstAlg n Nta TAn types types types types

ob n ta

VarAbstAlg n Nta TAn types types

x ISsn

p VarTypes n cons n ta x

ob n ta

AppAbstAlg n N ta TAn types types types

f obsn cons n ta

a obsn cons n ta

f h ob n ta

ah obn ta

ob n ta

And the typing of the abstraction algorithm

AbstAlg n Nta TAn types types

X ob sn cons n ta

obn ta

Now the terms that dene these constants

KAbstAlg n ta app n

ta

Kn ta

Kn ta

SAbstAlg n ta app n

ta

Kn ta

Sn ta

VarAbstAlg n ta x pVarType n

e

ta

x p ob n ta

I

y p app n

ta

Kn ta

varn ta y p

x

p

AppAbstAlg n ta f a f h ahapp n

ta

app n

ta

Sn ta

f h

ah

And the term for the abstraction algorithm which uses the terms ab ove

AbstAlg n ta X ob sn

e

consn ta

X obn ta

KAbstAlgn ta

SAbstAlgn ta

x p VarAbstAlgn ta x p

f a h h AppAbstAlgn ta f a h h

X

The combinatorial completeness

CombComp n ta X

appObInjAbstAlgXvar put n PutType n ta X

snconsnta snconsnta

where n N ta TAn types X ob sn cons n ta Some arguments were re

moved from the appObInj and AbstAlg

As with the denition of AbstAlg the term proving this statement is formed with ob so we will

e

prove the premisses of the rule b efore combining them The terms have the following typing

KCombComp n N ta TAn types types types

CombComp n ta Ksn cons n ta

SCombComp n N ta TAn types types types types

CombComp n ta

Ssn cons n ta

VarCombComp n N

ta TAn

types types

x ISsn

p VarType sn cons n ta x

CombComp n ta var s n cons n ta x p

AppCombComp n N ta TAn types types types

f obsn cons n ta

a ob sn cons n ta

f h CombComp n ta f

ah CombComp n ta a

CombComp n ta appsn cons n ta f a

The corresp onding terms are

KCombComp n ta Keq sn

cons n ta

Ksn cons n ta

varsn cons n ta put n PutType n ta

SCombComp n ta Keq sn

consn ta

Ss n cons n ta

varsn cons n ta put n PutType n ta

VarCombComp n ta x p

VarType n

e

ta

x p CombComp n ta

vars n cons n ta x p

IdEq sn cons n ta

varsn cons n ta putn PutType n ta

y p

Keq sn cons n ta

var sn cons n ta

injectn y InjectType n ta y p

var sn cons n ta putn PutType n ta

x

p

The case for application requires some denitions that make it more readable

fAbstn ta f ob n ta

fAbstn ta f AbstAlgn ta f

aAbstn ta a obn ta

aAbstn ta a AbstAlgn ta a

fAbstInjn ta f obsn cons n ta

fAbstInjn ta f ObInj n ta fAbstn ta f

aAbstInjn ta a obs n cons n ta

aAbstInjn ta a ObInj n ta aAbstn ta a

AppCombComp n ta f a f h ah

sn consn ta

app sn cons n ta

ObInjn ta

AbstAlg n ta

appsn cons n ta f a

varsn cons n ta put n PutTypen ta

app sn cons n ta

app sn cons n ta

fAbstInj

varsn cons n ta put n PutTypen ta

app sn cons n ta

aAbstInj

varsn cons n ta put n PutTypen ta

appsn cons n ta f a

Seq sn cons n ta

fAbstInj

aAbstInj

varsn cons n ta put n PutType n ta

sn cons n ta

appsn cons n ta

fAbstInj

var sn cons n ta put n PutTypen ta

f

appsn cons n ta

aAbstInj

var sn cons n ta put n PutTypen ta

a

f h

ah

ObCC n Nta TAn types types

X ob sn cons n ta

CombComp n ta X

ObCC n ta X ob sn

e

consn ta

X CombComp n ta X

KCombComp n ta

SCombComp n ta

x pVarCombComp n ta x p

f a h h AppCombComp n ta f a h h

X

Machine Checked Normalization Pro ofs

for Typed Combinator Calculi

draft

Veronica Gasp es

y

Jan M Smith

University of Goteborg and Chalmers University of Technology

June

Introduction

In this pap er we will present formalized normalization pro ofs of two calculi simply typed combi

nators and a combinator formulation of Godels T The pro ofs are based on Taits computability

metho d and are formalized in MartinLofs set theory NPS The motivation for do

ing these formalizations is to obtain machine checked normalization pro ofs The pro ofs in this

pap er have b een checked using the Alfsystem ACN in fact given pro ofs on the level of

formalization presented here it is a simple and straightforward task to have them veried in

the set theory implementation in Alf

The rst theory we will discuss the simply typed combinators is chosen b ecause of its

simplicity we want a machine checked pro of which avoids as much as p ossible syntactical

problems and concentrates on the computability metho d which has b ecome a standard to ol in

normalization pro ofs for typed theories

Tait treated a combinator formulation of Godels system T Although that is a

much more p owerful theory than the simply typed combinators the normalization pro of for

Godels T is from the formal p oint of view a straightforward extension of that for the simply

typed combinators

The pro ofs are done in MartinLofs set theory with the p ossibility of introducing families

of sets by induction All the inductive denitions we use are strictly p ositive and given the

introduction rules for such an inductively dened family an elimination rule expressing a

structural induction rule over the set introduced can b e obtained mechanically However

the implementation of MartinLofs set theory that we have used neither checks the strictly

p ositiveness of the introduction rules nor the correctness of the elimination rules

verocschalmersse

y

smithcschalmersse

The Simply Typed Combinators

The combinator calculus we will use is the one obtained by the CurryHoward interpration of

p ositive implicational calculus formulated in the Hilb ert style with the axioms

A B A

A B C A B A C

and with mo dus p onens as the only derivation rule So the types will b e built up from type

variables and the function arrow

X Y Z are types

If and are types then is a type

Corresp onding to the axioms we have for arbitrary types and constants K and S

with typings

K

S

Mo dus p onens corresp onds to application

M N

MN

We have the usual contraction rules in which we assume that all terms are of appropriate types

K MN M

S MNO MO NO

We will normalize a term by head reduction So we add the rule

M N

MO NO

and dene inductively what it means for a term to b e normalizable

K is normalizable

S is normalizable

K M is normalizable provided M is normalizable

S M is normalizable provided M is normalizable

S MN is normalizable provided M and N are normalizable

If M N and N is normalizable then M is normalizable

Intuitively it is clear that if a term is normalizable then it reduces to a term on normal form

that is to a term which do es not contain any subterm of the form K MN or S MNO

This can b e rigorously proved by dening the reduction as the transitive and symmetric

closure of the relation obtained by adding to the ab ove conversion rules

M N M N M N M N

K M K N S M S N S MO S NO S OM S ON

and by dening the normal forms inductively by

K is on normal form

S is on normal form

K M is on normal form provided M is on normal form

S M is on normal form provided M is on normal form

S MN is on normal form provided M and N are on normal form

The idea of dening normalizability directly by induction is due to MartinLof

Normalization Theorem for the Simply Typed Combinators

The pro of of the normalization theorem that is that every typable term is normalizable is by

Taits computability metho d The idea of this metho d is that the normalizability of a term M of

type is proved by induction on the derivation of M using a stronger induction hypothesis

namely that M is a computable term of type For the simply typed combinators the set of

computable terms of a type is inductively dened over the types by

There are no computable terms of a type variable

A term M is computable if

M is normalizable and

MN is computable of type provided N is computable of type

Note that from this denition it follows that a computable term is normalizable Hence the

normalizability theorem is an immediate corollary to the following theorem

Theorem If M then M is computable of type

In the pro of we need the following lemma which is easily proved by induction on the type

Lemma Let M and N be of type If M N and N is computable of type then M is

computable of type

The pro of of the theorem is by induction on the derivation of M We then have the following

cases

K

Since K is a term of an arrow type we have to prove by the denition of computability

that i K is normalizable and that ii K M is computable of type for all

computable M of type i follows from the denition of b eing normalizable For the

pro of of ii let M b e a computable term of type We have to show that K M is

normalizable and that K MN is computable of type for all computable N of type

Since M is computable M is normalizable hence by denition K M is normalizable

Since K MN M and M is assumed to b e computable lemma gives that K MN

is computable

S

The argument is similar to that for K Let M N and O b e arbitrary computable terms

of type and resp ectively The denition of computability gives that

MO and NO are computable terms of types and resp ectively By the denition

of computability MO NO is computable of type since S MNO MO NO

lemma gives that S is computable

Application

M N

MN

By the induction hypothesis M is computable of type and N is computable of

type The denition of computability for terms of type then gives that MN is

computable of type

Formalization of the normalization pro of

The formalization of the normalization pro of in MartinLofs set theory requires representations

of the typed combinators the relation of contraction of a head redex and of the predicates of

normalizability and computability All these are dened as sets either by introducing a new

set by an inductive denition or in the case of the computability predicate by recursion on the

type structure of the combinators using the universe of MartinLofs set theory

The simply typed combinators are introduced by a set Type for the types and a family Term

of sets over Type such that the elements in Term are the terms of type The contraction

of the head redex is expressed by a family of sets OneStepHead M N where M and N are

terms of type such that N is obtained by contracting the head redex of M

We follow the notation in NPS

The set of types

We rst declare Type to b e a set

Typeformation

Type Set

The set Type is inductively generated and there are two introduction rules one for the atomic

sets that is the type variables and one for the function types We let the type variables b e

indexed by some given set Atom which could for instance b e the set of natural numbers

Typeintroduction

a Atom

vara Type

Typeintroduction

Type Type

Type

The elimination rule expresses structural induction on the set Type

Typeelimination

P u Set u Type

b P var a a Atom

i I I P Type I P I P

Type

TypeRecP b i P

A step in the informal pro of by induction on the types will b e formalized by an application of

Typeelimination

The family of sets of terms

Term is declared to b e a family of sets over the types

Term formation

Term Set Type

The family is dened inductively by introduction rules which corresp ond to the formation of

the typed combinators

Term introduction

Type

K Term

Term introduction

Type

S Term

Term introduction

Type

M Term

N Term

App M N Term

In the sequel we will often omit the type arguments in the constructor App since they can b e

obtained from the types of the other arguments The elimination rule completes the denition

by expressing structural induction on the family Term

Term elimination

P u v Set u Type v Term u

k x y P x y z K x y x y Type

sx y z P x y z x y x z S x y z x y z Type

x y Type

u Term x y

v Term x

apx y u v I I P y Appu v

u v

I P x y u

u

I P x v

v

Type

M Term

TermRec P k s ap M P M

When informally a statement is proved by induction on the derivation of t the formal

pro of is by an application of Term elimination

The family of sets expressing head contraction

OneStepHead is declared to b e a family of sets over types and terms

OneStepHead formation

OneStepHead M N Set Type M N Term

The set OneStepHead M N expresses that N results from contracting the head redex of

M thus it is dened by the following introduction rules

OneStepHead introduction

Type M Term M Term

kk M N OneStepHead AppAppK M N M

OneStepHead introduction

Type M Term N Term O Term

ss M N O

OneStepHead App AppAppS M N O App AppM O App N O

OneStepHead introduction

Type M N Term O Term p OneStepHead M N

M N O p OneStepHead App M O AppN O

The elimination rule for this inductive denition of OneStepHead will not b e used in the

normalization pro of and we refrain from formulating it

The family of sets formalizing normalizability

The family Norm is introduced for the pro ofs that a term of a given type is normalizable

Norm formation

Norm M Set Type M Term

The introduction rules corresp ond to the clauses in the inductive denition of the set of

normalizable terms of a given type

Norm introduction

Type

kn Norm K

Norm introduction

Type

sn Norm S

Norm introduction

Type M Term M Norm M

n

kan M M Norm App K M

n

Norm introduction

Type M Term M Norm M

n

sfn M M Norm AppS M

n

Norm introduction

Type

M Term

N Term

M Norm M

n

N Norm N

n

sfgn M N M N Norm AppAppS M N

n n

Norm introduction

Type M N Term p OneStepHead M N N Norm N

n

mrn M N p N Norm M

n

The elimination rule for Norm will not b e used in the pro of

The family of sets for the computability predicate

The computability predicate

Comp M Set Type M Term

should satisfy the equations

Comp vara M a Atom M Term vara

Comp M Norm M N Term Comp N Comp App M N

The denition of Comp is by recursion on the type structure either by using a universe or

directly by set valued recursion Using the notation in NPS the denition of Comp using

a universe would b e

\

Comp SetComp

where

\

Comp TypeRecv Term v U atB aseC aseat I I Ar r ow C ase I I

b

B aseC aseat M

b

[ [

b

Ar r ow C ase I I M Norm M N Term I N c I AppM N

The denition of the computability predicate using the approach in would b e the same except

that no co ding would b e involved In fact in the implementation of the pro of in Alf we wrote

the two dening equations for Comp directly using pattern matching in fact this approach

makes the equations for the computability predicate denitional

The formal normalization pro of

The prop osition expressing that every typable term is normalizable can now b e formulated in

MartinLofs set theory by

Typet Term Norm t

The formalization of the pro of of the normalization theorem consists in deriving an element in

this set Such an element is built up by applying a pro of of

Typet Term Comp t Norm t

to a pro of of

Typet Term Comp t

The rst of these statements which in the informal presentation of the pro of was assumed

to b e a direct consequence of the denition of computability requires an explicit pro of in the

formalization the pro of is by induction on the type ie by Typeelimination

The second statement is proved by induction on the derivation of t Term ie by

Term elimination using the lemmata

Typet u Term OneStepHead t u Comp u Comp t

and

Typef Term a Term

Comp f Comp a Comp App f a

The rst lemma was proved by induction on and the second is an immediate consequence of

the denition of Comp f

Instead of presenting the pro ofs in the tree like fashion that results from the natural deduc

tion style used ab ove when formulating the inference rules we will express these rules in the

logical framework as functions For example the introduction rule for normalizability

Type M N Term p OneStepHead M N N Norm N

n

mrn M N p N Norm M

n

is expressed by the function

mrn TypeM N Term p OneStepHead M N N Norm N Norm M

n

We refer to NPS for expressing rules in the logical framework

Formally the normalization theorem is proved by the term

AllNorm Type t Term Norm t

AllNorm t applyComp t

Norm t

apply Term

aComp a Norm a

lemma

t

AllComp t

Removing all set parameters this term b ecomes

AllNorm t applyapplylemma t AllComp t

We will often use this convention of hiding the set parameters of the constants

The term AllComp proves that every term is computable by induction on the denition

of b eing a term in a given type and the term lemma proves that every computable term is

normalizable by induction on the types

lemma TypeTerm tComp t Norm t

lemma TypeRec aTerm a tComp a t Norm a t

atx cx v Norm varat x cx

e

h h f cf fstcf

AllComp Typet Term Comp t

AllComp t TermRec uComp u

Kcomp

Scomp

f b h h App comp f b h h

f b f b

t

The denition of AllComp requires the denitions of Kcomp Scomp and App comp which re

sp ectively prove that K S and Appf a are computable We will here only give the denition

of App comp the denitions of the other two are somewhat longer reecting that the pro ofs of

the computability of K and S are slightly more complicated

App comp Type

f Term

a Term

cf Comp f

ca Comp a

Comp App f a

App comp f a cf caapply applysndcf a ca

An example

As an illustration of the computational content of the formal pro of we will show the pro of

ob ject for the normalizability of the combinator I I I where I is the identity function

on the type and is an atomic type Omitting the type information in the combinators K

and S the identity function is dened by

I SKK

and the head reduction to normal form of I I I is

SKKS KKSKK KSKK SKKK SKKSKK

SKKSKK K SKKK SKK SKK I

This reduction sequence will app ear in the pro of term

For the formal pro of we need an element i Atom and the dene to b e var i The

combinators I I and I I I are introduced by the explicit denitions

I Term

I AppAppS K K

I Term

I AppAppS

K

K

and

I I I Term

I I I App I I I

resp ectively Both in these denitions and in the pro of term b elow many type arguments of the

constants have b een removed for the sake of readability

The pro of of the normalizability of I I I is by showing that the terms to which

I I I head reduces are normalizable hence the pro of consists of the series of terms in

the reduction together with pro ofs of these reductions and pro ofs that the corresp onding terms

are normalizable

Substituting and I I I for and t resp ectively in AllNorm t and unfolding

denitions we obtain

AllNorm I I I Norm I I I

AllNorm I I I

mrn I I I

AppAppK I I AppK I I

ssK K I I

mrn AppAppK I I AppK I I

I I

kkI I AppK I I

mrnI I

AppAppK I AppK I

ssK K I

mrn AppAppK I AppK I

I

kk I AppK I

sfgnK K kn kn

Extracting the normal form from the pro of

In the ab ove example we have seen that when the pro of of the normalizability theorem is applied

on a combinator the normal form app ears in the pro of We will now dene a function

extraction Typet Term p Norm tTerm

that from a pro of p of the normalizability of a given combinator extracts the the normal form of

the combinator The function will b e dened by induction on the normalizability of the term

The cases that corresp ond to the denition by elimination of the set Norm applied to p are

extraction K kn K

extraction S sn S

extraction AppK a kan a p

AppK extraction a p

extraction

AppS f

sfn f p

AppS extraction f p

extraction

AppAppS f g

sfgn f g p q

AppAppS extraction f p extraction g q

extraction t mrn t u p q extraction u q

This extraction function may then b e applied to the pro of AllNorm of the normalizability of

all terms thus we obtain an algorithm that computes the normal form of a term

nf textraction t AllNorm t Typet Term Term

Godels System T

A combinator formulation Godels system T of computable functionals is obtained from

the theory of the simply type combinators by replacing the type variables by the set N of natural

numbers The terms are then obtained by deleting the type variables and adding

N

s NN

R N N

The contraction relation is extended by the rules of the recursion op erator

R MN M

R MN sT N R MNT T

O P

R MNO R MNP

To the denition of the set of normalizable terms we add the following clauses

is normalizable

s is normalizable

sM is normalizable provided M is normalizable

R is normalizable

R M is normalizable provided M is normalizable

R MN is normalizable provided M and N are normalizable

Normalization Theorem for Godels System T

To obtain a pro of of the normalizability theorem for Godels T from the pro of for the simply

typed combinators we have to change the denition of the computability predicate in the

atomic case For the simply typed combinators the atomic case was empty now it is the set of

computable natural numbers

is computable of type N

sM is computable of type N provided M is computable of type N

If M N and N is computable of type N then M is computable

Formally the set of computable natural numbers is introduced by inductively dened family

CompN

CompN Formation

CompN M Set M Term N

CompN Introduction

zComp CompN

M Term N p CompN M

sComp M CompN sM

M N Term N p OneStepHeadM N N q CompN N

mrComp M N p q CompN M

CompN Elimination

P u v Set u Term N v CompN u

z z P zComp

ssx y z P s x sComp x x Term N y CompN x z P x y

x y Term N

u OneStepHeadx y N

mr cx y u v I P x mrComp x y u v

y

v CompN y

I P y v

y

M Term N

cn CompN n

CompNRec P z z ss mr c M cm P n cm

Similarly to the case of the simply typed combinators the computability predicate is dened

so that it satises the equations

Comp N M CompN M M Term N

Comp M

Norm M N Term Comp N Comp App M N

To the pro of that every simply typed combinator is computable we must add the cases

N which is computable outright

s NN Since s is in an arrow type we must show that i s is normalizable which

follows immediately from the denition of normalizability and that ii sM is computable

of type N for an arbitrary computable M of type N which follows from one of the clauses

dening computability of type N

R N N Since R is in a function type we must b e show that i R is

normalizable which it is by denition of normalizability and that ii R M is computable

of type N N for arbitrary computable M of type The pro of of ii is by

taking an arbitrary M computable of type and showing that iii R M is normalizable

which follows from the computability of M and iv R MN is computable in N for

arbitrary N computable of type N Again the pro of is by taking an arbitrary

computable N of type N and show that v R MN is normalizable which it is

b ecause b oth M and N are computable and vi R MNO is computable of type for

arbitrary O computable of type N The pro of of vi is by induction on the computability

of type N of O thus it has to b e proved that

R MN is computable of type which follows from R MN M

R MN sP is computable of type which is a consequence of

R MN sP N R MNP P

where the computability of N R MNP P follows from the induction hypothesis

and the computability of N and P

R MNP is computable of type where P Q and Q is computable of type

N The induction hypothesis gives that R MNQ is computable of type hence

R MNP R MNQ gives the result

Let R b e the formal constant expressing the recursion op erator let Rn Ran and Rain b e the

constants introduced in the inductive denition of normalizability let Rzr Rsr and Rtn b e the

constants introduced in the inductive denition of one step head reduction The following is

the formal pro of that R is computable

RComp TypeComp N N R

RComp

pairRn

a capair Ran a lemma a ca

i cipair Rain a i lemma a ca lemma N i ci

ncnRComp

where RComp which is introduced only for the sake of readability is the term which realizes

the induction on cn ie the computability of n

CompNRec t ctComp App AppAppR a i t

lemma App AppAppR a i a Rzr a i ca

t ct hlemma

AppAppAppR a i App s t

AppAppi App AppAppR a i t t

Rsr a i t

lemma a i t ci ct h

t u mr ct hlemma

AppAppAppR a i u

AppAppAppR a i t

Rtn a i t u mr

h

n

cn

In the pro of the terms lemma lemma lemma are pro ofs which are the same as for the simply

typed calculus of

lemma Type a Term ca Comp aNorm a

lemma Type

t Term

u Term

OneStepHead t u

Comp u

Comp t

lemma Type

a Term

i Term N

t Term N

ci Comp N i

ct CompN t

h Comp AppAppAppR a i t

Comp App Appi AppAppAppR a i t t

References

L Augustsson T Co quand and B Nordstrom A short description of Another Logical

Framework In Proceedings of the First Workshop on Logical Frameworks Antibes pages

Thierry Co quand and Christine Paulin Inductively dened types In Proceedings of

COLOG number in Lecture Notes in Computer Science SpringerVerlag

Peter Dyb jer Inductive sets and families in MartinLofs type theory and their settheoretic

semantics In G Huet and G Plotkin editors Informal Proceedings of the First Workshop

on Logical Frameworks pages Esprit Basic Research Action May To

app ear in G Huet and G Plotkin editors Logical Frameworks

Kurt Godel Ub er eine bisher no ch nicht b enutze erweitrung des niten standpunktes

Dialectica

Per MartinLof Hauptsatz for the Intuitionistic Theory of Iterated Inductive Denitions

In J E Fenstad editor Proceedings of the Second Scandinavian Logic Symposium pages

NorthHolland Publishing Company

Per MartinLof Intuitionistic Type Theory Bibliop olis Nap oli

Bengt Nordstrom Kent Petersson and Jan M Smith Programming in MartinLofs Type

Theory An Introduction Oxford University Press

L Sanchis Functionals dened by recursion Notre Dame Journal of Formal Logic

Jan M Smith Prop ositional Functions and Families of Types Notre Dame Journal of

Formal Logic

W W Tait Intensional interpretation of functionals of nite type I Journal of Symbolic

Logic

Inductive and Coinductive types with Iteration and Recursion

y

Herman Geuvers

Faculty of Mathematics and Computer Science

University of Nijmegen

Toerno oiveld

ED Nijmegen

The Netherlands

July

Abstract

We study extensions of simply and p olymorphically typed lambda calculus from a

p oint of view of how iterative and recursive functions on inductive types are represented

The inductive types can usually b e understo o d as initial algebras in a certain category and

then recursion can b e dened in terms of iteration However in the syntax we often have

only weak initiality which makes the denition of recursion in terms of iteration inecient

or just imp ossible We prop ose a categorical notion of primitive recursion which can easily

b e added as computation rule to a typed lambda calculus and gives us a clear view on

what the dual of recursion corecursion on coinductive types is The same notion has

indep endently b een prop osed by Mendler We lo ok at how these syntactic notions

work out in the simply typed lambda calculus and the p olymorphic lambda calculus It

will turn out that in the syntax recursion can b e dened in terms of corecursion and vice

versa using p olymorphism Polymorphic lambda calculus with a scheme for either recursion

or corecursion suces to b e able to dene the other We compare our syntax for recursion

and corecursion with that of Mendler Mendler and use the latter to obtain meta

prop erties as conuence and normalization

Introduction

In this pap er we want to lo ok at formalizations of inductive and coinductive types in dier

ent typed lambda calculi mainly extensions of the p olymorphic lambda calculus It is well

known that in p olymorphic lambda calculus many inductive data types can b e dened see

egBohm and Berarducci and Girard et al In this pap er we want to lo ok at how

functions on inductive types can b e represented Therefore two ways of using the inductive

building up of a type to dene functions on that type are b eing distinguished the iterative

way and the recursive way An iterative function is dened by induction on the building up of

the type by dening the function value in terms of the previous values A recursive function

is also dened by induction but now by dening the function value in terms of the previous

values and the previous inputs For functions on the natural numbers that is h Nat A

with h c hn f hn for c A f A A is iterative and h Nat A with

Extended notes of a talk given at the BRALF meeting in Edinburgh May

y

hermancskunnl

h c hn g hn n for c A g A Nat A is recursive If one has pairing

the recursive functions can b e dened using just iteration which was essentially already shown

by Kleene But if we work in a typed lambda calculus where pairing is not surjective

this translation of recursion in terms of iteration b ecomes inecient and sometimes imp ossible

Moreover if the calculus also incorp orates some predicate logic one would like to use the in

ductivity in doing pro ofs which is not always straightforward or just imp ossible We shall not

go into the latter topic here there is still a lot of work to b e done in relating the work presented

here to systems like AF by Krivine and Parigot connections may b e found in Parigot

and Co q Dowek ea

This asks for an explicit scheme for recursion in typed lambda calculus which yields for

say the natural numbers the scheme of Godels T To see how this can b e done in general

for inductive types we are going to dene a categorical notion of recursion just like initial

algebra categorically represents the notion of iteration One of the tradeos is that we can

dualize all this to get a notion of corecursion on coinductive types These categorical notions of

recursion and corecursion have indep endently b een found by Mendler see Mendler who

treats these constructions in MartinLof type theory with predicative universes What we dene

as corecursive coalgebras are what Mendler calls coalgebras that admit simple primitive

recursion We shall always use the term recursion b ecause although the functiondenition

scheme has a strong avour of primitive recursion one can dene many more functions in

p olymorphic lambda calculus then just the primitive recursive ones Coinductive types were

rst describ ed in Hagino a and Hagino b with only a scheme for coiteration and

without corecursion Here we give a quite straightforward extension of simply typed lambda

calculus with recursive and corecursive types

A very surprising result is that in a p olymorphic framework if we have a notion of recursive

types which reects our notion of recursive algebra then we can dene corecursive types that

corresp ond to corecursive coalgebras By duality this also works the other way around This

result will b e given here syntactically We dene a p olymorphic lambda calculus with recursive

and corecursive types that straightforwardly represents the categorical notions of recursive

algebra and corecursive coalgebra and show that the scheme for recursive types can b e dened

from the scheme for corecursive types and vice versa We also lo ok at a system of recursive and

corecursive types dened by Mendler and show that with either the scheme for recursive

types or the scheme for corecursive types there is a recursive algebra and a corecursive

coalgebra in the syntax for every syntactic functor where syntactic functors are p ositive type

schemes

The categorical p ersp ective

As said we shall get our intuitions ab out inductive and coinductive types from the eld of cate

gory theory The main notions in category theory related to this issue come from Lambek

Denition Let C be a category T a functor from C to C

A T algebra in C is a pair A f with A an object and f TA A

If A f and B g are T algebras a morphism from A f to B g is a morphism

h A B such that the fol lowing diagram commutes

f

A TA

h T h

TB B

g

A T algebra A f is initial if it is initial in the category of T algebras ie for every

T algebra B g theres a unique h which makes the above diagram commute

In a category with pro ducts copro ducts and terminal ob ject the initial algebra of the

functor TX X is the natural numbers ob ject for which we write Nat Z S The initial

algebra of TX A X is the ob ject of nite lists over A List Nil Cons In this pap er

A

our p etexample of an initial algebra will b e Nat Z S which will b e used to illustrate the

prop erties we are interested in First take a lo ok at how the iterative and recursive functions

can b e dened on Nat The example immediately generalizes to arbitrary initial algebras

Example For g B B we write g for g in B and g for g in B B

The iteratively dened morphism from g g Elimg g is dened as the unique morphism

h which makes the diagram commute ie h Z g and h S g h

For g B g B Nat B the recursively dened morphism from g and g is

constructed as fol lows

There exists a unique h which makes the diagram

Z S

Nat Nat

h id h

B Nat B Nat

h g g Z S i

i id h If we write h h and Z S commute That is h Z S h g g

h h we have the equalities

h Z g

h S g h

h Z Z

h S S h

Now h id by uniqueness and also h hh h i so

N at

h Z g

h S g hh idi

So h satises the recursion equalities and we dene

Recg g h

Denition Let C be a category T a functor from C to C

A T coalgebra in C is a pair A f with A an object and f A TA

If A f and B g are T coalgebras a morphism from B g to A f is a morphism

h B A such that the fol lowing diagram commutes

g

B TB

T h h

A TA

f

A T coalgebra A f is terminal if it is terminal in the category of T coalgebras ie for

every coalgebra B g theres a unique h which makes the above diagram commute

Our p et example for terminal coalgebras is the one for TX Nat X the ob ject of innite

lists of natural numbers for which we write Stream hH Ti We shall dualize the notions of

iterative and recursive function to get coiterative and corecursive functions to Stream Again

this example easily generalizes to the case for arbitrary terminal coalgebras

Example For g B Nat B write g for g B Nat and g for g B B

The coiteratively dened morphism from g and g Introg g B Stream is the unique

morphism h for which the diagram commutes That is H h g and T h h g

If j is a morphism from Nat to Nat one can dene the morphism from Stream to Stream

which applies f to every point in the stream as Introj HT Note that it is not so

straightforward to dene coiteratively a morphism which replaces the head of a stream

by say zero This however can easily be done using corecursion

For g B Nat g B B Stream the corecursively dened morphism from g

and g Corec g g is dened by h in where h is the unique morphism which makes the

diagram

hg g i hH in Ti

Nat B Stream B Stream

h id h

Nat Stream Stream

hH Ti

commute If we write h h in h h in then we have for h the fol lowing equations

H h H

T h h T

H h g

T h h g

Now h id by uniqueness and also h h h so

H h g

T h h id g

These are the equations for corecursion if g B Nat and g B B Stream then

j B Stream is corecursively dened from g and g if H j g and T j j id g

The function ZeroH Stream Stream which changes the head of a stream into zero

can now be dened as ZeroH Corec Zin T where is the unique morphism from

Stream to Informal ly Z is of course just s Stream

As usual in categorical denitions the denitions of initial algebra and terminal coalgebra

split up in two parts the existence part theres an h such that and the uniqueness part

the h is unique In the following we shall sometimes refer to these two parts of the denition

as the existence property and the uniqueness property

In the typed lambda calculi that we shall consider the inductive and coinductive types will

not exactly represent initial algebras and terminal coalgebras What the systems are lacking

is the uniqueness prop erty for the morphism h in resp ectively Algebras resp ectively

coalgebras which only satisfy the existence prop erty are called weakly initial resp ectively weakly

terminal

Denition For T an endofunctor in a category C The T algebra respectively T coalgebra

A f is weakly initial respectively weakly terminal if for every T algebra respectively T

coalgebra B g there exists an arrow h that makes the diagram in respectively com

mute

Remark The notion of weakly initial algebra is really weaker than that of initial algebra

For example in the category Set Z S is a weakly initial X X algebra but also

Z S with S n Sn S n n is On weakly initial algebras the behaviour of

morphisms is only determined on the standard part of the algebra that is in settheoretic terms

those elements that are constructed by nitely many times applying the constructor f Initiality

says that the algebra is standard

As we made serious use of the uniqueness prop erty in constructing the recursive and core

cursive functions its interesting to see how much we can do in weak initial algebras and weak

terminal coalgebras The construction of the iterative and coiterative functions of examples

and can b e done in the same way we only lo ose the uniqueness prop erty of the iteratively

dened function The construction of recursive and corecursive functions in a weak framework

is not so straightforward We shall study again the examples of natural numbers and streams of

natural numbers Fix a category C which has weak pro ducts and copro ducts So we do have

t in t but not h t ti t and t in t in eg ht t i t and t t

It will turn out that weak pro ducts and copro ducts will cause some extra restrictions on the

denability of functions Therefore we shall also study what happ ens if pro duct and copro duct

are semi that is for pro ducts hf g i h hf h g hi and for copro ducts h f g h f h g

The reason for not considering the strong pro ducts and copro ducts in these examples is that

in the syntax of typed lambda calculi pro duct and copro duct are usually weak or semi The

notions of semi pro duct and semi copro duct are taken from Hayashi

Example Recursion on a weak natural numbers object Let Nat be a weakly initial X

X algebra Consider the diagram in where we dened recursion in terms of iteration and

let h Nat B Nat be some morphism that makes the diagram commute ie

h Z S h g g Z S i id h

Applying projections to the left and injections to the right of the equation we obtain the fol lowing

equalities where h h and h h

h Z g

h S g h

h Z Z

h S S h

Nat doesnt satisfy the uniqueness properties so not necessarily h id but only

N at

n n

h S Z S Z

n

for every n N where S denotes an nfold composition of S Now we would like to deduce

h Z g

n n

h S Z g hh idi S Z

which says that h satises the recusion equations for the standard natural numbers

For weak products this conclusion is only valid if g k for some k B B or

i

k Nat B Note that if g k for some k B B then h is just iteratively

dened from g and k so only the case for g k gives us really new functions for

instance the predecessor

For semi products this conclusion is only valid for g k h i for some k B Nat

B which is not a serious restriction Just replace g by g h i

Example Corecursion on a weak stream object Let Stream be a weakly terminal X Nat

X coalgebra Consider the diagram in where we dened corecursion in terms of coiteration

and let h B Stream Stream be some morphism that makes the diagram commute Write

h h in and h h in We have the fol lowing equalities

H h H

T h h T

H h g

T h h g

Now we can not conclude h in id because we dont have uniqueness but we do have

n n

H T h H T

that is h is the identity on the standard part of the stream those points that can be obtained

by nitely many applications of H or T Again we would like to conclude

H h g

n n

H T h H T h id g

that is h satises the corecursion equations for the standard part of the stream

For weak coproducts this conclusion is only valid if g in k for some k B B or

i

k B Stream Note that if g in k for some k B B then h is just coiteratively

dened from g and k so only the case for g in k gives us really new functions like

for instance the function ZeroH

k for some k B For semi coproducts this conclusion is only valid if g in in

g B Stream again this is not a serious restriction Just replace g by in in

For the morphism ZeroH Stream Stream which replaces the head by zero dened in by

Corec Zin T we now have for either weak or semi coproducts

H ZeroH Z

n n

H T ZeroH H T

so ZeroH works ne on the standard part of the stream That one can not in general dene a

morphism ZeroH such that T ZeroH T wil l be shown later when we look at these examples

in polymorphic lambda calculus which is an instance of a category with weakly initial algebras

and weakly terminal coalgebras semi products and weak coproducts

Remark With strong products and coproducts we would have similar problems in dening

recursion and corecursion The recursion equations would only be valid for the standard natural

numbers and the corecursion equations would only be valid for the standard part of streams The

only advantage would be that the g B Nat B respectively the g B B Stream can

be taken arbitrarily

In Section the p olymorphic lambda calculus will b e considered in which inductive and

coinductive types can b e dened which corresp ond to weakly initial algebras and weakly terminal

coalgebras It will b e shown that recursion in that calculus is problematic from a p oint of view of

eciency One solution could b e to strengthen the reduction rules to get a stronger extensional

equality However its not p ossible to add some relatively easy reduction rules to the syntax

to obtain the uniqueness prop erty of initiality and terminality We cant say in an easy way

that the only ob jects of a structure are the standard ones This is b ecause the equality of

primitive recursive functions can not b e decided by an easy decidable equality We can do

something dierent namely say that our functions should b ehave on the nonstandard part as

they b ehave on the standard part Categorically this can b e obtained by strengthening the

notion of weakly initial algebra and weakly terminal coalgebra a little bit such that recursion

works That is for N for c A g A Nat A there is a function h Nat A with h c

and hn g hn n These new notions will b e called recursive algebra and corecursive

coalgebra The denitions are not dicult if one understands what makes it p ossible to dene

corecursion in terms of coiteration

Let in the following C b e a category with weak pro ducts and weak copro ducts and T a

functor from C to C

Denition A f is a recursive T algebra if A f is a T algebra and for every g

T X A X there exists an h A X such that the fol lowing diagram commutes

f

TA A

T hh id i h

X T X A

g

Notice that this is the same as saying that A f is weakly initial and that moreover in the

diagram for dening recursion in terms of iteration h id See

Denition A f is a corecursive T coalgebra if A f is a T coalgebra and for every

g X T X A there exists an h X A such that the fol lowing diagram commutes

g

T X A X

h T h id

TA A

f

Again this is the same as saying that A f is a weakly terminal T coalgebra and that

moreover in the diagram for dening corecursion in terms of coiteration h id See

When talking ab out weakly initial or recursive T algebras and weakly terminal or corecursive

T coalgebras it is convenient to denote the h that makes the diagram commute as a function of

g So we shall denote a weakly initial T algebra by A f Elim where Elimg denotes a morphism

h in that makes the diagram commute Similarly we write A f Intro for a weakly terminal

T coalgebra A f Rec for a recursive T algebra and A f Corec for a corecursive T coalgebra

Examples If Nat Z S Rec is a recursive X X algebra Rec is a recursor

on Nat For g g X Nat X

Z g Rec g g

Rec g g S g hRec g g id i

so Rec g g is the recursively dened function from g and g We can dene P

and we have Rec Z

P Z Z

P S id

If Stream hH Ti Corec is a corecursive X Nat X coalgebra Then for hg g i X

Nat X Stream the function Corec hg g i satises

H Corec hg g i g

T Corec hg g i Corec hg g i id g

so Corec hg g i is the corecursively dened function from g and g We can dene

ZeroH Corec hZ in Ti

with

H ZeroH Z

T ZeroH T

Extending simply typed lambda calculus with inductive and

coinductive types

In his thesis Hagino a Hagino derives from the notions of initial algebra and terminal

coalgebra an extension of simply typed lambda calculus which he calls categorical data types

This amounts to adding two schemes for dening a new type from a covariant functor from

types to types In the notation of these schemes b elow we follow Wraith These new

types come together with some constants and reduction rules A covariant functor from types

to types in is a positive type scheme that is a type in which the free variable

o ccurs positively The type variable o ccurs positively in the type if FV

or if and o ccurs negatively in p ositively in The type variable o ccurs

negatively in if FV or if and o ccurs negatively in p ositively

in If is a type scheme with we mean the type with substituted for If

theres no ambiguity to which type variable were referring we just write in stead of

A p ositive resp ectively negative type scheme can b e applied to a function f ob

taining f resp ectively f by lifting f f if FV

f id and if o ccurs negatively in p ositively in then

f x y f x f y

f x y f x f y

Denition Let be types in the simply typed lambda calculus in which the

n

typevariable occurs positively The sum scheme for constructing data types is the fol lowing

sum with constructors

c

c

c

n n

end

A declaration of a type using this sum scheme gives rise to an extension of the language of

with

a closed type

constants c for i n

i i

for every type Elim

n

The reduction relation is extended with the rule

Elim M M M c t M Elim M M t

n i i i n

An easy example of a type dened by the sum scheme is for and types representing

the the disjoint sum of and

sum with constructors

inl

inr

end

with inl inr and for M M M M

The sequence of type schemes in the sum scheme can also b e empty allowing us to dene

the unit type by

sum with constructors

end

We have and for any t t with t t

Denition Let be types in the simply typed lambda calculus in which the

n

typevariable occurs positively The pro duct scheme for constructing new data types is the

fol lowing

pro duct with destructors

d

d

d

n n

end

A declaration of a type using this product scheme gives rise to an extension of the language

of with

a closed type

constants d for i n

i i

for every type Intro

n

The reduction relation is extended with the rule

d Intro M M M t Intro M M M t

i n i n i

The straightforward example of a type dened by the pro duct scheme is for and

types representing the the pro duct of and

pro duct with destructors

fst

snd

end

with fst snd and for M M M M

Remark The type dened by the sum scheme from wil l be denoted by

n

The type dened by the product scheme from

n n

wil l be denoted by This is also how these types should be read as

n

weakly initial algebras of TX X X and weakly terminal coalgebras of

n

TX X X respectively So dualising is of course not the same as reversing

n

al l the arrows in a sum scheme to obtain a product scheme

ind

Denition is the simply typed lambda calculus extended with sum scheme and

product scheme

Example The iterative functions on an inductive type can be straightforwardly dened by

the Elim construct Write Nat for then for c and f Elimz cf Nat

is the iteratively dened function from c and f The recursive functions can be dened by

translating recursion in terms of iteration as is done in For c g Nat dene

Reccg fst Elimz hc ihxg fst xsndx S sndi and we have

Reccg c

n n n

Rec cg S g Rec cg S sndElimz hc ihxg fst xsndx S sndiS

n

This recursor only works for terms of type Nat which are of the form S but moreover it

is quite inecient compared to for instance the recursor in Godels T

Prop osition The predecessor function of type Nat Nat dened in terms of iteration in

ind

computes the predecessor of a numeral n in n steps

Pro of The predecessor function P is the normal form of Recxy y so

P fst Elim z h ihsnd S sndi

Nat Nat

Now

n n

P S sndElimz h ihsnd S sndiS

sndElimz h ihsnd S sndi

and with induction one proves that

n n

sndElimz h ihsnd S sndiS S sndElimz h ihsnd S sndiS

ind

Prop osition In there is no term P Nat Nat with

P S and

P S x x

for x a variable of type Nat

ind

Pro of This follows by the ChurchRosser prop erty for reduction in See Hagino b

If P S x x then P S x x Analyzing the p ossible structure of P one can conclude that

if P S x x then not at the same time P S This prop osition is also an immediate

corollary of the same prop osition for system F in

ind

If one tries to do corecursion on the coinductive types in a similar situation o ccurs

For Stream Nat one can dene ZeroHStreamStream which replaces the head by

using the denable corecursion in weakly terminal coalgebras We do not have T ZeroHs T s

n n

for s a Stream but just H ZeroHs and H T ZeroH s H T s One can also show

that there can b e no term ZeroH StreamStream such that T ZeroHs s for a variable

sStream Using the ChurchRosser prop erty or as a corollary of the same prop osition for

system F

There are of course ways to strengthen the equalities of the sum and pro duct scheme to get

real recursion and corecursion The initiality can b e restored totally by adding the conditional

rewrite rule

If hc t M ht for i n and M and t of appropriate type then h Elim M M

i i i i n

However conditional rewrite rules are metatheoretically very complicated the rewriting de

p ends on the typing and on the previously generated equality Another alternative which

restores part of the unicity is to add a rewrite rule

E l im c c I d

n

for

sum with constructors

c

c

c

n n

end

This is not enough to obtain a recursive algebra b ecause the Elim constructor do esnt auto

matically commute with pairing One has to add

snd Elim hg c sndi hg c sndi Elim c c

n n n n

n N

In the pro of of Prop osition we then have that Rec xy y S S in a constant

number of steps In this case it is of course b etter to take and if we add similar rules

for the pro duct scheme as primitive type constructors The new reduction rule is not a very

pretty one

We can also follow the categorical denitions of recursion and corecursion and strengthen

the sum and pro duct schemes themselves Again it is b est to take and as primitives For

the sum scheme this would lead to the type with the same constructors and further

for every type Rec

n

the reduction rule Rec M M M c t M hRec M M idit

n i i i n

For the pro duct scheme we would also get the same type with the same destructors and

further

for every type Corec

n

the reduction rule d Corec M M M t id Corec M M M t

i n i n i

ind r ec

Call the system with mo died sum and pro duct scheme as ab ove Without pro of

we give the following prop osition

r ec

Prop osition In the system the inductive types are recursive algebras and the coin

ductive types are corecursive coalgebras For the appropriate functors

The p olymorphic lambda calculus

We just give the rules to x our notation and shall not go into the system further assuming

it is familiar We write and for the denable weak pro duct and copro duct

and We could also have added and

as new type constructors with extra rules turning them into a weak pro duct and copro duct

This however is inconvenient The added and would not b e functorial eg Types

TypesTypes do es not preserve identities and comp osition whereas the denable and

are functorial by construction if we assume an reduction rule See Denition and the

discussion

Denition The set of types of F T is dened by the fol lowing abstract syntax

T TypVar j TT j TypVar T

The expressions of F T are dened by the fol lowing abstract syntax

T Var j TT j T T jVar TT j T y pV arT

A context is a sequence of declarations x x Var and T where it is assumed

that if x and y are dierent declarations in the same context then x y

The typing rules for deriving judgements of the form M for a context M an

expression and a type are the fol lowing

If x is in then x

x M M N

MN xM

M

M

if T if FTV

M

M

FTV denotes the set of free type variables TypVar

The one step reduction rules are the fol lowing

x M N M N x

x M x M if x FVM

M M

M M if FTVM

FV denotes the free term variables Var One step reduction is dened as the union

of and The relations and are respectively dened as the transitive

reexive and the transitive reexive symmetric closure of

Here t tu denotes the substitution of t for the variable u in t Substitution is done

with the usual care renaming bound variables such that no free variable becomes bound after

substitution

Type variables will b e denoted by the lower case Greek characters and term variables

will b e denoted by lower case Roman characters The set of expressions typable in the context

with type is denoted by Term

We want to discuss categorical notions like weak initiality in the syntax and therefore dene

need a syntactic notion of functor This will b e covered by the wellknown notion of p ositive

or negative type scheme

Denition A type scheme in F is a type where marks al l occurrences possibly

none of

A type scheme can be p ositive or negative but also none of the both which is

dened by induction on the structure of as fol lows

a If FTV then is p ositive and negative

b if then is p ositive

c if then is p ositive if is negative and is

positive is negative if is positive and is negative

d if then is p ositive resp negative if is

positive resp negative

A positive resp negative type scheme works covariantly resp contravariantly on

a term f obtaining a term f of type resp by lifting

dened inductively as fol lows Let f

a If FTV then f id

b if then f f

c if then if is positive

f x y f x f y if is negative

f x y f x f y

d if then if is positive f x f x if

is negative then f x f x

It is easy to check that the lifting preserves identity and comp osition id id and if

is p ositive then f g f g if is negative then f g g f

This also works for type schemes containing or if we interpret and as the denable

weak pro duct and copro duct

fst x x y z y

snd x x y z z

f g z k k f z g z

for f g

inl x f g f x

inr x f g g x

f g z z f g

for f g

It should b e remarked here that if one lifts f via a type scheme

resp ectively according to Denition this do es not give

the exp ected result f x f fstx f sndx resp ectively f inl

f inr f If we take the latter denition for lifting a function via a pro duct or sum

this do esnt yield functoriality of and We introduce some new notation to denote this

lifting via and

Denition Let f g

timesf g is dened by

timesf g z y z p q y f pg q

plusf g is dened by

plusf g z y y z y f y g

Now for f if then f times f f and if

then f plus f f Lets state some more easy facts ab out times

and plus some of which will b e used later

Fact For f g h and k of the right type we have

plusf g inl inl f

plusf g inr inr g

plusf g plushk plusf hg k

timesf g timeshk timesf hg k

f g plushk f h g k

plushk f g h f k g

In general we dont have fst timesf g f fst or snd timesf g g snd

Positive negative type schemes can really b e viewed as contravariant functors in the

syntax of p olymorphic lambda calculus Consider a syntax with countably many variables

of every type and view types as ob jects and terms of type as morphisms from to

The p ositive type schemes are a syntactic version of covariant functors Similarly we also have

syntactic versions of weakly initial terminal coalgebras and corecursive coalgebras

Denition Suppose we work in an extension of polymorphic lambda calculus where we

have xed a notation for weak products and coproducts eg the second order denable ones

Let be a positive type scheme

The triple M Elim is a syntactic weakly initial algebra if

a T

b M

c Elim

such that

Elim g M g Elim g

for any T and g

The triple M Intro is a syntactic weakly terminal coalgebra if

a T

b f

c Intro

such that

M Intro g Intro g g

for any T and g

The triple M Rec is a syntactic recursive algebra if

a T

b M

c Rec

such that

Rec g M g Rec g id

for any T and g

The triple M Corec is a syntactic corecursive coalgebra if

a T

b f

c Corec

such that

M Corec g Corec g id g

for any T and g

We have the following prop osition of which the rst part is a syntactic version of a result

in Reynolds and Plotkin and the second part is a result of Wraith In fact the

rst part of the prop osition says that the algebraic inductive data types can b e represented in

F which result originally go es back to Bohm and Berarducci Here we just want to give

these representations in short for further details one may consult Bohm and Berarducci

Leivant or Girard et al

Prop osition We work in the system F Let be a positive type scheme Then

There is a syntactic weakly initial algebra

There is a syntactic weakly terminal coalgebra

Pro of Let b e a p ositive type scheme

Dene M x g g Elimg x and Elim

g y y g Now M Elim is a syntactic weakly initial algebra

Dene

M xx g z Intro g g x and

Intro g y h hg y Now M Intro is a

syntactic weakly terminal coalgebra

We dont know whether there are syntactic recursive algebras or syntactic corecursive coalge

bras in F The answer seems to b e negative The wellknown denitions of algebraic datatypes

in F which are almost the ones dened in the pro of ab ove do in general not allow recursion or

corecursion as will b e illustrated by lo oking at the examples of natural numbers and streams

of natural numbers This means that recursion and corecursion have to b e dened in terms of

iteration and coiteration using the techniques discussed in the Examples and As was

noticed there it makes a dierence whether pro duct and copro duct are weak or semi so lets

note the following fact

Fact The denable coproduct in F is a weak coproduct but the denable product in F is a

semi product

That is f g h f h g h but not h f g h f h g

Example See also Example and Proposition We dene recursive functions on the

weak initial algebra of natural numbers

Let Nat M Elim be the syntactic weak initial algebra of as given in the proof

of where and are the second order denable ones One can also take the wel lknown

polymorphic Church numerals which is a slight modication of our type Nat The exposition is

not essential ly dierent but we want to use our categorical understanding of recursion of

So Nat M x Nat g g id Elimg x and

Elim g y Nat y g Now we rst dene Z M inl and S M inr

Following Example we now dene Rec g fst Elim Nat g Z S snd for g

Nat If

g g k fst snd

for some k Nat we obtain the recursion equalities for Recg

Rec g Z g

n n

Rec g S Z k Rec g id S Z

See for the restriction on the form of g the product is semi here The predecessor is now

dened by taking g Z snd so P fst Elim Nat Z snd Z S snd Notice that

n

P St t only for standard natural numbers ie for t S Z with the unique closed

term of type Also notice that P computes the predecessor of a natural number n in a number

of steps of order n

Example We dene corecursive functions on streams of natural numbers Take for Stream

the syntactic weakly terminal coalgebra as in the proof of for Nat So

Stream Nat M xStreamxNat g Nat

z id Intro g g x and

Intro g Nat y h Nat hg y We can dene head and

tail functions by taking H fst M and T snd M Following Example we now

dene for g Nat Stream Corecg Intro Streamg H inr T inl As the

coproduct is not semi but weak see we nd that only for g g in k for in is inr or

inl and some k StreamB or k StreamStream we obtain the corecursion equations

H Corec g g

T Corec g Corec g id snd g

The function that replaces the head of a stream by zero is now dened by ZeroH CorecZ inr

T

It is really imp ossible to dene a global predecessor on the weakly initial natural numbers

as describ ed ab ove and similarly for the p olymorphic Church numerals Also it is imp ossible

to dene a global ZeroHfunction on the weakly terminal streams as describ ed ab ove This is

shown in the following prop osition

Prop osition For Nat there is no closed term P Nat Nat

such that P Sx x for x a variable

For Stream Nat there is no closed term

ZeroH StreamStream such that TZeroHy Ty and HZeroH y for y a variable

Pro of Both cases immediately by the ChurchRosser prop erty for the system F

One can show in general that the coinductive types in system F as dened ab ove do not

allow corecursion ie they are weakly initial terminal coalgebras

Recursive algebras and corecursive coalgebras and p olymor

phism

We dene an extension of F which includes a syntactic formalization of recursive algebras and

corecursive coalgebras Then we show the remarkable fact that in this system one can dene

recursive algebras in terms of corecursive coalgebras and vice versa so one of the two is enough

to b e able to dene the other This fact has a counterpart in semantics in the form that every

K mo del of p olymorphic lambda calculus that has a recursive T algebras for every expressible

functor T also has a corecursive T coalgebra for every expressible functor T and vice versa

The notion of K mo del is in Reynolds and Plotkin it is a syntax dep endent notion of

mo del for F describ ed by giving a set of constraints that a structure and an interpretation

function should satisfy in order to b e a mo del As it covers a lot of known mo dels it serves well

as a framework for stating this prop erty semantically Also the notion of expressible functor

comes from Reynolds and Plotkin roughly sp eaking a functor is expressible if there is a

type scheme whose interpretation in the mo del as a function of the free type variable is a the

functor

We then want to relate our extension of F with recursive and corecursive types to a sys

tem describ ed by Mendler The latter system has a dierent scheme for recursive and

corecursive types the syntax of which is a bit to o weak to dene one in terms of the other

We can however interpret our system with recursive and corecursive types in Mendlers with

either recursive or corecursive types This is done by showing that the system has syntactic

recursive algebras and syntactic corecursive coalgebras for every p ositive type scheme

See Denition

Denition The system F is the system F extended with the fol lowing

cor ec

The set of types T is extended with and for a positive type scheme

For and we have the extra constants

In Rec

Out Corec

Reduction rules for and

Rec g In x g Rec g idx

OutCorec g x Corec g idg x

abbreviates and abbreviates

We now have the following theorem stating that in p olymorphic lambda calculus if one

has recursive types the corecursive types can b e dened and vice versa

Theorem In F we can dene Out and Corec in terms of In and Rec and vice versa

Pro of Supp ose we only have the rules for In and Rec and let b e a p ositive type scheme

Dene

Corec g x In h h g x

Out Rec z z pCorec plusidsnd p sndp p

where p and p abbreviate fstp and sndp the type of p is We

have

Rec g In x g Rec g idx

for any g and x of appropriate types and we want to show

OutCorec g x Corec g idg x

for g and x

To make things easier to read we omit the type information in lambda abstractions Let

b e a type g and x and abbreviate F pCorec plusidsnd

p sndp p The lifting of an f via is dened as following

f t k t z k times y xplusidf y xidz

Now

OutCorec g x Rec z z F In hh g x

Rec z z F id hh g x F

z F times y xplusidF y xidz g x

Corec plusidsnd plusidF g sndplusidF g x

Corec g snd plusidF g x

Corec g idg x

The other way around supp ose we only have rules for Out and Corec and let b e a

p ositive type scheme Dene

Rec g x Out xg

In Corec z h h Rec h id inr inrz

We have

Out Corec g x Corec g idg x

and we want to prove

Rec g In x g Rec g idx

We omit again type information in lambda abstractions and abbreviate F z hh Rec h

id inr inrz According to Denition

f t k t z k times idf z

Now

Rec g Inx Out Corec F x g

Corec F id hh Rec h id inr inrx g

hh Rec h id inr inrx z g times idF z

g times idF Rec z g times idF z timesidinr inrx

g Rec g timesidF timesidinr idx

g Rec g idx

We now want to lo ok at the system of recursive types as dened by Mendler lets

call it F The system also has corecursive types

CO RE C

Denition Mendler The system F is dened by adding to the polymor

CO RE C

phic lambda calculus the fol lowing

The set of types T is extended with and for a positive type scheme

For and we have the extra constants

in R

out

Reduction rules for and

R g in x g id R g x

out g x g id g x

abbreviates and abbreviates

In Mendler it is shown that this system satises a lot of nice metaprop erties like

strong normalization and conuence of the reduction relation

Denition The system F with only the rules for wil l be called F and similarly

CO RE C RE C

F with only the rules for wil l be called F

CO RE C C O RE C

We show that the system F can b e dened in b oth F and F so b oth systems

cor ec RE C C O RE C

have all syntactic recursive algebras and all syntactic corecursive coalgebras

Prop osition The types of F can be dened in F

cor ec RE C

The types of F can be dened in F

cor ec C O RE C

Pro of Let b e a p ositive type scheme

Write for and take In in

Rec g R f k g k f Then In and Rec

together dene the type of F in the sense that Rec g Inx g Rec g idx

cor ec

Write for and take Out out

Corec g f k k f g Then Out and

Corec together dene the type of F b ecause OutCorec g x Corec g idg x

cor ec

Corollary F can be dened in both F and F

cor ec RE C C O RE C

For every positive type scheme both F and F have a syntactic recursive

RE C C O RE C

algebra and a syntactic corecursive coalgebra

Pro of Both immediately by the prop osition and Theorem

As a corollary of the translation of F in to F we nd that F is strongly

cor ec CO RE C cor ec

normalizing

Prop osition The reduction relation of the system F is strongly normalizing and con

cor ec

uent

Pro of In order to prove strong normalization we dene a mapping from the terms of

F to the term of F that preserves innite reduction paths Then F is strongly

cor ec CO RE C cor ec

normalizing by the fact that F is strongly normalizing see Mendler One easily

CO RE C

veries that the system is weakly conuent ie if M N and M P then QN

QP Q The conuence then follows from Newmans lemma Newman stating

that strong normalization and weak conuence together imply conuence

The denition of is very similar to the mapping dened in the pro of of Prop osition

As the types do not in any way interfere with the reduction pro cess we omit the types in

abstractions Dene by

Rec g R f k g k f

Rec g R f k g k f

Rec g R f k g k f

In in

Corec g f k k f g

Corec g f k k f g

Corec g f k k f g

Out out

and further by induction on the structure of the terms Then

N M N M

M N M N

M N M N

M N M N

denotes a reduction in at least one step As there is no innite reduction in where

F the mapping maps an innite reduction path in F to an innite reduction path

cor ec cor ec

in F so we are done

CO RE C

It do esnt seem p ossible to dene the types in terms of the types in F nor

CO RE C

to dene the system F in the system F When one attempts to do so some extra

C O RE C cor ec

equalities seem to b e required

Discussion

As p ointed out by Christine Paulin Paulin the technique in the pro of of Theorem

also applies to a p olymorphic lambda calculus with a kind of retract types that we shall

describ e now We give the syntax as it has b een communicated to us by Christine Paulin it is

implicit in pap ers by Parigot Parigot and Parigot where extensions of the system

AF with recursive types are studied AF is a system of second o der predicate logic with an

interpretation of pro ofs as untyped lambda terms The connections b etween our system with

recursive types and the extensions of AF is a sub ject which needs further investigation we

feel that this is not the place to do so

Denition The system F is the extension of system F with the fol lowing

r et

The set of types T is extended with for a positive type scheme

For we have the extra constants

i o

Reduction rule for

o i x x

abbreviates

In this system one can construct for a p ositive type scheme a type with

is a retract of As p ointed out to us by Paulin the technique of can b e

applied to obtain that b oth the systems F and F can b e dened in F Also the reverse

r ec cor ec r et

holds F can b e dened in b oth F and F It would b e an interesting sub ject for further

r et r ec cor ec

investigations to see how the retract types relate to the recursive and corecursive types on the

categorical level

Theorem The systems F and F can be dened in F and vice versa

r ec cor ec r et

Pro of To dene F in F take

r ec r et

Rec f x ox f

In xi f f Rec f idx

and Rec g In x g Rec g idx easily follows To dene F in F take

cor ec r et

Corec f x i k k f x

Out x ox f Corec fst f idfstf sndf

and Out Corec g Corec g idg x easily follows

To dene F in terms of F or F take resp ectively

r et r ec cor ec

i In

o Rec snd

so oi x x and

o Out

i Corec inr

so again oix x

We can collect the results from Theorems and and Corollary in a picture as

follows An arrow from A to B means that the system A can b e translated in the system B

F

r et

I

R

F F

cor ec r ec

F F

RE C C O RE C

If we translate in F the type in terms of the type which is dened in terms

r ec

of the type we obtain the type A similar situation o ccurs if we

translate in F a type in terms of a type which is dened in terms of the type

r et

b ecomes Using these double translations we can deduce the following

facts ab out the systems F F and F themselves

r ec cor ec r et

Fact For a retract type of or of

is also a retract type of

For a recursive type of is also a recursive type of

For a corecursive type of is also a corecursive type of

We can also comp ose the translations to obtain new interpretations of types in types

and vice versa

Fact For a positive type scheme we can interpret types in F by taking

r ec

and Corec as in and

Out xRec sndx f Corec fstf idfst f sndf

For a positive type scheme we can interpret types in F by taking and

cor ec

Rec as in and

In xCorec inr f f Rec f idx

References

Bohm and Berarducci C Bohm and A Berarducci Automatic synthesis of typed

programs on term algebras Theor Comput Science pp

Co quand and Huet Th Co quand and G Huet The calculus of constructions

Information and Computation pp

Co quand and Mohring Inductively dened types In P MartinLof and G Mints

editors COLOG International conference on computer logic LNCS

Dowek ea G Dowek A Felty H Herb elin G Huet C PaulinMohring B Werner

The Co q pro of assistant version users guide INRIA Ro cquencourt CNRS ENS

Lyon

Girard et al JY Girard Y Lafont and P Taylor Proofs and types Camb Tracts in

Theoretical Computer Science Cambridge University Press

Hagino a T Hagino A categorical programming language Ph D thesis University of

Edinburgh

Hagino b T Hagino A typed lambda calculus with categorical type constructions In

DH Pitt A Poigne and DE Rydeheard editors Category Theory and Computer

Science LNCS pp

Hayashi S Hayashi Adjunction of semifunctors categorical structures in

nonextensional lambda calculus Theor Comp Sc pp

Kleene SC Kleene denability and recursiveness Duke Math J pp

Lambek J Lambek A xed p oint theorem for complete categories Mathematisches

Zeitschrift pp

Leivant D Leivant Contracting pro ofs to programs In P Odifreddi editor Logic in

Computer Science Academic Press pp

Mendler NP Mendler Inductive types and type constraints in secondorder lambda

calculus Proceedings of the Second Symposium of Logic in Computer Science Ithaca

NY IEEE pp

Mendler NP Mendler Predicative type universes and primitive recursion Proceedings

of the Sixth Annual IEEE Symposium on Logic in Computer Science Amsterdam The

Netherlands IEEE pp

Newman MHA Newman On theories with a combinatorial denition of

equivalence Ann of Math pp

Paulin Ch PaulinMohring private communication

Parigot M Parigot Programming with pro ofs a second order type theory ESOP

LNCS pp

Parigot M Parigot Recursive programming with pro ofs Theor Comp Science pp

Reynolds and Plotkin JC Reynolds and GD Plotkin On functors expressible in the

p olymorphic lambda calculus In G Huet editor Logical Foundations of Functional

Programming In The UT Year of Programming Series Austin Texas pp

Wraith GC Wraith A note on categorical datatypes In DH Pitt A Poigne and DE

Rydeheard editors Category Theory and Computer Science LNCS pp

Girards Paradox in lambda U

Leen Helmink Eindhoven

Abstract

The presentation discusses a computer assisted construction of a pro of of Girards para

dox in lambda U Theoretical as well as practical issues will b e addressed

Computable interpretation of crosscuts pro cedure

Hugo Herb elin INRIA Ro cquencourt and ENS Lyon

Abstract

In the symmetric sequent calculus of Gentzen several ways of eliminating cuts are p os

sible One of them known as the crosscut pro cedure enjoys prop erties of symmetry We

will give an interpretation of this pro cedure in computable terms in the paradigm of pro ofs

as programs and cuts as communications b etween these programs We will show from cho

sen examples that this sometimes gives more natural programs than the actually known

interpretations of classical sequent calculus for arithmetic such as LC or T Co quands

interpretation in terms of games

Typing in Pure Type Systems

Bert Jutting

Nijmegen

Abstract

In the theory of Pure Type Systems PTSs it is to my knowledge an op en question

whether Expansion Postponement holds That is Let denote derivability in a PTS and

derivability in the same PTS where the rule

c a A c B s A B

conv

c a B

has b een replaced by the rule

c a A A B

red

c a B

Is it true that c a A c a B for some B with A B

Expansion Postponement is among other things imp ortant for proving correctness of

typing algorithms

In the talk I will prop ose an alternative denition giving rise to a dierent derivability

relation satisfying

c a A c a A and A s or c A s

The imp ortance of is stressed by the following prop erties

For Expansion Postponement holds

For an easy pro of of strengthening is p ossible which carries over to

A straightforward typing algorithm for can b e derived from

Relating Logic Programming

and Prop ositionsasTypes

A Logical Compilation

summary

James Lipton

Dept of Mathematics

University of Pennsylvania

Aug

Abstract

We analyze logic programs Horn Clause programs and extensions informally as speci

cations or types in the sense of the CurryHoward isomorphism rather than as programs

Using a realizability interpretation we develop a translation of these clauses to equational

sp ecications These give rise to various ways of asso ciating nondeterministic terms or

computations with this type that satisfy the logic program as a sp ecication By adapting a

result of Nero de generalizing HerbrandGodel computability to term mo dels we are

able to solve the equational sp ecication directly over the termmo del and pro duce a mul

tivalued Turingmachine index for the solution We also dene a realizability semantics in

a partial applicative structure over the Herbrand Universe and consider a nondeterministic

or disjunctive calculus All interpretations are indep endent of any choice of logic pro

gramming interpreter Rather they transfer control and implementation features of pro of

search to control and implementation features of the recursion theorem Completeness of

the former is mapp ed to correctness of the latter

Our translation provides a framework for integrating logic programming directly into a

typed or untyped functional programming environment in a way that preserves the Curry

Howard content of typing Our interpretations also provide new completeness theorems

for various classes of logic programs The results apply to Horn Logic Programs and the

MillerScedrovNadathur Uniform logic programming languages

Introduction Logic Programming as a sp ecication Language

The results in this pap er come from exploiting a largely unused uniformity that is present

in most logic programming paradigms the extraction of a witness to a query is uniform in

the parameters and predicates in the program By explicitly rewriting a logic program as a

realizability goal we search not for a sp ecic witness but a function that returns this witness for

every choice of parameters This reformulation is done rst in the framework of an abstract form

of the recursion theorem adapted from and then in terms of realizability over Fefermans

partial applicative structures where we can formalize logic programming languages and where

we are guaranteed the existence of the required partial recursive function via the appropriate

xp oint theorem as in

What we obtain is a compilation of logic programs into an equational sp ecication of func

tional co de via a generalized logic programming paradigm The logic program is treated as a

type the computation pro cess as one of nding a uniform inhabitant for the type The entire

development is implementation indep endent we obtain not a particular evaluation strategy

but a sp ecication which gives dierent functional solutions according to dierent evaluation

sequences We also dene a multivalued realizability which captures the nondeterminism of the

declarative program directly In this outline we develop one of these paradigms in detail with

an example and give a quick sketch of the remaining ones

Towards a Realizability Semantics for Logic Programs

In this section we develop an informal notion of realizability for logic programs We b egin with

a logic program P decorated with abstract realizers which are taken as atomic evidence that

the clauses are true b ecause the programmer says so We rst consider the rstorder case

Horn or First Order Hereditarily Harrop logic programs whose syntax is dened as follows Let

a q q q q xq q

h a q a h h xh

g a g g g g xg xg f g

f a g a f f xf

where a stands for an atomic formula Then a Horn clause program is a nite set of closed

hformulas and a query or goal for such a program is a q formula or a nite set of them

A First Order Harrop program is a nite set of closed f formulas and a query or goal

for such a program is a g formula or a nite set thereof

In the rst part of this pap er we will b e considering an arbitrary Horn or FOHH program

h s T t

h s T t

m m m m m

where s and t are tuples of terms and where each clause is decorated with abstract

i i

realizers These realizers supply atomic evidence that the corresp onding clauses are

n

b eing considered true

Realizability over the Herbrand Universe Our rst approach to extracting functional

content from the program P dened ab ove in together with a query Quv where the u are

parameters and the v are variables is to inhabit the Horn Clause sp ecication directly with

a realizer over the Herbrand Universe This means nding a term e from a suitable partial

combinatory structure EH dened over the Herbrand universe of the program satisfying

e uv P Quv

As will b e shown b elow this entails nding a function e which on a suitable domain D

satises the sp ecication

u P Qu eu

We show how to pro duce a series of recursion equations sp ecifying e from Variants of

Kleenes and Nero des recursion theorem guarantee the existence of a solution in the

set of partial recursive functions We start with an example that shows how we obtain a

sp ecication for a multivalued function which captures the full nondeterminism of the original

declarative program seen indep endently of any choice of an interpreter

An nondeterministic Example

We consider the realizability interpretation and the induced translations for the following Horn

clause program P equipp ed with dummy realizers

add X X

addsX Y sZ addX Y Z

Which means see realizability denitions b elow

x x add x x

xy z f f addx y z xy z f addsx y sz

We trace through the compilation of this program to a sp ecication of the nondeterministic

function f N N N satisfying

f x f x x

First we translate this program to the following realizability goal assigning what we will call

b elow a h i template to the predicate add that is to say the character of an input to the

third variable and of an output to the rst two

e e uv w P addv w u

Unravelling this according to the denitions of realizability given b elow with the notation e

b

and e for left and right pro jections of e

b b

ue u P adde u e u u

ie

b b

u adde u e u u u P e

Taking to b e h i from and ab ove we have

b b

euh i adde u e u u

Now unifying on the third variable that is to say unifying on the template h i with the

rst clause of the original program we have

u add u u

b b

uh i adde u e u u e

b

which has a solution e if we choose

b b

e u and e u u

uh i u Now assuming an e exists satisfying we have by applying the as well as e

second clause of the original program

b b b b

u e ue uu e uh i addse u e u su

and applying to su

b b

suh i adde su e su su u e

where the choice of argument in and is dictated by unifying and on the last

b

variable Now has a solution if e satises the recursive equations

b b b b

e su se u and e su e u

b b

as well as the corresp onding condition e suh i e ue uue uh i for e Leaving

aside for the moment the requirements for the evidence e we have the following conditions for

b

e

b

e u

b

e u u

b b

e su se u

b b

e su e u

We must b e carreful ab out how we deal with the multivalued character of these equations Taken

at face value they logically imply the collapse of the underlying Herbrand Universe since for

b

every u we have e u u

b b

For this reason we interpret dierent conditions for e and e disjunctively Before delving

into our formalized treatment b elow we give an informal treatment Using for non

deterministic disjunction we can write this sp ecication somewhat in the style of ML as

b

f un e h i

b b b

e su h su i hse u e ui

There is a natural execution mo del for this sp ecication corresp onding to every complete pro of

search strategy for the original program for example a breadthrst traversal of the induced

computation tree until a leaf is found in normal form

We also obtain a solution to this which captures the nondeterminism of the sp ecication

b

itself by lifting the solution e to a setvalued function e ie to the nondeterministic monad

in the obvious way Let set b e the canonical lifting of functions f D D to maps

setf D D b etween the p ower sets given by

setf X ff x x X g

Then e D D is given by

e fh ig

xhsp x p xie u e su setxh su i

setxh su ie u setxhsp x p xie u

where p and p are left and right comp onents of the pairs in eu

These approaches suggest several computational and realizability formalisations each with

its own xp oint or recursion theorem We sketch one b elow adapted from Nero des

dissertation which is in some sense indep endent of implementation ie developed in terms of

indices Several concrete developments of the lambda calculus along these lines are sketched

in the app endix

Nero deKleene computability over termalgebras

The following development adapted from Nero des dissertation provides an immediately ap

plicable framework for generating and solving equations along the lines of the example studied

ab ove

Denition A recursion calculus a nitesignature onesorted equational calculus is a

triple e V F C where V is a set of variables and F and C are nite nonempty sets of

functions and constant symbols respectively We wil l also call FC the esignature

The word ealgebra W is the Herbrand Universe of ground terms for the recursion calculus

e

e

A nite set A of equations in the recursion calculus e V F C is said to overlay the word

ealgebra W if e V F C and F F We say such a set of equations distinguishes W if

for any w w W

A w w W j w w

We say A is complete for W if for any function letter f F of arity k and any w w W

k

there is a w W such that

k

A f w w w

k k

We say A is a partial denition over W if A overlays and distinguishes W A is a denition

if in addition it is complete

Denition If A is a partial denition over the word algebra W and f is a k ary function

symbol in A we dene the partial function

k

f W W

A

by f w w w A f w w w

A k k k k

It is easy to see that if A is a partial denition then f is welldened and is total if A is

A

complete over W

k

Denition The partial function g W W is denable if there is a partial deni

tion A with a function symbol f of arity k such that f g

A

We now extend the notion of recursive function to a term algebra in a completely straightforward

manner

Denition Let e F C be a nite signature where F and C are ordered sets Then

the similarity type of e is a nitesupport sequence of natural numbers with n m i

there are m function symbols of arity n We dene a Godel numbering of the term algebra W

e

in fact the Godel numbering induced by any encoding of sequences in N and by the ordering

of F and C to be a function W N given by the standard ecoding f t t

n

S eq of t t A numbering of W is a bijection I N W such that such that

n e e

there are recursive bijections and with I and I

k

Denition Let I be a numbering of the wordalgebra W The partial function g W

k

W is recursive over W if there is a recursive partial function f N N such that the

fol lowing diagram commutes

f

k

N

N

k

I

I

k

W

W

g

We then have the following theorem proven in

k

Theorem The partial function g W W is denable i it is recursive over W

The pro of also shows that an index for the asso ciated partial function f N N can b e

uniformly eectively computed from co des for the equations in a way similar to Kleenes

original development of HerbrandGodel computability for partial recursive functions

A nondeterministic termmo del extension

Let e b e a recursion calculus and W its term mo del Then the term mo del W of the calculus

e p

e F fpar g C ffail g obtained by adding one distinguished binary function symbol par and

p

the constant fail is called the parextension of W We call the set of equations A overlaying W

e e

a parextension theory if the signature of A includes the function symbol par and the constant

symbol f ail and if A includes the following equations

asso ciativity of par

par par x y z par x par y z

failure

par f ail x par x f ail par x x

lifting for each f F other than par of arity n

f x x par y z x x

j j n

par f x x y x x f x x z x x

j j n j j n

Remark A slight reformulation of the ab ove will give us a syntactic variant of the nondeterminism

triple or monad construction eg Let C b e the category of partial ealgebras and algebra

e

homomorphisms Observe that if B is an ealgebra then so is the algebra B whose carrier jB j is given

a a

by the set of terms

fpar a a a jBj ff ail g g

m i

where par a a is shorthand for par a par a par a a The algebra op erations

m m m

are induced by lifting as given in the equations ab ove with constants a interpreted as par a a Let

T C C b e a functor dened by T B B with T s action on morphisms induced by the

e e a

corresp onding notion of lifting Then let B T B T B b e given by

par par a a b par a a b

m m

and B B T B by a par a a or par a f ail Then T is a monad

The aim of this termmo del construction is to reformulate equations of the sort pro duced

in the example ab ove eg which failed to distinguish the program signature ie led to a

collapse of the underlying Herbrand universe as equations over a parextension which constitute

a legitimate partial denition over that extension All that needs to b e shown is that all the

necessary denitions used in theorem lift to the new structure

Lemma Let I be a numbering of an eterm algebra W Then there is a numbering I of

e p

its associated parextension and a pair of recursive injections and from N to N such that

for al l a in W

e

I a I a and I a I a

p p

Since the parextension of W is just another termalgebra the main theorem states that a

e

function is denable over the parextension of W i it is partial recursive

e

Multivalued Turing Machines

In the next section we dene a pro cedure which when applied to a logic program and uniform

query P Q pro duces a set of equations A which give partial denition over the parextension

of the Herbrand universe of P By the main theorem of this section every A dened function

f has an asso ciated Turingmachine index e in the sense of denition We now dene the

f

asso ciated multivalued Turing machine R in the obvious way

f

sete n R n par

f f

where

par setn fI a a I ng

p

and where the relation is given by

x par y z x y xz

Our development is not particularly dierent than dening re set valued recursive functions by

asso ciating with any partial recursive f N N the function F N given by F x S

e

where S is the domain of the eth Turing machine The only signicant dierence is that the

e

numbering of sets is more natural since it is induced by Godel numbering of terms used to

dened sets of values

generic variables

We must also deal with fresh constants or variables introduced by the generic step for SLDR

computation see b elow or by equations induced by unbalanced programs those with o ccur

rences of a free variable in the head of a clause that do es not also o ccur in the tail Thus we

may need to generate equations of the form eg

ea y

where a is a constant or a term in which y is not free In order to solve these over parextensions

we must include sp ecial genericvariable terms g enc i where the c are fresh constants

i i

Then equations like are rewritten

ea g enc

i

where c is the rst such constant not already used When we lift the partial recursive functions

i

computed via theorem to nondeterministic functions we interpret g enc as the set of

i

all terms over the original Herbrand mo del These generic variables app ear as upp ercase logic

variables in the lambda calculi introduced in the app endix

Termmodels with choice op erators

A useful variant of the termmo del construction just given is the introduction of ternary function

symbols

cho a b

in lieu of par a b with an unsp ecied choice index f g cho satises the additional

equations

cho a b a cho a b b

This indexing device can also b e added to the disjunctive lambda calculus see app endix to

preserve unrestricted reduction and the ChurchRosser prop erty For convenience we can

extend this in the obvious way to terms

cho a a

n

where is in f n g and eg cho a cho b c cho a b c We will call an

assignment of sp ecic values to all in a choice termmo del an instantiation of the mo del

and by abuse of language we will also call them instantiations of the asso ciated parterms in

the parextension With such instantiations the multivalued functions computed ab ove now

b ecome single valued functions over the Herbrand Universe These are also called instances of

the corresp onding par or multivalued functions

SLDRcomputation of Equations

We now describ e the SLDRcomputation algorithm for generating equations ovber the par

extension of the Herbrand Universe or a generic extension

Denition F unication Let be a signature and F a set of function symbols disjoint

from those in Let s and t be terms over the signature F A term s over this signature

is called a term or just a pure term if no symbol in F occurs in s otherwise it is called an

F term An F term s is said to be rigid or in head form if s is et t for some e F

n

The set C s t of F unication constraints for hs ti is a nite set set of equations

dened according to the structure of s and t as fol lows

Case s and t pure then C s t is the equational representation of the most general uni

er of s and t namely a nite set of basic equations iea set of equations of the

form f x g where the x are variables not occurring in any of the terms

i i i j

representing the substitution x

i i

Case s or t F terms If either s or t is rigid C s t fs tg Otherwise we consider

the usual cases found in rstorder unication

s f s s and t a or t g t t where a f g are in and f is

n m

distinct from g then C s t fs fail t fail g

S

s f s s and t f t t where f then C s t C s t

n n i i

with the proviso that if fail occurs in C s t then this is equivalent to C s t

ffail g

any basic equations in C s t contributed as a result of case wil l be called pure unication

constraints

Scheduling We do not go into the details of scheduling here Since the compilation pro cedure

b elow always terminates bad scheduling cannot cause divergence Let us remark however that

the development is in the style of constraint logic programming so that failure of unication

may not b e noticed unless the generated equations are p erio dically analyzed for consistency

with resp ect to the decidable rst order theory of equality over the Herbrand Universe Iden

tities involving introduced function symbols never introduce inconsistencies For example an

attempt to unify Qf x and Qy in the presence of the constraint fy g ag may result

in success followed by the expansion of the constraint set to fy g a y f xg which must

eventually generate failure In prolog this happ ens at unication time and there is no rea

son why this could not b e done with SLDRresolution Then we must mo dify the denitions

ab ove appropriately to include F C unication of s and t ie unication in the presence

of constraints C We just apply C to s and t prior to carrying out F unication

We now describ e the SLDRcomputation pro cess First a few conventions regarding intro

duction of function symbols and scheduling

Introduction of function symbols We make the following assumptions on the predicates

to facilitate their functional interpretation all unary predicates P a are treated as predicates

in two variablesof variables P a tr ue so that the asso ciated function e satises e a

P P

true when P a ary predicates are just treated as Bo olean constants nary predicates

Qt t are assigned an inputoutput template a binary string of length n dening some

n

slots as inputs and the remaining ones as outputs ie as comp onents of the asso ciated function

value Because of the inherently relational nature of the induced multivalued equations there

is no need to consider more than one template p er predicate and with the exception of the

toplevel query no reason to pick one over another The equations generated by the SLDR

pro cedure b elow will work for any choice For eciency in solving these equations and ease of

representation it may prove useful to introduce more than one function for a given predicate

corresp onding to dierent templates eg to asso ciate subtraction with addin out in and

addition with addin in out but this can b e done at the time of solving the equations and

it is not required for the theoretical development or the results below

In what follows we will describ e the lo cal state of a program P with distinguished

clause C current goals Q Q equations C as a no de on the SLDR tree with the

n n

notation

h C P C Q Q i

n

and we show how to develop the subsequent no des of the tree by induction on the structure of

the current query Q

Denition Let P be a rstorder program with assigned realizer and suppose one of the

clauses of P is

T t Qr s

where r s is any breakdown and rearrangement of the predicate Qt t eg Qa b c

n

with x b and y a c Further suppose that the current query is Qx y ie the current

state is

h C P T t Qv s Qx y i

and that the predicate letter Q has not already occurred as a goal Then we introduce a function

symbol e or e rewrite the current state of the program as

Q

b

Qu eui h C P T t Qv s e

Then the fol lowing is the SLDRreduction step backchain

b

h C P T t Qv s e Qu eui

b

h C f e u s e g P T t i

where is the set of pure unication constraints as dened above in generated by F

b

unication of Qv s and Qu eu

ab ove along For the sake of thoroughness we have shown how to pro cess the evidence eg e

with the witnesses As remarked ab ove for selfrealizing classes of formulas there is no p oint

to carrying along this extra information so we omit these terms in the remaining pro of steps

We assume that the program is written in such a way that there is never more than one

clause with a given predicate o ccurring in the head Any logic program can b e so rewritten by

the use of disjunction in the tail of a clause and the p ossible addition of equational goals For

example

Qs S Qt T

can b e rewritten to

Qx x s S x t T

for a fresh vector variable x

1

their sole purp ose here other than to give another motivation for considering hereditarilky selfrealizing

classes of formulas a logic programming languages is to make p ossible the treatment of more general classes

via the generation of realizability constraints If the program is not selfrealizing it is only true in the induced

realizability mo del But this will b e taken up elsewhere

Denition Let P be as above and suppose a goal is of the form S s T t The fol lowing

is the SLDRreduction step cosatisfy

h C P S T i

h C P S i h C P T i

The steps corresp onding to all the remaining ones in eg FOHH logic programming eg

augment and generic in remain unchanged augment is

h C P A B i

h C P A B i

and generic

h C P xAi

h C P Ac i

where c is a fresh constant The most imp ortant step in the SLDR derivation of equations is the

recursion step which o ccurs every time a goal eg Qt t o ccurs for a second time

nm

on the same path of an SLDRtree Then a witnessing function e has already b een introduced

Q

for it with the condition

Qx x e x x e x x

n Q n Q n m

so the goal is immediately satised with the corresp onding F unication equations added to

C

recursion

h C P Qt t i

nm

m n

C x t C e x x t P i h C

i i Q n j j

i j

The search terminates when every goal on the right of the turnstile has a set of recursion

equations sp ecifying the corresp onding realizer in C Termination dep ends only on the predicate

letters o ccurring in a rstorder program Call a predicate letter A active if it has not yet

recurred in the sense of the recursion step ab ove Then a give predicate B can only o ccur on

the right of a turnstile if

it has never o ccurred b efore

it recurs on some path for the rst time

it is recurring again on some path b ecause it is a subgoal asso ciated with an active goal

A eg B C C A for if A were recurrent we would satisfy it using recursion

n

rather than backchain

Thus the number of recurrences of an inactive letter is b ounded by the total number of

predicate letters in the program We omit the straightforward but tedious details in this

summary

In particular termination is guaranteed irresp ective of termination of SLD resolution even

if the original program never halts for any input in which case a solution will b e a co de or term

denoting the totally divergent function eg a leastxp oint solution to the equation e e

We also leave for a fuller development of this pap er a description of the compilation of

the multivalued equations for all introduced function variables Essentially the equations on

dierent paths through a no de of an SLDRtree are pro cessed separately and then merged via

disjunctive expressions

t e x t

n

or using the formal terms in a parextension of the Herbrand Universe The particular parterms

that arise are clearly determined by the order in which the equations on dierent branches are

pro cessed

Semantics and correctness

Formalizing Realizability and computation over a Herbrand Universe

We will let L L P denote the language of the logic program Then dene H to b e

P

the Herbrand Universe of the program the set of ground terms over L We now build a

partial applicative theory around H or its asso ciated parextension along lines similar to eg

P

We will take Beesons formulation of Fefermans theory APP which Beeson calls

PCA with a primitive unary p ostx predicate for terms that denote together with the

standard partial combinators s and k pairing and unpairing a unary integer sort N and a ary

denition by integer cases op erator d The key results we will need here ab out APP are that

it satises combinatory completeness admits lambda abstraction and Kleenes single and

double recursion theorems admits strong denition by cases and satises the numerical

and term existence prop erty See or for details

Denition Let P be a Horn or FOHH logic program decorated with abstract realizers

h i Then we dene the associated applicative theory EH extending APP to

P

include the fol lowing

constants c f for every constant c and nary function symbol f in L We call these

symbols imported from L and also denote them c and f We also include the

abstract realizers directly as constants

i

constants t for every ground term t from L This means that eg for constants a b c

and function symbols f g imported from L the terms fagbc and

def

f ag bc AppAppAppAppf a g b c

2

dxy z w if x y then z el se w

are syntactically distinct objects in EH although they are identied via new axioms

P

below

A unary predicate H denoting the universe of the interpretation

for every term t and function symbol f imported into APP from H and for each

P

abstract realizer the axioms

i

t H t f i n

i

and for each nary function symbol f and terms t t imported from L

n

f t f t t f t t f t t

n n

The constant fail together with the axiom fail

Al l schemas in APP are to be extended to the new terms

eg t x Ax At for each term t

We extend the of terms to formulas in the obvious way

pt t pt t for f g etc We dene to

n n

be EH together with the embedded program itself ie in the form ftheta P g as a

P

set of nonlogical axioms

We now develop realizability style semantics over the applicative theories just dened in a

manner analogous to eg but restricting ourselves to interpreted formulas from the

language of the original program Although we have carried out this interpretation in order to

have one theory to discuss b oth program and evidence one should p erhaps think of this also

as a realizability with a distinct object language namely that of the program and a realizing

metalanguage namely EH or EP

P

Denition Syntactic Realizability over EH For a term t of EH and a for

P P

mula over the language of the original program L we dene the binary relation t

t realizes by cases and by induction on the structure of as fol lows

if is the ith clause of the program

i

def

t p t p

def

t Np t p t p t p t p t

def

t t

def

t x D p t p t xp t

x D

def

t x u D u tu tu xu

x D

We now can state our main representation theorem for rstorder logic programs We use

the following notational convention If t is a term in EH we write t ht t i to denote

P n

iterated pairing with asso ciation to the right Thus p t t p p t t etc

Theorem Let P be a rstorder program with generic query u v Then

Any instance e of a SLDRcomputed term e in EH provably realizes the program in

P

the sense that for some D denable in EH

P

EH e u D v D P u v

P

In particular there is a term t ht t i in EH which is the image of an

n P

instance of an SLDR computed term and which maximal ly satises the program as a

specication in the sense that for any input u in H for which

P v u v

we have

EH P u tu

P

Such a witnessing term t is faithful to the program in that

whenever t u u the values t u u are modulo the translation between

i m i m

language and metalanguage correct answers for the original program H

whenever values v v exist for a set of inputs u u

n m

we have t u u

i m

The theorem follows from the fact that al l logic programming languages considered here are

selfrealizing classes of formulas see eg Thus whenever

P u u t u t u t u t u

m m n n m

is realized provably in EH it is provable and conversely It is shown in eg that all

P

the key prop erties of APP are preserved in extensions by selfrealizing theories including the

soundness of most realizability notions in particular ours the existence prop erty and the

recursion theorem

It is clear that the structure of SLDRcomputation is geared towards preserving the com

putational content of the logic programs without selecting an arbitrary evaluation strategy To

make this precise we need to compare pro of search strategies selection and branching rules with

evaluation strategies of the resulting terms The notational machinery for this is cumbersome

and is omitted here although the results and ideas are straightforward

Corollary Suppose terms e and t from the theorem above are instances of NerodeKleene

solutions to a nite set of equational constraints C over the disjunctive term calculus obtained by

SLDRcomputation Then these terms preserve the computational content of the logic program

in the sense that every fair evaluation instantiation strategy for the resulting terms in a choice

extension of the Herbrand model corresponds to a complete proof search strategy for the logic

program

Other realizability interpretations

Adding a Domain or Type variable Constraint Logic programming

We provide a brief sketch of the way a mo died realizability enables us to capture constraint

logic programming and at the same time ensure a total realizability witness by constraining

the domain of the computed realizer The idea is to formally add an existential ly quantied

domain variable D when formulating the realizability goal for P

e D u D v D P Qu v

This formulation do es not require a partial applicative structure and can b e developed in total

type theoretic frameworks such as eg MartinLof type theory

It can also b e developed using KreiselTroelstra realizability over HAS or IZF see eg In

this case constraints are added to the list of goals to b e solved and determine the instantiation

of the variable D

A Kripke mo del for rstorder logic programs

We can capture the notion of partial realizability of logic programs formalized directly over the

Herbrand mo del using Nero deKleene computability by considering pairs e D where D is a

subset of the Herbrand Universe on which e converges as follows

We dene a Kripke mo del K with the following carrier set

K K where K fe D x y u D eu g

xy xy

where xy range over all tuples of variables x x and x x n m and with

k k k m

order given by e D x y e D x y if e extends e ie xe x ex e x ex

and D is a subset of D No des e D x y may only force atomic formulas with free variables

matching the tuples xy Atomic forcing is given by

e D x y kAx y u D P Aueu

where eu is a tuple of length equal to y We introduce the following notion of cover The set

S

S K is a cover of e D x y if for every e D xy in S e D is ab ove S and D

D S

Then we dene forcing of disjunctions via covers see eg and obtain a mo del in which for

all rstorder goals A

e D x y kAx y u D P Aueu

Using this semantics we obtain another completeness theorem for ther SLDR translation pro

vide d P is assumed to b e Horn or Hereditarily Harrop every node e D x y in

K forcing a query Qxy is extended by some instance of an SLDRcomputed term e and every

SLDRcomputed term occurs in a node of K

Realizability by multivalued functions

As we illustrated by example ab ove we can also choose IZF as our

metatheory with an applicative structure embedded in it as in eg McCartys We are

then able to construct the realizability interpretation of IZF as a basic mo del also known as the

realizability universe or with some variationthe eective top os see eg Our realizers

live in this mo del but will not b e the terms of the formalized applicative structure They

are sets and multivalued functions denable in IZF with the following p ossible realizability

denitions induced by term realizability over the logic program which we call strong and weak

s w

realizability and Strong realizability by sets of realizers is just

def

s

e x ex

Weak realizability is as follows Conjunction and implication and existence are as b efore The

interesting clause is disjunction

def

w

e x ex x

and

def

e x x e

Towards a nondeterministic realizability of logic programs

If we use the more syntactic formulations of multivalued functions describ ed ab ove and in the

app endix then order of the terms and the p ossible presence of a fail token suggest more complex

denitions to capture negation as failure

def

t t t t t fail t t fail t

where

def

t t fail t

and where for any predicate Qx x Qx fail is true We are able to obtain an analogue

n i

of theorem for multivalued realizability discussed in the

Conclusion

Using realizability interpretations of logic programs we can translate them into disjunctive

terms that weakly inhabit these programs as types or sp ecications in the CurryHoward

sense These translations maintain the declarative meaning of the program while leaving control

features untouched These are tranferred to the evaluationcontrol problems the way in which

the recursion theorem and disjunctive branching conditions are evaluated in the target mo del

This p oints to the p ossibility of studying control features of logic programming in the context

of functional programming with nonlo cal control op erators It also gives a natural way of

asso ciating domaintheoretic interpretations to logic programs Our translations also transform

logic programs into rst and higher order constraints over various kinds of applicative structures

This also p ermits the formalization within logic programming itself of constraint solving in a

new way Many new questions need to b e addressed here which constraints generated by

logic programs in the style discussed here have solutions over dierent typed calculi Can we

identify a typed logic programming language corresp onding to various subrecursive classes

How can we mo dify our realizability calculus to capture nonlo cal control more eciently and

clearly Perhaps most imp ortantly of all our work suggests that a ma jor task ahead of us is to

understand equation and constraintsolving together with feasibility questions over applicative

structures along the lines initiated by Statman and Tronci This work must combine

type inference and simultaneous constraint solving This issue is discussed in more depth in

In particular higher order programming is likely to require the simultaneous solution of

domain equations and constraint sets over continuous or computable functions on the indicated

domain

App endix

The disjunctive calculus

Following the example computed earlier we can extend the term structure of the lambda calculus

t We also or of a partial combinatory calculus such as APP to include disjunctive terms t

consider the addition of generic or logic variables X which can also b e thought of as lab elled

contexts standing for all p ossible nondisjunctive instances We consider two developments

here pure disjunctive calculus

t x X t t xt t t

indexed disjunctive calculus

X t t xt t t t x

The second calculus allows us to reason ab out disjunctive lambda terms with a generic evalua

tion index which is assumed to select one of the disjuncts which admits fullblown reduction

In the pure calculus we must lift disjunctions to the top using rule and rule prior to b eta

reducing with rule We now give reduction rules for b oth calculi The optional rules are

included to b etter handle the simplication of functions computed from logic programs but do

not seem eessential for the lambda calculi themselves

pure disjunctive calculus

t u ; su tu s

xsu ; sxu u nondisjunctive

x s t ; xs xt

xs u v ; xsu xsv

v z i ; hu z i hv z i h u

hz u v i ; hz u i hz v i

indexed disjunctive calculus

s t u ; su tu

xsu ; sxu

v z i ; hu z i hv z i h u

v i ; hz u i hz v i hz u

3

The author has recently learned of substantial work in disjunctive calculi by Pip erno Liguori and Dezani

among others which may provide a b etter framework for nondeterministic term extraction from logic programs

optional rules

v ; f u f v f u

u fail ; u

fail u ; u

u u ; u

References

Beeson M J a Foundations of Constructive Mathematics SpringerVerlag Berlin

Beeson M J b Proving programs and programming pro ofs in Logic Methodology and

Philosophy of Science VI I NorthHolland Amsterdam

Cerrito Serenella A linear axiomatization of negation as failure in the Journal of Logic

Programming Elsevier

Constable R L and Howe D J Implementing Metamathematics as an Approach to

Automatic Theorem Proving in Formal Techniques in Articial Intel ligence R Banerji ed

NorthHolland

Constable R L et al Implementing Mathematics with the NUPRL Development System

PrenticeHall NJ

Constable R L Programs as pro ofs Information Pro cessing Letters

Co quand T On the analogy b etween prop ositions and types in Logic Foundations of

Functional Programming AddisonWesley Reading MA

Co quand T and G Huet a Constructions A higher order pro of system for mechanizing

mathematics EUROCAL Linz Austria

Feferman S A language and axioms for explicit mathematics in Algebra and Logic

Lecture Notes in Mathematics No pp Springer Berlin

Amy Felty and Dale Miller Sp ecifying theorem provers in a higherorder logic programming lan

guage In Ninth International Conference on Automated Deduction pages SpringerVerlag

Argonne IL May

Fitting M Proof Methods for Modal and Intuitionistic Logics D Reidel Dordrecht The

Netherlands

Grin T The FormulasasTypes notion of control in the pro ceedings of the th POPL

conference

Harp er R MacQueen D Milner R Standard ML Technical Rep ort LFCS Lab o

ratory for the Foundations of Computer Science University of Edinburgh

Hayashi Sand H Nakano PX A Computational Logic The MIT Press Cambridge

Howard W A The Formulaeastypes notion of construction in Seldin JP and J R

Hindley eds To H B Curry Essays in Combinatory Logic Lambda Calculus and Formalism

Academic Press New York

Hyland J M E The eective top os in Troelstra A S and D S van Dalen eds

LEJ Brouwer Centenary Symposium NorthHolland Amsterdam

Huet G ed Logic Foundations of Functional Programming Languages pro ceedings of a

symp osium from the Year of Programming at the University of Texas at Austin Addison

Wesley Reading MA

J Jaar and JL Lassez Constraint logic programming In Proceedings of the th ACM Sympo

sium on the Principles of Programming Languages

Kleene S C Introduction to Metamathematics North Holland

Lipton J Constructive Kripke Semantics and Realizability in the pro ceedings of the

Logic for Computer Science conference held at the Math Sci Research Institute Berkeley Nov

Lipton J Relating Logic Programming and Prop ositionsasTypes full version of this

summary to app ear as a technical rep ort University of Pennsylvania

Lloyd J W Foundations of Logic Programming second ed SpringerVerlag

Dale Miller and Gopalan Nadathur Prolog Version July Distribution in CProlog and

Quintus sources

Dale Miller Gopalan Nadathur Frank Pfenning and Andre Scedrov Uniform pro ofs as a foundation

for logic programming To app ear in the Annals of Pure and Applied Logic

McCarty D C Realizability and recursive set theory Annals of Pure and Applied Logic

van Dalen D Intuitionistic logic in The Handbook of Philosophical Logic Vol I I I

D Reidel Dordrecht

MartinLof P Constructive Mathematics and Computer Programming in Logic Metho d

ology and Philosophy of Science IV North Holland Amsterdam

MartinLof P Intuitionistic Type Theory Studies in Pro of Theory Lecture Notes BIB

LIOPOLIS Nap oli Italy

Mitchell J and E Moggi Kripkestyle mo dels for typed lambda calculus Proceedings

from Symposium on Logic in Computer Science Cornell University June IEEE Washington

DC

Moggi E Computational Lambda Calculus and Monads in Pro c th IEEE Symp osium

on Logic in Computer Science Asilomar

Moggi E Notions of computation and monads technical rep ort University of Edinburgh

Murthy C Extracting Constructive Content from Classical Pro ofs Compilation and the

Foundations of Mathematics Ph D dissertation Cornell University

Murthy C An Evaluation Semantics for Classical Pro ofs LICS Pro ceedings

Nero de A Composita Equations and Recursive Denitions Ph D Dissertation University

of Chicago

Nero de A and Shore R Logic and Logic Programming to app ear

Odifreddi G Classical Recursion Theory NorthHolland Amsterdam

Robinson J A A machineoriented logic based on the resolution principle Journal of the

ACM V

Statman R Completeness Invariance and lambdadenability JSL

Tronci E Equational Programming in Lambda Calculus th LICS pro ceedings

Troelstra A S and D van Dalen Constructivism in Mathematics An Introduction Vol I I

Studies in Logic and the Foundations of Mathematics Vol NorthHolland Amsterdam

Troelstra A S Metamathematical Investigation of Intuitionistic Arithmetic and Analysis

Mathematical Lecture Notes SpringerVerlag Berlin

Programming with Streams in Co q

A case study the Sieve of Eratosthenes

y

Christine PaulinMohring Francois Leclerc

LIPIMAG URA CNRS CRIN URA CNRS

ENS Lyon Allee dItalie BP

Lyon cedex France VandoeuvrelesNancy cedex France

August

Abstract

A parallel dataow program can b e seen as a network of functional transformers over

innite lists also called streams G Kahn and D MacQueen prop osed this paradigm

in order to apply standard technics of semantics for proving the correctness of concurrent

programs On the other hand type theory and the paradigm of pro ofs as programs has

proved to b e useful for the justication of functional programs We investigate the program

mation with innite lists in strongly typed lambdacalculus by studying the example of the

sieve of Eratosthenes We develop this example b oth in system F and in the Calculus of

Constructions where certied programs are extracted from constructive pro ofs This study

suggests suitable representations for the type of Streams in the system Co q

Introduction

Programming with pro ofs

Usual programs involve inductive structures as natural numbers lists or trees We know quit well

how to systematically represent these structures in strongly typed lambdacalculus as Girards

system F We also know which induction principles are needed to reason ab out these programs

in a system like Co q for instance

An alternative p ossibility in Co q is to use realisability to extract correct programs from

intuitionistic pro ofs of existential statements From a pro of of xP x y Qx y the system

Co q will extract a functional program f written in a ML like language We know from the

metatheory that xP x Qx f x holds and consequently the program f is certied

Proving interactively xP x y Qx y is like developing simultaneously the program and

its pro of of correctness

FrancoisLeclercloriafr

y

cpaulinlipenslyonfr

This research was partly supp orted by ESPRIT Basic Research Action Logical Frameworks and by MRT

Programme de Recherche Co ordonnees Programmation avancee et Outils p our lIntelligence Articielle It

started during F Leclercs DEA practical p erio d at LIP in spring

Programming with coinductive types

The representation of coinductive types in strongly typed lambdacalculus has b een less in

vestigated However an innite list can b e represented as a pro cess for generating innitely

many elements Such innite lists also called streams can b e used to mo del concurrency in a

functional way making the pro ofs of correctness easier to achieve

A program which acts as a stream transformer can b e written in a MLlike language with

a lazy evaluation of constructors In a language with full p olymorphism like system F or

the Calculus of Constructions it is p ossible to internally represent the type of streams We

exp eriment these systems by applying the paradigm of pro ofs as programs to the construction

of streams This pap er presents a complete development of various versions of the sieve of

Eratosthenes in Co q

Notations

Our aim is to give the main ideas for the constructions of the programs We will not b e to o

formal but the examples were developed completely formally in the Co q system

We shall use terms either from the system F or from the Calculus of Constructions with

the following notations Quantication is written as x M N implication is written M N

which asso ciates to the right The lambdaabstraction is written as x M N or X K M for

an abstraction over types variables the application of term M to term N is written M N it

asso ciates to the left we shall sometimes omit the external parentheses The type annotation

after the in quantication or abstraction will b e omitted when it is clear from the context

We shall write M N when the terms M and N are convertible

The same names will b e used for dierent constructions but in that case also the ambiguity

can b e solved from the context

Representing Streams

In typed functional programming languages as ML innite lists are represented using a p ossible

lazy evaluation of the arguments of the constructors A value of type innite list will b e a pair

with a value the head of the list as the rst comp onent and an arbitrary program of type

innite list representing the tail of the list as the second comp onent We can write a program

which evaluates the rst n elements of an innite sequence This program can p ossibly fail or

lo op

It may seem imp ossible to represent streams in a strongly typed programming language

where all programs are strongly terminating However a p ossible concrete representation of

lists in a language like system F will b e as a pro cess generating innitely many ob jects

We investigate p ossible representations of the type of streams in b oth system F and the

Calculus of Constructions The type of streams is a particular case of a coinductive type

namely a greatest xp oint of a monotonic op erator We rst recall the general scheme to

represent coinductive types in system F

Coinductive types in System F

The representation of inductive data types like integers or lists in system F can b e seen as an

enco ding of smallest xp oints of monotonic op erators A general presentation of this can b e

found in or The case of coinductive types is less known but was studied by G Wraith

The representation of xp oints of monotonic op erators can b e seen as an application of

Tarski general xp oint theorem A coinductive type is the greatest xp oint of a monotonic

op erator AX which is computed as the least upp er b ound of the X such that X AX

The order is just inclusion which is enco ded via implication The least upp er b ound is the

union which is enco ded via an existential type This existential type is not a primitive notion

in system F but can itself b e enco ded using a secondorder quantication over types

Basic denitions

In system F the types in which a variable X o ccurs p ositively are generated by the entry Pos

of the following syntax

Pos M j X j Y Pos j Neg Pos

Neg M j Y Neg j Pos Neg

with the restriction that X do es not o ccur in M

Let AX b e a correct type in which X o ccurs p ositively let Y b e a type variable and f a

variable of type X Y then it is p ossible to build a term Af of type AY by induction over

AX

Let AX b e a correct type of system F in which X o ccurs p ositively We can dene b oth

and the smallest and the greatest xp oint of this op erator We outline in the following table

the main constructions asso ciated to b oth types

Inductive types Coinductive types

S

T

X AX

X

AX X

X

X X AX X

X AX X X

C X X AX X C C

iter X AX X X build X X AX X

X f mm X f X f xC H H X f x

in A out A

aX f f Aiter X f a mm A X f xAbuild X f f x

iter X F in m F Aiter X F m out build X F x Abuild X F F x

Natural numbers and Streams

The typical example of an inductive denition is the type of natural numbers It is the smallest

xp oint of the op erator X which can b e enco ded in system F as C C X C C

The typical example of a coinductive denition is the type of streams of elements of a type A It

is the greatest xp oint of the op erator A X which can b e enco ded as C A X C C

In b oth cases we can nd more direct enco ding than the one presented ab ove We outline the

main constructions in the following table

Natural numbers Streams

Str A Str

Nat Nat

X X A X X X

X X X X X

C X X A X X X C C

iter X X X X Nat X build X X A X X X Str

X xf nn X x f X htxC H H X h t x

Nat hd Str A

X xf x ss A X htxh x

S Nat Nat tl Str Str

nX xf f n X x f ss Str X htxbuild X h t t x

g T h T T g T A h T T

f Nat T iter T g h f T Str build T g h

f g hd f x g x

f S n h f n tl f x f h x

Examples

The nth element of a stream To compute the nth element of a stream is done by induction

on n We dene a function nth which has type Nat Str A We want it to satisfy the

following equations

nth s hd s nth S n s nth n tl s

This is achieved by the following denition

nth iter Str A hd H Str As StrH tl s

This is an example of an iterative denition over an higherorder type Str A

Stream of natural numbers starting from n We can represent the stream of natural

numbers n n n We dene a function Enu which has type Nat Str We want it

to satisfy the following equations

hd Enu n n tl Enu n Enu S n

This is achieved with the denition Enu build Nat xx S

Following the same pattern we can represent the constant stream which only contains the

value n as

Con build One xn xx o

with One a type for instance X X X with at least one element o

Prop erties of streams

A canonical element of type streams will b e a quadruple X H T x with X a type H a

function of type X A T a function of type X X and x a term of type X Such a stream is

obtained by build X H T x Its head will b e H x and its tail a quadruple X H T T x

n n n

The nth element of this stream is H T x where T x x and T x T T x

The stream X H T x can b e seen as an abstract representation of a pro cess build on a type

X a current state x and functions H and T that computes the output of the stream and the

mo dication of the state

We can say that this representation is abstract b ecause when we have an element of type

stream we cannot access its particular implementation

Of course an innite list can b e implemented as many dierent ob jects of type streams For

instance if s is a stream then build Str hd tl s and build Nat n Natnth n s S are also

streams which pro duce the same elements

A natural question to ask is whether a close ob ject of type Str is convertible to a term of

the form build X H T x This is not true b ecause of the impredicative representation of the

existential type For instance the constant stream can b e represented as

C H X X Nat X X X C

H C C x C C n x C C x x C x

This sort of problem was also mentioned for inductive types in although the representation

of inductive types is adequate for some simple types as natural numbers This problem

will disapp ear in the system Co q if we use the general primitive notion of socalled inductive

denitions but which can b e used also for noninductive concrete denitions as existential

pairs or disjunctions With this enco ding of the existential type a close normal term of type

X AX will b e a pair X H with a close type X and a close term H of type AX

Iterative versus primitive recursive denitions The impredicative enco ding of natu

ral numbers gives naturally the denition of functions using an iterative scheme f S n

h f n The more general scheme of primitive recursive denition f S n h n f n

is obtained using iteration and pairing It is well known that this enco ding is not satisfactory

b ecause f S n reduces to h n f n only if n is a close natural numbers and also the

number of reduction steps will b e prop ortional to n There is of course an analogous problem

for streams The basic iterative scheme of denition is tl f x f h x With this only

scheme it is not direct to program a function for the concatenation of an element a at the head

of a stream s The equations for such a denition will b e

hd conc a s a tl conc a s s

More generally we would like to program a stream as some pro cess X h t x which at some

step b ecomes a new given stream We write X Str C X C Str C C the

type representing the disjunct union of X and Str We call inl resp inr the left resp right

injection of type X X Str resp Str X Str The analogous of primitive recursion will

pr of type b e an op eration build

X X A X X Str X Str

We would like the following equalities to hold

hd build pr X h t x h x

pr X h t x build pr X h t y if t x inl y tl build

pr X h t x s if t x inr s tl build

If f is of type X Y and g of type Str Y we write f g the function of type X Str Y

pr such that f g inl x f x and f g inr y g y We can mimic the b ehavior of build

by taking

build pr X h X At X X Strx X

build X Str h hd t s Strinr tl s inl x

The equalities hd build pr X h t x h x and tl build pr X h t x build pr X h t y

if t x inl y will b e satised as convertibility rules But if t x inr s the streams

tl build pr X h t x and s will not b e convertible but will only have the same b ehavior

pr the stream conc a s can b e dened as Using build

build pr O ne xa xinr s o

The denition of the analogous of primitive recursion for coinductive types in typed lambda

calculus is presented in We will not need it in our development of the sieve of Eratosthenes

Termination prop erties In system F every program terminates If s is a stream it implies

that for each n nth n s has a value So an element of type Str dene a total function from Nat

to A

Streams in the system Co q

The system Co q extends the Calculus of Constructions with a primitive mechanism for inductive

denitions It contains system F and the ab ove representation of Streams can consequently b e

used We do not use the extension with primitive inductive denitions for the enco ding of

streams but we shall use it for the type of natural numbers in order to make available the

corresp onding induction principle

The Calculus of Constructions contains dep endent types like equality or the existential type

This allows to reason ab out these streams For instance we may state and prove prop erties like

nnth n Enu n

this will b e done by proving more generally by induction over n

n m Natnth n Enu m n m

But this is an external p oint of view where we rst write a program in that case a stream and

then prove its prop erties We are lo oking for a metho d where we build at the same time the

stream and its pro of of correctness One rst p ossibility is to use for the type A of the elements

of the stream a type which contains some logical information For instance the constant stream

with only n which was sp ecied as a stream with elements of type Nat can in the Calculus of

Constructions b e sp ecied as a stream with elements in the type p Natp n of natural

numbers which are equal to n But this is clear that this kind of constant sp ecication will not

b e very useful and it seems necessary to b e able to parameterize the sp ecication dep ending on

the p osition of the element in the stream We shall investigate a new denition of the type of

streams with a type of output dep ending on the range of the element in the stream

Indexed Streams

We can dene a type for streams using dep endent types that will allow an internal parameteri

zation of streams with the index A stream in system F gives for each n an element in a type

A Using dep endent types we can more generally in the Calculus of Constructions dene a new

type of streams that will give for each n a pro of of a prop erty A n The main constructions

related to such a stream are listed in the following table

Str n NatP Nat SetmP m A m mP m P S m P n

Nat Set

n NatC Set

P Nat SetmP m A m mP m P S m P n C

C

build n NatP Nat Set

mP m A m mP m P S m P n Str n

nP htxC H H P h t x

hd mStr m A m

mss A m P htxh m x

tl mStr m Str S m

mss Str S m P htxbuild S m P h t t m x

The functions dened ab ove satisfy the following convertibility rules with m P h t and x of

the appropriate types

hd m build m P h t x h m x

tl m build m P h t x build S m P h t t m x

We can now prove the following prop erty by induction over n

nm NatStr m A n m

We call this pro of nth We can check that its computational b ehavior is similar to the one of

the nth function in system F

Examples

The example of the stream which contains successive numbers can b e seen as an indexed stream

The sp ecication of the output will b e that for each n it gives a number p equal to n This is

represented in Co q as n Natp Natp n Let us call A this sp ecication Because there

exists obvious pro ofs h of mA m A m t of mA m A S m and for each n an

ob ject x of type p Natp n we can dene a stream on the sp ecication A indexed by n as

build n A h t x

Computational interpretation

There exists a computational interpretation of the pro ofs of the Calculus of Constructions as

programs of F which is describ ed in If we p erform this interpretation on indexed

streams we do not endup with the system F representation of streams but with a slightly

heaviest representation

X Nat X A Nat X X X

More or less this representation of streams contains an extra state of type Nat with the index

stored in it

We may avoid this problem if we introduce an extra notation for variables that will not b e

used for computations These notations are xt and xP The precise rules and interpretation

for this extension are in the spirit of what Hayashi did in the system AT T They have still

to b e written and are not the purp ose of this pap er but intuitively the ideas are the following

The extraction of xt is just the extraction of t if t is of type xP then the extraction of

t u is the extraction of t A program p will b e correct with resp ect to the sp ecication xP if

for all x the program p is correct for P usually we say that p is correct with resp ect to xP if

for all x the result of the program p applied to x is correct for P We can statically check that

a variable x is not used in a computational part which makes sure that the extraction pro cess

is correct

With the following denitions for the type of indexed streams we shall have as extracted

terms exactly the system F analogous constructions

Str n NatP Nat SetmP m A m mP m P S m P n

Nat Set

n NatC Set

P Nat SetmP m A m mP m P S m P n C

C

build n NatP Nat Set

mP m A m mP m P S m P n Str n

nP htxC H H P h t x

hd mStr m A m

mss A m P htxh m x

tl mStr m Str S m

mss Str S m P htxbuild S m P h t t m x

General parameterized Streams

In general the stream can b e parameterized by an arbitrary sequence of ob jects in a given type

U The sp ecication of the output will b e a relation on U namely A of type U U Set

A stream parameterized by p of type U will give as an output a new parameter q a pro of of

A p q and its tail part will b e a stream parameterized with q

We do not give all the precise denitions for such a type of streams It will b e done in a

particular case for the development of the partial version of the sieve of Eratosthenes

The sieve of Eratosthenes in system F

We are now interested in the development of the sieve of Eratosthenes in system F

Description of the algorithm

The algorithm is simple we describ e it equationally

An auxiliary op eration is the sieve function itself which takes a number p and a stream s

and gives back the stream of the elements of s which cannot b e divided by p The op eration

sieve has type Nat Str Str It can b e describ ed by the following equation

sieve p s if div p hd s then sieve p tl s

else conc hd s sieve p tl s

The sieve is used in an op eration of type Str Str that we call primes This op eration takes a

stream s keep its head p and applies to the tail of this stream the sieve op eration using p The

primes function is characterized by the following equations

hd primes s hd s tl primes s primes sieve hd s tl s

The primes numbers are obtained by applying the primes op eration to the stream Enu

If the scheme for the denition of the stream of prime numbers follows the general pattern

of an iterative denition it is not the case for the sieve function The head of the stream

sieve s will b e the rst element of s which can b e divided by p Nothing in the algorithm

makes sure that this search terminates Starting from a dierent stream than Enu we could

lo op forever To say that the result of the sieve has type Str implies in particular that there are

innitely many primes numbers It is not surprising that we cannot just translate this algorithm

in system F

A total version of the sieve

There are two solutions to avoid this problem The rst one is to introduce an explicit b ound

from mathematical results we know how to compute one for the search of the next number

which cannot b e divided by p The second one is not to manipulate streams of natural numbers

but streams of a type Nat which contains an extra dummy element dum The output will b e

a stream with primes numbers separated by the dummy element Nothing in the type of the

output avoids that from one p oint every output will b e dummy

We call this last algorithm the total version of the sieve of Eratosthenes We can program in

system F a function div of type Nat Nat b o ol such that div p q true when p or

q is the dummy element or when p divides q division on natural numbers is primitive recursive

and can b e programmed in system F The op eration sieve has type Nat Str Nat

Str Nat It can b e describ ed by the following equations

hd sieve p S if div p hd S then dum el se hd S

tl sieve p S sieve p tl S

This follows an iterative scheme It is actually just the op eration of applying a function f in

that case q if div p q then dum el se q to each element of a stream It can easily b e

translated into exact co de in system F

Str A B Str A Str B map

f A B build Str A s Str Af hd s tl

The primes op eration has type Str Nat Str Nat The equations are not changed

hd primes s hd s tl primes s primes sieve hd s tl s

The primes numbers are obtained by applying the primes op eration to the stream of successive

elements in Nat starting from namely with inj the injection function from Nat to Nat

Si build Nat inj S

We may remark that we will also get the stream of primes numbers starting from three by

applying the primes op eration to the stream of o dd numbers starting from three This stream

can b e constructed as

build Nat inj n NatS S n

The sieve of Eratosthenes in Co q

We now want to have a proved version of the sieve of Eratosthenes namely that it gives us all

prime numbers

Instead to do a pro of of the previous program we shall build a new one that will give us as

an output a natural number and a pro of of its primality Of course the problem will also b e to

sp ecify that it gives us also all prime numbers

We rst study the pro of counterpart of the total sieve which answers for each number if it

is prime or not We shall also gives the constructions corresp onding to a stream which only

contains the prime numbers

Sp ecication

If we analyze the algorithm we can see that its sp ecication do es not concern really primality

but can b e parameterized by the initial stream the primes op eration is applied to

Let this stream b e called Si We shall denote Si n the nth element of this stream The

output of the sieve program will b e the elements of Si which cannot b e divided by any of the

previous elements in the stream Of course if Si is the stream of natural numbers starting from

two or the stream of o dd numbers starting from three the fact that they cannot b e divided by

a previous element is equivalent to the fact that they are prime

This analysis led us to the denition of the relation divinf on natural numbers with the

following meaning

divinf k n pp k div Si p n

A few logical lemmas ab out divinf will b e used

A total sieve development

We rst develop a proved version of the sieve of Eratosthenes which corresp onds from the

computational viewp oint to the total sieve we studied in system F

We introduce the predicate divsp ec of type Nat Nat Set The denition of the sp eci

cation divsp ec k n is p Natp Si n divinf k p divinf k Si n The computational

contents of this sp ecication corresp onds to the type Nat

The output of the nal sieve program will b e an indexed stream based on the predicate

n Natdivsp ec n n It will indicate for the nth element of the stream whether there exists

k n such that Si k divides Si n

The function sieve The sieve transformation itself corresp onds to a pro of of

p Natk Natp Si k nStr divsp ec k n Str divsp ec S k n

Let assume that we have p k and a pro of of p Si k To prove nStr divsp ec k n

Str divsp ec S k n we use build with the predicate Str divsp ec k we have to prove the

two following lemmas

nStr divsp ec k n divsp ec S k n

and

nStr divsp ec k n Str divsp ec k S n

This last lemma is just proved by the tl term For the rst one assuming we have n and

an element s in Str divsp ec k n we lo ok at the head of the stream It gives us a pro of of

divsp ec k n q Natq Si n divinf k q divinf k Si n We do a case analysis If

there is a pro of of divinf k Si n then there exists a l k such that Si l divides Si n so a

fortiori divinf S k Si n is satised and then there is a pro of divsp ec S k n In the other

case let q b e such that q Si n divinf k q we test whether q can b e divided by p If p

divides q then b ecause p Si k and q Si n we conclude that divinf S k Si n is satised

and then divsp ec S k n In the other case from divinf k q and div Si k q we conclude

divinf S k q and nally divsp ec S k n This ends the pro of of the sieve

The function primes The primes function corresp onds to a pro of of

k NatStr divsp ec k k Str n Natdivsp ec n n k

It means that starting from a stream indexed by k and which gives for each n if Si n can b e

divided by Si m for m k we can build a diagonal stream also indexed by k which gives

for each n whether Si n can b e divided by Si m for m n

In order to prove this we apply build to the predicate n NatStr divsp ec n n We have

to prove the two lemmas

n NatStr divsp ec n n divsp ec n n

which is just proved by the hd function We also have to prove

k NatStr divsp ec k k Str divsp ec S k S k

Let s b e a term of type Str divsp ec k k we take the head of this stream It gives a pro of

of divsp ec k k p Natp Si k divinf k p divinf k Si k We do a case analysis

Let p b e such that p Si k we apply the sieve program to p k S k and the tail of s which

has type Str divsp ec k S k We get the exp ected pro of of Str divsp ec S k S k If

divinf k Si k we use the only non trivial lemma ab out divinf which says that if n cannot b e

divided by any Si m with m k then b ecause Si k can b e divided by Si l with l k we

have that n cannot b e divided by Si k So divinf k Si k divinf k n divinf S k n

So from q Natq Si n divinf k q we deduce q Natq Si n divinf S k q

And b ecause we always have divinf k n divinf S k n we deduce divsp ec k n

divsp ec S k n We nally can map this pro of on the tail of s to get a pro of of

Str divsp ec S k S k We may check that this pro of which lo oks a bit complicated acts

like identity on streams

Because we have trivially a pro of of divinf n we may build the initial stream as a pro of

of Str divsp ec

n

This is done using build with the predicate n Nats Strs tl Si We have to prove

n

ns Strs tl Si divsp ec n

and

n S n

ns Strs tl Si s Strs tl Si

n

Let s b e such that s tl Si For the rst lemma we take its head which is equal to Si n

It gives us a pro of of q Natq Si n divinf q and then a pro of of divsp ec n For

S n n

the second lemma we take the tail of s and check that tl Si tl tl Si

Final program Applying the primes op eration to this initial stream gives us a pro of of

Str n Natdivsp ec n n

Using the nth function we have a pro of of ndivsp ec n n

One step that remains to b e done is to prove arithmetical lemmas like

prime n is prime n pSi p p ndivsp ec n n is

or

pSi p p ndivsp ec n n is prime n is prime n

A partial lter development

We are now interested in a program that will only gives as output the numbers that cannot b e

divided by previous elements

Sp ecication

It is not easy to sp ecify this problem using the index of this number in the actual stream A

more natural sp ecication will b e to relate the output to its index in the initial stream Si and

also to the index of the previous element

For this we use a general parameterized type of streams which is dened as follow Let A

b e a sp ecication of type Nat Nat Set We give the type of the build and the out function

In that case the out function gives for a stream parameterized by p a new parameter q its head

which is a pro of of A p q and its tail which is a stream parameterized by S q

Str p NatP Nat SetpP p q NatA p q P S q P p

Nat Set

build p NatP Nat Set

pP p q NatA p q P S q P p Str p

out pStr p q NatA p q Str S q

1

The general case would have b een to give the tail as a stream parameterized by q but in our case q will

alway b e equal to S q and the sp ecication can more naturally b e written as a relation b etween p and q than

as a relation b etween p and q

We introduce the notation

b etween n m NatP Nat Prop n m xn x m P x

b etween n m P means that n m and P holds for all x such that n x m The sp ecication

we shall use is

ASieve k p q Natn Natn Si q divinf k n b etween p q xdivinf k Si x

ASieve k p q means that we have a number equal to Si q which is the rst element in Si from

Si p that cannot b e divided by a Si l for l k

Bounded search

We have to search for an element in the stream which satises some prop erty We know the

existence of a b ound N for the number of step in the search

To program this we use that some order is wellfounded The order dep ends on the b ound

N it is dened as

n m m n m N

N

It is clear that there cannot b e any innite decreasing chain for b ecause if n

N k N N

n n we have

N

n n n N

k

We shall use a principle of wellfounded induction namely the prop erty WF

N

P Nat Setnmm n P m P n nP n

N

This prop erty can b e proved directly by induction over the b ound N We shall use the fact that

n m Natm n and N n m NatS m S n m n

S N N

For the case N we assume we have F of type nmm n P m P n

and n of type Nat We apply F to n we have to prove mm n P m which is done

by absurdity of m n

For the induction step we have a pro of HypN of

P Nat Setnmm n P m P n nP n

N

a predicate P of type Nat Set a pro of F of nmm n P m P n and n

S N

of type Nat We apply F to n we have to prove mm n P m Let m b e such that

S n

m n we know that m S m We get the pro of of P S m using the hypothesis

S N

HypN on the predicate q P S q and on m We have to prove

nmm n P S m P S n

N

let p b e of type Nat and Hp b e a pro of of mm p P S m We build a pro of of

N

P S p with F applied to S p We then have to prove mm S p P m But

S N

m S p implies m S q and q p We apply Hp to q and get a pro of of P S q

S N N

which is P m This ends up the pro of

The computational content of this pro of can b e written as a program in a ML like language

let rec Wfind function

fun F n F n fun m error

S N fun F n

F n fun m Wfind N

fun p Hp F S p fun m Hp m

m

This primitive recursive functional lo oks slightly more complicated than the general recursive

program which do the same task

let rec Wfrec F n F n Wfrec F

This second program do es not make use of the b ound N for the search In Co q we can choose

to use the direct pro of of the induction principle and we will get a strongly normalizable

N

program We can also just prove that the order we use is wellfounded and then use the

principle

founded R P U SetnmR m n P m P n nP n R well

This axiom is interpreted via a realisability interpretation as the program WFrec It do es not

make use of the pro of of the wellfoundness of the relation

The sieve program

To b e able to write the sieve program we need more information on the stream Si namely that

for each k it contains innitely many element that cannot b e divided by Si l for l k

We add such an hypothesis k n NatN Natp Natn p N divinf k Si p

If we want a program written in a total language we need to explicitly give the b ound N if we

only want to develop the program using general xp oint this prop erty can b e non informative

and will only b e used for proving the wellfoundness of the order

The sieve program will b e a pro of of

n Natp q Nat b etween p q xdivinf p Si x n Si q

r NatStr ASieve p r Str ASieve S q r

In order to do that we assume we have n p and q natural numbers and pro ofs of n Si q

and b etweeen p q xdivinf p Si x We apply build with the predicate Str ASieve p We

have to prove

rStr ASieve p r t NatASieve S q r t Str ASieve p S t

For this we use the fact that there exists N such that x Natr x N divinf S q Si x

and prove

r x Natr x N divinf S q Si x

Str ASieve p r t NatASieve S q r t Str ASieve p S t

using the wellfounded induction over the order Our induction hypothesis will b e

N

u Nat u r x Natu x N divinf S q Si x

N

Str ASieve p u t NatASieve S q u t Str ASieve p S t

Now we assume x Natr x N divinf S q Si x Let s b e of type Str ASieve p r

We apply it an out step It gives us a parameter t pro of of ASieve p r t and a stream stl of

type Str ASieve p S t We do an elimination on the pro of of ASieve p r t It gives us a

natural number m and pro ofs of m Si t divinf p m and b etween r t xdivinf p Si x

Now we lo ok whether n divides m or not

Case n divides m If n divides m then we apply the induction hypothesis to S t It is easy

to check from the hypotheses that

xr x S t divinf S q Si x

Consequently from x Natr x N divinf S q Si x we get

x NatS t x N divinf S q Si x

We have to show that S t r From b etween r t xdivinf p Si x we get r t and

N

then r S t Also it implies that S t N b ecause otherwise there will b e no x b etween r

and N such that divinf S q Si x

The pro of of Str ASieve p S t will b e just the stream stl the tail of s We got

a new parameter u and pro ofs of ASieve S q S t u and Str ASieve p S u It

is enough to show from this that the prop erty ASieve S q r u holds The only prob

lem is to show b etween r u xdivinf S q Si x but this is a simple consequence of

b etween r S t xdivinf S q Si x and b etween S t u xdivinf S q Si x which

comes from ASieve S q S t u

Case n do es not divide m If n do es not divide m then the pro of of

t NatASieve S q r t Str ASieve p S t

is done by checking that indeed t satises the exp ected prop erties

The pro of of Str ASieve p S t is the tail stream stl To prove ASieve S q r t we

rst remark that the prop erty b etween r t xdivinf S q Si x is an easy consequence of

b etween r t xdivinf p Si x and the fact that p S q Because m Si t it is enough

to prove divinf S q m We have a pro of of divinf p m Let us assume that there exists

a S q such that Si a divides m and show that it leads to a contradiction We cannot have

a p b ecause divinf p m a q is not p ossible b ecause Si q n do es not divide m we

cannot have p a q b ecause xp x q divinf p Si x so we shall have b p such

that Si b divides Si a and consequently m This ends the pro of of this case and of the sieve

program

The primes function

The primes function is now not really dicult to prove Its sp ecication is

k NatStr ASieve k k Str n m NatASieve n n m k

The pro of is done by applying build with the predicate k NatStr ASieve k k We have to

show that

p NatStr ASieve p p q NatASieve p p q Str ASieve S q S q

So let s b e of type Str ASieve p p We apply an out step It gives us q a pro of of ASieve p p q

and the tail stream stl of type Str ASieve p S q From this we need to get a pro of of

Str ASieve S q S q From the pro of of ASieve p p q we get n such that n Si q and

b etween p q xdivinf p Si x So we can apply the sieve lemma to n p and q also to S q

and stl We get the exp ected pro of of Str ASieve S q S q

The nal step

As previously it is easy to build from Si a pro of of Str ASieve to which we apply the

primes op eration Now if we have a pro of of ASieve p p q it implies that Si q cannot b e

divided by Si k with k p and xp x q divinf p Si x this implies that Si q cannot

b e divided by Si k with k q which is the exp ected result for testing primality

Conclusion

In this pap er we investigated the programmation with innite lists in strongly typed lambda

calculus by developing the example of the sieve of Eratosthenes The complete pro ofs were

developed in the system Co q

It app ears when we want to develop programs concerning streams that the metho ds to

indicate in a sp ecication which part will b e used for computation is to o weak in Co q If we

want to control exactly the computational asp ect of the streams which are used we shall need

a metho d to indicate that a parameter of the problem should not app ear as an input of the

extracted program

When trying to develop basic programs for instance sorting algorithms in the pure Cal

culus of Constructions axioms like induction over natural numbers were always needed In

the development of this algorithm on streams we did not need to add any axiom concerning

coinductive types to the theory The only axiom we used is the one concerning wellfounded

induction for the development of the partial recursive sieve But it is not surprising b ecause we

know it is not p ossible to write in the Calculus of Constructions a pro of of a search which do es

not make a computational use of a b ound for this search

The main diculty to carry out this development was rst to get the idea of using a param

eterized type for streams second to nd the correct predicate to use when we apply the build

op eration In general we know from the exp ected program what is the computational part of

this predicate For the logical part it corresp onds to nd a correct invariant for the problem

This is a mathematical diculty which often app ears in the domain of pro ofs of programs As

so on as we get the right sp ecications and invariants the system Co q is of a great help to carry

out the whole formal development of the pro of

References

C Bohm and A Berarducci Automatic synthesis of typed programs on term algebras

Theoretical Computer Science

G Dowek et al The Co q Pro of Assistant Users Guide Version Rapp ort Technique

INRIA December

H Geuvers Inductive and coinductive types with iteration and recursion Faculty of

Mathematics and Informatics Catholic University Nijmegen

JY Girard Y Lafont and P Taylor Proofs and Types Cambridge Tracts in Theoretical

Computer Science Cambridge University Press

S Hayashi Singleton union intersection types for program extraction In Proceedings of

TACS

G Kahn The semantics of a simple language for parallel programming In Information

Processing NorthHolland

G Kahn and D MacQueen Coroutines and networks of parallel pro cesses In B Gilchrist

editor Information Processing NorthHolland

N Mendler Predicative types universes and primitive recursion In Sixth Annual IEEE

Symposium on Logic in Computer Science pages Amsterdam The Netherlands

IEEE Computer So ciety Press

C PaulinMohring Extracting F s programs from pro ofs in the Calculus of Constructions

In Asso ciation for Computing Machinery editor Sixteenth Annual ACM Symposium on

Principles of Programming Languages Austin January

C PaulinMohring Extraction de programmes dans le Calcul des Constructions PhD

thesis Universite Paris January

G C Wraith A note on categorical data types In DH Pitt DE Rydeheard P Dyb jer

AM Pitts and A Poigne editors Category Theory and Computer Science Springer

Verlag LNCS

Comp ositional understanding of type theory

Zhaohui Luo Edinburgh

Abstract

We present a theory of dep endent types and discuss several issues concerning its concep

tual universe of types which include the relationship b etween data types and prop ositions

intensionality and comp ositional understanding

The new Implementation of ALF

Lena Magnusson

Department of Computer Science

University of GoteborgChalmers

Preliminary version August

Introduction

This pap er describ es the completely new implementation of ALF which is an interactive pro of

editing system still on the exp erimental stage The aims are to have a general mechanism for

adding and treating denitions in a uniform and p owerful way and to do pro of editing as with

scratch pap er and p encil Theories are represented in the framework as collection of constant

declarations place holders are represented as yet unknown constant denitions and computation

rules are dened by pattern matching The exibility in pro of editing comes from the p ossibility

to have several goals simultaneously to combine topdown and b ottomup derivation and to b e

able to backtrack in a structured way Many of these features originate in the rst ALFsystem

ACN and an earlier implementation of MartinLofs logical framework Mag

System Overview

The pro of editing system is based on MartinLofs logical framework NPS with the extension

of judgements for contexts and substitutions lo cal environments and the notion of explicit

substitution applied to terms The framework provides a general machinery for the theory

indep endent part of the pro of derivation system and the p ossibility of representing theories in

the framework Theories denitions pro ofs and incomplete derivations are all represented as

collections of constants declared in an environment Pro of editing consists of manipulating

the scratch area part of the environment by adding denitions new goals and lemmas rening

goals by combining rules from the theory primitives and lemmas proved or not extending the

theory with a completed pro of or deleting parts of a pro of

The system consists of three main parts the environment with theory denitions and scratch

area the checker and the command interpreter The latter will not b e a sub ject of this pap er

and we will refer instead to the system manual which is under development The dierent

checking algorithms are all based on rules of the framework and are parameterized over the

environment denitions

lenacschalmersse

Window system

Q

Q

Q

Q

Q

Q Administration Checker Environment

add theory

rene denitions

delete

Z

Z

Z

Z

Z

Z

Commands to Checking judgements

manipulate the denitions and Scratch area

User

environment renements

Figure System overview

The framework provides general rules for application abstraction substitution and reduction

mainly b eta and eta A theory is represented by a collection of typed constants where every

constant type pair corresp onds to giving an axiom state the prop osition without pro of

Rules in a natural deduction style formulation of the theory are represented as functions from

premises to conclusions Denitions of functions are given with pattern matching in a functional

language style

The environment consists of three parts the theory the dictionary and the scratch area Prim

itive constants given without justication b elong to the theory and abbreviations which can

b e justied by type checking are kept in the dictionary All constants can b e declared in a local

context which allows for dening theories and pro ofs parameterized over the context variables

These generalized op en theories and pro ofs can b e instantiated to particular closed theories

and pro ofs by sp ecializing the free variables of the constants with explicit substitutions

The idea of the scratch area is that unsure parts of pro ofs can b e manipulated in a similar

way as on a scratch pap er Once completed in a satisfactory way the pro of can b e moved

to the dictionary part of the environment To manage backtracking and gluing parts together

in a correct way some b o ok keeping is required For instance a full dependency graph is kept

and up dated continuously to prevent circular denitions Moreover a set of constraints are

kept which are requirements concerning unknown notions needed to b e satised in the future

renements All this b o ok keeping is the reason for not allowing backtracking in the entire

environment

The framework

Terms and types

Terms in ALF are lambda terms extended with a notation for explicit substitution and with

constants declared in the environment The syntax of terms is the following

e x j c j x x e j ee e j cfx e x eg for n

n n n

where x denotes variables and c constants

Additional restrictions are that in an abstraction x x e e is not itself an abstraction

n

the head e in an application ee e is not an application and the variables x x

n n

in an explicit substitution fx e x egc must all b e declared in the lo cal context of

n

the constant c

Op en terms contain free variables These terms must b e validated in a context which is a

sequence of typings of free variables

x x x n

n n

where x i n are distinct variables and the free variables o ccurring in must have

i i

b een declared earlier in the context A substitution is a sequence of assignments of terms to

variables

fx a x a x a g

n n

The substitutions are p erformed simultaneously instantiating some of the free variables of the

term Only op en terms or constants denoting op en terms can b e aected by a substitution

The extension of syntax for explicit substitution is esp ecially useful for instantiating variables

of yet unknown constants or for constructing generalized pro ofs pro ofs in a context which

can later b e sp ecialized to particular closed pro ofs

Types are generated from a set of ground types and a dependent function type constructor A

ground type is either the predened type S et or a term of type S et The syntax of ground types

are

S et j e provided e S et

g r ound

and for types

j for n

g r ound n g r ound

where

x j x x j for n

k

We will denote terms by a b e or A B types by contexts by and substitutions by

An extension of a context or substitution is denoted by x or by fx ag

The framework rules

The extensions compared to the original formulation of MartinLofs logical framework are the

two judgements concerning contexts and substitutions and that judgements are given relative

to contexts

The basic assertions in the framework logic are the following judgement forms

is a context

Context

is a substitution which ts context in the context

Type

is a type in the context

T y pe and are equal types in the context

a is an ob ject of type in the context

a

a and b are equal ob jects of type in the context

a b

Context rules

A context is either empty or an extension of a prop er context

C ontext

T y pe

C ontext

x

x C ontext

A substitution ts a context if for every x a in x is in the context and a has

i i i i

the type of x Also this relation is relative to a context which will contain the free variables

i

of the a s This is also referred to as a contextual mapping with the notation

i

T y pe

f g

a

fx ag x

Term and Type rules

The new formation rules concerning contexts are the following

T y pe a

T y pe a

For the other rules we will have to refer to NPS

Representing a theory

There are mainly two dierent kinds of denitions primitive and dened notions As mentioned

primitive notions can not b e justied inside the system whereas dened notions can b e justied

by type checking

Primitive notions

The primitive notions are divided into two groups constructors which could b e either set

constructors or element constructors and implicitly dened constants Implicit denitions are

used for representing rules of theories such as structural induction or for dening primitive

functions on datatypes These are called implicit since their meaning is given by usually

recursive equations which show their computational b ehavior

Primitive constant denitions have the following form

name where name is a unique identier

such as N S et N and succ N N Implicit denitions consist of an additional list of

pattern equations describing the computational b ehavior of the rule function Examples of

implicitly dened constants are

add N N N

addx x

addx succy succaddx y

natr ec P N S et P x N P xP succx n N P n

natr ecP d e d

natr ecP d e succx ex natr ecP d e x

where patterns are either variables or element constructors p ossibly applied to a substitution

The constructors must b e applied to the prop er number of arguments which are again pat

which means that the argument is uniquely terns A pattern can also b e redundant denoted

determined by type checking and can therefore b e safely omitted These generalized patterns

compared to functional languages come from the dep endent types Nonlinear patterns are one

example of redundancy but there are other cases as well As a simple example consider the

rst pro jection f st A B S et p P r odA B A where pair is the constructor of the pro duct

type P r od The pattern equation should b e

pair A B a b a f st

or equally

f stA B pair a b a

We require the pattern equations to b e non overlapping or mutually disjoint which means that

at most one pattern can match any term and there is a way to ensure the pattern equations

to b e exhaustive by using a built in feature for generating pattern equations The pattern

matching is describ ed in detail in Co qb

Dened notions

Dened notions are either named terms together with their types and lo cal contexts or yet

unknown notions There is also a p ossibility of giving a name to a context or a substitution

and use the name as an abbreviation of the context or substitution resp ectively A yet unknown

notion is simply a dened notion where the term is not yet known but which is intended to

b e instantiated at a later p oint Yet unknown notions are used for place holders A constant

denition is of the following form

c a

where a is a term which may contain free o ccurrences of the variables in context or

c

which denotes that c is yet unknown The name c must b e unique Contexts can b e concatenated

extended denoted by Context abbreviations are written as follows

name n

n

where can b e either a context or a dened name Substitution abbreviations are written

i

name

Substitutions can also b e comp osed with if and The

abbreviations of contexts and substitutions are simply short hand notations since whenever

needed the abbreviations are expanded to their denitions

Judgement checking

Judgements usually dep end on constants from the current theory and dictionary which are

declared in the environment denoted and therefore the checking algorithm is parameterized

over We are not explicitly stating the validity of the environment in the rules b elow but it

is assumed the notion of valid environment is describ ed in section

The judgement checking algorithm will pro ceed in three steps by checking wellformedness

validity and nally truth of the judgement The judgement forms presented ab ove are all

decidable with some minor restrictions provided that the pattern equations given in the theory

will give rise to a conuent rewriting system This prerequisite is needed since each pattern

equation will corresp ond to a reduction rule from left to right and the equality of terms is

mo dulo all reduction equalities Abbreviations are reduced by expansion of their denition

but these are harmless rules concerning conuence On the other hand the incorp oration

of place holders as yet unknown constant denitions have the eect that the equality of two

terms can b e not yet decidable if the terms contain constants which have no denitions as

yet Therefore the judgement checking algorithm will not always answer either yes or no it

will sometimes answer maybe meaning that the judgement might b ecome true if the yet

unknown constants are instantiated prop erly fulll the constraints The second step in the

algorithm concerns validity of a judgement which is weaker than a true judgement since it

means that the judgement will b ecome true if the additional requirements of the constraints are

satised A judgement can b e decided to b e true or false as so on as there are no yet unknown

constants involved and sometimes refuted b efore that

Constraints

A constraint is a tuple a a in which at least one of the terms a and a are not

complete where complete means not dep ending on any yet unknown constants The meaning

of the constraint is that the unknowns in the equality is required to b e instantiated in such a

way that

a a

b ecomes a complete and true judgement

The judgement checking algorithm pro duces a set of constraints restricting the p ossible instan

tiations of the yet unknowns or a sp ecial symbol F ail denoting that the judgement can never

b ecome true for any instantiations of the unknowns

Valid judgements

The syntax of a wellformed judgement is as follows

J C ontext j j T y pe j T y pe j a j a b

The validity of a judgement is computed by the function J which takes a judgement and com

putes a set of constraints the union of all constraints resulting from the premises or F ail if

any of the premises computes to F ail J is dened in terms of I sC ontext F itsC ontext I sT y pe

and I sE l em which are the constrained counterparts of the formation rules for contexts sub

stitutions types and terms and of the functions computing conversion of types and terms

T y peC onv and C onv All constraints originate in the C onv function since its purp ose is to

check if two terms are convertible equal mo dulo equality rules First we give the rules of a

valid judgement and then state the additional requirements for a true judgement We will also

describ e the conversion algorithm C onv but the other functions are directly corresp onding

to their resp ective formation rules and are omitted

I sC ontext

I sC ontext I sC ontext

Context Subst

F itsC ontext

J C ontext

J

I sC ontext

I sT y pe

I sC ontext

I sT y pe

I sT y pe

Type TypeEq

T y peC onv

J T y pe

S

J T y pe

i

i

I sC ontext

I sT y pe

I sC ontext

I sE l em a

I sT y pe

Elem ElemEq

I sE l em b

I sE l em a

C onv a b

J a

S

J a b

i

i

Formally we dene a true judgement to b e

J i J is complete and J J empty set of constraints

and conversely a judgement is said to b e false i J J F ail The notion of b eing complete

is dened in more detail in section

The rst step of the conversion algorithm is to reduce the two terms to head normal form and

we will therefore pro ceed by giving the reduction rules b efore the conversion is describ ed

Reduction rules

The reduction is p erformed by applying the one step reduction rules until one of the following

cases o ccur

the term is on head normal form the head of the term is a constructor or a variable or

the term is an abstraction

the term is irreducible

the term can not b e reduced any further at this p oint since there is a not yet dened

constant blo cking the reduction

One step reduction rules

The reduction is dened by explicit substitution as an uncurried version of the usual rule

meaning that several b ound variables are substituted simultaneously The expansion is simply

unfolding a dened constant with or without denition and the last rule is matching against

given pattern equalities

reduction

bfx a x a g if n k

n n

x x ba a x x bfx a x a g if k n

n k k n k k

bfx a x a ga a if k n

n n n k

expansion

c c a

c a c U nk now n

Pattern matching

Since we require the patterns to b e non overlapping we know that in the list of patterns

asso ciated to a given constant in any p osition there must b e either only pattern

variables or only constructors This means that if a yet unknown constant is found in a

p osition of a constructor we know that no other pattern can p ossibly match as yet and

the term is not yet reducible and if a lo cal variable is found in a constructor p osition

we know that no pattern can match at all and the term is irreducible Moreover

redundant patterns are only allowed in p ositions where type correctness guarantees a

sp ecic term and therefore can safely b e ignored in the matching There are three

cases

if cp p a and cp p ca a then

n n n

ca a a

n M

the pattern matching term is not yet reducible

the pattern matching term is irreducible

Reduction to head normal form

The reason for not always reaching a term on head normal form is either that the term is

cb b where c is an implicitly dened constant and at some p osition i where constructors

n

are exp ected in the patterns the b is either a variable or a yet unknown constant or the unknown

i

is in the head p osition of the term Therefore the output of the reduction will b e a term prexed

with its status of reduction ie

Term HnfTerm IrrTerm NotYetTerm

hnf

and the reduction pro ceeds by case analysis on the term structure

Var

x Hnfx

hnf

Const

c Hnfc if c is a constructor

hnf

c NotYetc if c is yet unknown

hnf

c P e if c e P e where P fHnf Irr NotYet g

hnf hnf

Abs

x x a Hnfx x a

n hnf n

App Case analysis on the head b of ba a

n

b is an abstraction

ba a P e if ba a e P e

n hnf n hnf

b is a variable or constructor

ba a Hnfba a

n hnf n

b is a dened constant c

ca a NotYetca a if c is yet unknown

n hnf n

ca a P e if c e and ea a P e

n hnf n hnf

b is a constant dened by pattern matching

ba a P e if ba a e P e

n hnf n M hnf

Conversion

The check for conversion is done in three stages The rst stage checks syntactic equality or

if either of the terms are yet unknown the second stage assures that the type of the terms

are ground and the last stage p erforms the reduction to head normal form and then do es the

simpler head conversion check To compute

C onv e e

yielding a set of constraints or F ail we will pro ceed as follows

if e e then C onv e e empty set of constraints

if either e or e is a yet unknown constant then C onv e e fe e g

if x x then

n n

e y y e y y fx y x y g

n n n n

in the context extended by the new variables y y

n

This rewriting of the original conversion problem is a combination of p erforming

expansion conversion and removing common abstractions of b oth terms but it

is done in one step After this transformation we know that the type must b e ground

which means that when b oth sides are reduced to head normal form neither term is an

abstraction and in an application the head is supplied with all its arguments useful for

pattern matching

apply the reduction to head normal form to b oth terms and dep ending on their status of

the terms we have the following table

e ne Hnfe Irr e NotYete

Hnfe see b elow F ail

Irre F ail if e e then else F ail

NotYete

where fe e g

we only have to consider two cases in the head conversion since we know that e and

e are on head normal form and since the type is ground they are not abstractions The

only p ossibilities are for the heads to b e either variables or constructors applied to a

prop er number of arguments

ba a and b a a

n

n

if b b then

C onv a a

C onv a a

n n

n

S

n

a C onv ba a b a

i n

i n

else F ail for b b

b and b

if b b

C onv b b

F ail otherwise

Environment

The environment contains three parts the theory declarations the dictionary and the scratch

area The declarations in the theory and dictionary are required to corresp ond to true judge

ments while in the scratch area valid judgements are allowed This means that the constants

in the scratch area can dep end on any primitive or dened constant which is declared in the

environment but the other way around is not accepted

The environment is extended by one declaration at the time and any kind of denition can b e

added at any time provided the new declaration is a valid extension of the current environment

The only op eration on the theory and the dictionary is the extension of a new declaration which

is explained b elow The extension is monotone in the sense that if a judgement is true in an

environment it is also true in any valid extension of that environment Note that the monotony

prop erty do es not include the scratch area denitions The scratch area and its op erations are

describ ed in the next two sections

Extending the theory

The theory contains b oth declarations of canonical constants constructors and noncanonical

constants implicitly dened constants which in addition to their type declaration have a set

of pattern equations Therefore the extension is either a named type declaration canonical or

noncanonical constant or it is an extension of a pattern equation

type declaration

A new primitive constant can b e declared if the type is valid in the given context

with resp ect to the current environment

V al id T y pe c

V al id c

pattern equation

A pattern equation is an equality

cp p e

n

where c must b e known in the current environment and c must b e of arity n The

pattern context and the type of cp p are computed and e is checked to

n

b e of type in Further requirements are that redundant patterns only o ccur in

p ositions where the term is uniquely determined by type checking and that the new

pattern is nonoverlapping with resp ect to all the other pattern equations asso ciated

with c The nonoverlapping prop erty as well as exhaustive pattern equations are

ensured if the pattern equation generator is used to create new equations see section

V al id cp p e

n

V al id cp p e

n

Extending the dictionary

The dictionary can b e extended by abbreviations for a term a context or a substitution which

corresp ond to true judgements The formal rules are the following

V al id V al id V al id

e C ontext

c c c

V al id c e V al id c V al id c

Scratch area

The scratch area is where pro of development take place A goal is represented as a yet unknown

constant declaration c where is the type corresp onding to the prop osition to b e

proven contains the free variables or parameters which are allowed to o ccur in the pro ofterm

which is yet to b e lled in c is the name of the pro of or more correctly an abbreviation of the

pro ofterm When the pro of is completed ie the is replaced by a term which can b e checked

to b e of type in the pro of can b e moved to the dictionary as an abbreviation and later

used as any other abbreviation New goals can b e added to the scratch area at any p oint and

it is p ossible to work on any goal one desires simply b e always referring to the name of the

goal

The two main purp oses for the scratch area is to achieve full exibility of combining topdown

pro of derivation with b ottomup as well as b eing able to backtrack and choose an alternative

way of constructing the pro of Here backtracking means more than resume at an earlier state

of the scratch area since what we refer to as backtracking is rather deletion of a subterm of a

pro of with the eect that only parts of the pro of structurally dep ending on the deleted term

will b e deleted as well

The price we have to pay for this exibility is that b esides the set of constant declarations

which are the actual goals and subgoals we need to keep track of some additional information

Since the declarations in the theory part and dictionary are required to corresp ond to complete

judgements all the not completed declarations are kept in the scratch area and therefore the

set of constraints restricting the instantiation of the subgoals is kept here as well We also

need a dependency graph which records all the dep endencies b etween the constants to prevent

circular denitions of constants recall that abbreviations are not allowed to b e recursive Since

the actual order of the declarations in the scratch area is irrelevant any constant declared in

the scratch area can b e used anywhere b efore or after it is dened and we sometimes need to

sort the declarations in a top ological order dep endency order the dep endency graph is very

useful for this purp ose as well

To b e able to p erform backtracking prop erly we need to distinguish b etween constants which

are dened by renement and constants which are instantiated by unication required by

constraints since these requirements might not b e relevant after the backtracking Therefore we

have a backtrack area which contains a copy of the scratch area declarations but which constants

are not instantiated by unication restrictions The reason for choosing double representation

of the same information instead of p erforming the instantiations when needed is that in an

interactive system esp ecially with a window interface we really want the information to b e

visible and up dated continuously This would require unnecessary computations to keep the

declarations up to date most of the time Instead we recompute the scratch area from the

backtrack area only after the hop efully more seldom op eration of backtracking

Finally there is a list of waiting patterns which are patterns generated by ALF and which are

waiting to get their lefthand side of the equation their denition A waiting patterns can b e

connected to a goal and this provides a way of constructing the term within the scratch area

which is an advantage if the term is large and complicated

Dep endency graph

The dep endency graph is a graph recording the internal dep endencies of the constants decla

rations in the scratch area The graph provides answers to the following questions

which constants the term of c dep ends on denoted TermDepc

which constants the type and context of c dep ends on denoted TypeDep c

all constants that c dep ends on denoted Depc TermDep c TypeDep c

the set of constants which are yet unknown denoted U

the constants which are yet unknown that c dep ends on DepUc Depc

The no des of the graph corresp onds to the constants in the current set of declarations and the

p ointers b etween the no des are either term dep endent or typecontext dep endent The reason

for separating the two kinds of dep endency is that a constant which is typecontext dep endent

on c is not a meaningful declaration without c while the term dep endent constant is still

meaningful with the term removed We will mainly think of the graph in the term dep endent

p oint of view since it captures the structure of the pro ofterm and we will refer to the subgraph

of c as b eing the part of the graph corresp onding to cs fully expanded pro ofterm

Backtrack area

The backtrack area contains a set of constant declarations which as a subset contains the con

stants in the scratch area and a dep endency graph concerning these constants The constants

also o ccurring in the scratch area are called visible whereas the others are invisible The in

tuition is that each constant declaration stands for a step in the derivation the denition of

the constant stands for the rule applied in that step and the new constants o ccurring in the

denition corresp ond to other steps in the derivation Moreover the invisible constants stand

for intermediate steps in the pro of derivation and the visible constant denitions corresp onds

to derivations collapsed to a few ma jor steps If we did not instantiate constants at all by

unication and also expanded the invisible constants then the scratch area and backtrack area

declarations would b e identical

The corresp ondence b etween the scratch and backtrack area can b e summarized by the following

p oints

All visible constants in the scratch area are also in the backtrack area

If a constant is dened in the scratch area but unknown in the backtrack area then its

denition is forced by unication

Waiting patterns

A waiting pattern is a tuple cp p where is the context of the pattern

n

variables and the lo cal context of c Waiting patterns are created by the op erations create

pattern and expand pattern As an example consider the implicit constant declaration of add

x y N N then create pattern will add the waiting pattern

addx y N x y N a pattern with only pattern variables

to the list of waiting patterns and expanding that pattern with resp ect to the variable y would

replace the same by

addx N x N and addx succy N x y N

Note that the generation of waiting patterns by the op erations create pattern and expand pattern

preserves the the prop erty of the patterns of b eing exhaustive and non overlapping Any of

these new waiting patterns can again b e expanded with resp ect to another pattern variable

The waiting pattern can b e asso ciated with a goal in the scratch area which means that when

that goal is proven the pattern is completed and can b e moved to the theory A waiting pattern

can also b e completed by giving the denition directly

Op erations on the scratch area

The op erations on the scratch area can b e divided into three groups proof construction proof

completion and backtracking or pro of deletion Pro ofs are constructed by rening a yet un

known constant ie by giving a partial pro ofterm as its denition The term can contain

other constants from the scratch area constants from the theory or dictionary or variables from

the lo cal context of the constant b esides the ordinary term constructions When a pro of is

completed in a satisfactory way it can b e moved from the scratch area to the dictionary and

from that p oint it is no longer p ossible to mo dify On the other hand as long as the pro of is

still in the scratch area completed or not it can b e mo died by these op erations There are

two dierent ways of backtracking by removing the denition of a constant or by removing the

entire constant declaration The former op eration can b e useful for retrying a not so successful

attempt of constructing a pro of and the latter when a lemma or subgoal is declared which was

found not to b e useful

Pro of construction

For constructing a pro of we have the following op erations available extending the scratch

area with new goals or lemmas making a global replacement of a constant with its denition

unfolding and rening a goal The renement of a goal can b e done top down by rening

with a constant which generates new subgoals or b ottom up by explicitly giving the pro ofterm

or a combination of the two Each renement is checked to b e admissible which means that

the set of constraints is not violated

Extending the scratch area

The scratch area can b e extended with a new constant declaration a new named

context or substitution or a new waiting pattern The constant declaration can b e yet

unknown new goal or it can b e partially or totally dened Contexts and substitutions

can dep end on yet unknown constants as well and therefore give rise to constraints

but can not b e altered A new waiting pattern can b e added rened completed and

moved to the theory without changing the rest of the scratch area To summarize any

extension of the scratch area is allowed at any time provided that the set of constraints

is not violated

Unfolding a denition

If c e is a declaration in the scratch area then c is replaced everywhere in

the set of declarations by e and the declaration is removed The dep endency graph

is up dated which means that each incoming p ointer of no de c is replaced by the set

of outgoing p ointers and the no de is removed The set of constraints is not aected

by this op eration since all denitions are always expanded as far as p ossible in the

constraints and the only change in the backtrack area is that c b ecomes invisible

Top down and b ottom up renements

To rene a constant c with a term e we need to type check if e is of prop er type But to

b e able to type check all constants in e must b e known in advance which means that

they must b e declared in the environment Therefore is the term given as a renement

prepro cessed b efore type checking The prepro cess consists of doing the following

if the arity of e is greater than the arity of c which means that e needs more

arguments to b e of prop er type then e is applied to a prop er number of system

generated new names

a new name in the term is considered to b e a new subgoal which means that the

type and context of such a subgoal is computed and the new unknown constant

declaration is added to the scratch area The computation of type and context is

done as for pattern variables

if the symbol is given instead of a new name the system will generate a unique

name All system generated names b ecome by default invisible constants whereas

user names b ecome visible The purp ose of this setup is to name important

the others subgoals and neglect by using

all the transformations ab ove are done recursively in the subterms for partially

given terms

Admissible renement

The algorithm for checking if the renement of the constant c with the term e is

admissible pro ceeds with the following three steps pro ducing a rened scratch area if

the renement is admissible and a F ail otherwise

Preconditions

c c is a yet unknown constant

J e the type checking do es not fail

c DepUe the new denition is not circular with resp ect to c

Up dating the scratch area

is replaced by e in the declaration of c

c is replaced by e everywhere in the set of constraints and is added to that

set

the dep endency graph is up dated ie TermDepc the set of constants

o ccurring in e

is replaced by e in the backtrack area

if c is invisible then c is unfolded and removed the op eration Unfold

Rening the scratch area

the set of constraints is rened which means that each constraint e e

is rechecked by

J e e

and replaced by If J fails the entire renement is rejected The reason for

rening the set of constraints is that the replacement of e for c might have

created a failure constraint

if the set of constraints contain a simple constraint

c e w hichisnotcir cul ar then the c is up dated to e in the

scratch area as in except for the replacement in the backtrack area which

remains the same The reason to keep constraints which are circular is that

if x y x is the constraint then the equality will hold if y is instanciated

to z for example

These two steps are rep eated until there are no simple constraints and the rene

ment is admissible or some rened constraint pro duces a F ail and the renement

is not admissible

Pro of completion

This op eration consists of two parts to check that the construction of the constant is completed

and if so move the constant declaration to the dictionary

A complete pro of

A precise denition of a complete constant pro of is that c is complete i c U and

DepUc A complete denition or judgement is when all constants o ccurring

in the denitionjudgement are complete A pro of can consist of several constant

declarations one main constant corresp onding to the pro of and other minor constant

declarations corresp onding to lemmas All these constants must b e in the subgraph

of the pro of which means that all lemmas must b e used in the pro of

Moving a complete pro of to the dictionary

To move a pro of c from the scratch area to the dictionary the following steps needs to

b e done

check that c is complete and compute the set of constants fc c g which is

n

used in c

sort c fc c g in their top ological order c will always b e last and add

n

the constant declarations to the dictionary in this order which will satisfy the

condition of a valid extension

the declarations of c and fc c g are simply erased from the scratch area

n

including the backtrack area There is no problem in erasing the declarations

since the constants are complete and since they are moved and not removed and

can still app ear in other declarations The subgraph of c is removed from the

dep endency graph since it only concerns scratch area constants

Backtracking

Any deletion of a constant or a constant denition are pro ceeded by an allowance check

b efore the actual deletion is p erformed in the backtrack area and nally the new scratch

area is computed from the diminished backtrack area We will pro ceed by rst describing the

recomputation of a scratch area and then the two kinds of deletion pro cedures are explained

Note that the constant declarations and dep endency graph mentioned in these explanations

refer to the backtrack area

Recompute the scratch area

Recomputation of the scratch area is done after any kind of backtracking since the

old scratch area is not of any use at that p oint The following steps will compute a

scratch area from a backtrack area which will have the same corresp ondence b etween

them as describ ed in section

Unfold the denitions of all invisible constant declarations everywhere

sort the remaining declarations top ologically

extend an empty scratch area with the constant declarations in order yielding a

set of constraints

and nally rene the scratch area constraints as in step of the rene op eration

Remove a constant declaration

The entire constant declaration c e is removable if there are no other constants

dep ending on any of the constants c c c where fc c g Depc except

n n

internal dep endencies b etween these constants The reason for this requirement is

simple if there is a declaration in which the type or context dep end on say c then the

same declaration would not make sense if c is removed Describing that c is removable

in terms of dep endency graph is to say that the subgraph of c must b e disconnected

from the rest of the graph

Remove the denition of a constant

The denition e of a constant declaration c e can b e removed replaced by

if the set of constants fc c g DepUe which e dep ends on are all removable

n

The reason we want to remove the constant declarations of c c is that they all

n

corresp ond to steps in the derivation of c and we want to remove the entire derivation

To b e more precise the denition of c is allowed to b e removed if the subgraph of c

is only connected externally to other parts of the graph via the no de c The actual

pro cedure of removing the denition take place in three steps by rst replacing the

denition of c with then removing the constant declarations of c c and nally

n

recompute the scratch area from this revised backtrack area In the dep endency graph

the subgraph of c except the no de c itself is deleted

The only reason for not allowing a removal of a constant or denition is that this op eration

would remove some constant which is used elsewhere Sometimes this can b e arranged by

further removals of constants andor denitions but we have taken the stand p oint not to

do any clever decisions of what to remove b esides the obvious parts and instead disallow

removals of this kind Since anything is p ossible to remove as long as it is done in the prop er

order the restriction seems motivated

Validity of the scratch area future work

As already mentioned this is an implementation of exp erimental nature trying out several

ideas simultaneously The scratch area involves most of these ideas and this part needs to b e

describ ed more formally hop efully reaching at a p oint where we can state and prove prop erties

such as

if the constraints concerning a denition is satised then the denition corresp onds to a

true judgement this is now given as a denition

dene the relation b etween scratch area and backtrack area and show that the relation

is preserved for the dierent op erations on the scratch area

dene the partial order of denedness concerning the scratch area and show that back

tracking will always result in a less dened scratch area

Conclusion

Since this new implementation is still under developement we will have to do much more

exp eriments to b e able to evaluate the new features However a few larger examples are

carried out in ALF such as a normalization pro of for simply typed calculus Co qa another

normalization pro of for the typed combinator calculus GS as well as some prop erties of well

quasi ordered sets Fri

References

ACN L Augustsson T Co quand and B Nordstrom A short description of Another Logical Frame

work In Proceedings of the First Workshop on Logical Frameworks Antibes pages

Co qa Catarina Co quand A pro of of normalization for simply typed lambda calculus written in alf

In To appear in the informal proceeding from the logical framework workshop at Bastad June

Co qb Thierry Co quand Pattern matching with dep endent types In To appear in the informal

proceeding from the logical framework workshop at Bastad June

Fri Daniel Fridlender Formalizing prop erties of wellquasi ordered sets in alf In To appear in the

informal proceeding from the logical framework workshop at Bastad June

GS Veronica Gasp es and Jan M Smith Machine checked normalization pro ofs for typed combi

nator calculi In To appear in the informal proceeding from the logical framework workshop at

Bastad June

Mag Lena Magnusson An Implementation of MartinLofs Logical Framework Licentiate Thesis

Chalmers University of Technology and University of Goteborg Sweden June

NPS Bengt Nordstrom Kent Petersson and Jan M Smith Programming in MartinLofs Type

Theory An Introduction Oxford University Press

An implementation of Constructive Set Theory in the Lego

system

Nax Paul Mendler

Computer Science Department

University of Manchester

Manchester M PL

August

Remark by Peter Aczel This note was written by Nax Mendler just b efore he left the

LF pro ject in November My talk at the workshop was a rep ort on his work

This note contains comments to accompany a le library I wrote for Randy Pollacks Lego

system

In the pap er Peter Aczel describ ed a constructive set theory CST and gave an interpre

tation of it into Martinlof type theory I to ok this pap er and implemented this interpretation

in the Extended Calculus of Constructions using Lego The b est and p erhaps only way to study

this Lego le is to read it or enter it into the system as you follow along in the original pap er

and Ive tried to have the Lego le match it as closely as p ossible

In Lego I used the Extended Calculus of Constructions theory and extensively used the

new facility for adding userdened combinators and reductions The most imp ortant example

of this is the type called V used to interpret the universe of sets it is the wellfounded type

W x Type x and its induction combinator was used in dening a bisimulation relation which

mo dels extensional equality on sets

The only subtle technical p oint of the Lego implementation was that while the original

pap er assumed the existence of extensional identity types in the type theory one can rework

a few arguments and use denitional equality instead This is not to o surprising I think it

so on b ecomes clear whether one can or cant eliminate the use of extensional identity types in

a given piece of type theory and in this case I was lucky

So in this Lego library the prop ositionsastypes interpretations or translations of the ax

ioms of CST are all proven The intention is that one can then go on to do some set theory

in Lego and also b e able to execute the constructive content of the pro ofs One example that

we thought might b e of a reasonable size is to dene and prove some basic facts ab out the

hereditarily nite sets

Just a few sentences on what this exp eriment has taught me ab out the Lego system Ive

used Lego b efore although this was my rst long example using the combinator denition

facility As Ive come to exp ect from the system what it is meant to do it do es with style I

already knew the basic denition mechanism and type synthesis would prove useful and I was

pleased with the new userdened combinator facility I was happy with how fast the system

ran to o But as for the question of why do any formal theorem proving on computer I still

can not b e p ositive my example should only b e viewed as evidence that it is p ossible to sit

down and enter these sorts of formal pro ofs not as an endorsement of the activity

References

Peter Aczel The type theoretic interpretation of constructive set theory Choice principles

In AS Troelstra and D van Dalen editors The LEJ Brouwer Centenary Symposium pages

NorthHolland

ZLuo A higherorder calculus and theory abstraction Information and Control

January

lambda mucalculus an algorithmic interpretation of classical

natural deduction

Michel Parigot Paris

Abstract

We present a way of extending the paradigm pro ofs as programs to classical pro ofs

The system used is a natural deduction system with multiple conclusions It has two kinds

of reduction rules logical and structural ones logical ones corresp ond exactly to those of

intuitionistic natural deduction

The computation mechanism can b e describ ed as a pure calculus called lambda mu

calculus which extends in a simple manner lambdacalculus mu lo oks like a lambda having

a p otentially innite number of arguments Pure lambda mucalculus satises the Church

Rosser prop erty Typed lambda mu calculus satises also the type preservation and strong

normalisation prop erties

lambda mucalculus has a simple abstract environment based machine the new instruc

tions in addition of those of lambdacalculus are save the stack and restore the stack

Teaching Theory of Programming Languages Using a Logical

Framework an Exp erience Rep ort

Frank Pfenning Carnegie Mellon

Abstract

During the Spring semester I taught a graduate course Computation and Deduc

tion This course explored the theory of programming languages using systems of natural

deduction Such systems were used to sp ecify implement and verify prop erties of functional

imp erative and logic programming languages The deductive approach to the sp ecication

of programming languages has b ecome standard practice and one of the goals of this course

was to provide a go o d working knowledge of how to engineer and prove prop erties of lan

guage descriptions in this style Throughout the course we used Elf as a metalanguage Elf

is a logic programming language based on the LF Logical Framework and was introduced

by means of a few extended examples An implementation of Elf and all the examples were

available online for exp erimentation Overall there were lectures of hours each of

which were given by students presenting pro jects

The rigorous use of Elf as a metalanguage was seen as a very p ositive factor Otherwise

dry exercises b ecame programming problems and the students learned how to employ Elf

eectively to implement languages and their metatheory Type reconstruction and a few

other features of the Elf implementation turned out to b e usable and valuable It was

generally felt that the expressive p ower of the LF logical framework was adequate although

a few extensions emerged as desirable in practice These were a simple denitional equality

a limited form of subtypes and overloading and a mo dule system

In my talk I will outline the approach and content of the course Furthermore I will

sketch some initial ideas on how to enhance the expressive p ower of LF in directions moti

vated by the course exp erience

Typechecking in Pure Type Systems

Randy Pollack

LFCS University of Edinburgh

July

Retraction

At Baastad I claimed a pro of of the Expansion Postponment prop erty for functional PTS Eric

Poll of Eindhoven p ointed out an error in my claimed pro of As far as I know this problem is

still op en

Introduction

This work is motivated by two related problems The rst is to nd reasonable algorithms for

typechecking Pure Type Systems Bar PTS the second is a technical question ab out PTS

the so called Expansion Postponment prop erty EP which is tantalizingly simple but remains

unsolved

There are several implementations of formal systems that are either PTS or closely related

to PTS For example LEGO LP implements the Pure Calculus of Constructions CH

PCC the Extended Calculus of Constructions Luo and the Edinburgh Logical Frame

work HHP ELF Pfe implements LF CONSTRUCTOR Hel implements arbitrary

PTS with nite set of sorts Are these implementations actually correct It is not dicult to

nd a natural ecient algorithm that is provably sound Section but completeness is more

dicult In fact Jutting has shown typechecking is decidable for all normalizing PTS with a

nite set of sorts vBJ but his algorithm which computes the normal forms of types is not

suitable for practical use

The Decision Problems

We consider two problems ab out PTS The Type Checking Problem TCP is to decide given

M and A whether or not M A is derivable In implementations we want to enter a

term and have the program compute its type in the current context For PTS with types unique

up to conversion the functional PTS this Type Synthesis Problem TSP is clear given and

M compute a term A such that M A or return failure if no such A exists In general

however PTS do not have unique types and an exact statement of TSP involves a notion of

type scheme which will b e p ostp oned to Section

Let s range over fProp Type g the sorts of PCC

ax Prop Type

A s

x fresh start

xA x A

C A s

weak x fresh

xA C

x A B s

pi

fx AgB s

xA M B

B Type lda

x AM fxAgB

M fx AgB N A

app

M N N xB

M A B s A B

conv

M B

Table The Pure Calculus of Constructions PCC

An Example Typechecking Pure Constructions

Without b eing to o precise for the moment Table presents typing rules for the Pure Calculus of

Constructions PCC Consider the type synthesis problem for PCC given and M compute

a term A such that M A or return failure if no such A exists The natural approach is to

guided by the shap e of the sub ject and M The only aw lo ok for a derivation of M

in this plan is the rule conv which may b e used at any p oint in a derivation without changing

the shap e of the sub ject Putting it the other way around you cannot tell when to use conv

in a derivation by lo oking at the shap e of the sub ject It is clear we must control the conv

rule In my rst typechecker for PCC co ded in my approach was to compute the normal

forms of types This eliminates the need for conv and since PCC is normalizing leads to a

sound and complete algorithm if done correctly For example you must check that a term is

welltyped before trying to normalize it This approach is terribly slow and clearly could not

b e used to check large b o dies of mathematics

In Gerard Huet showed me a collection of techniques for eciently typechecking PCC

that he collected into an abstract machine called the Constructive Engine Hue The most

imp ortant asp ect of the Constructive Engine is shown abstractly in Table The correctness

lemma for this system is

Lemma If M A then M A

ce

If M A then there exists A such that A A and M A

ce

Table b ecause of its nondeterminstic use of conv allows many derivations over a given

sub ject even deriving structurally dierent types for a single sub ject It is a prop erty of PCC

that all those types are convertible In contrast the system of Table has no conv rule and

allows at most one derivation over a given and M and that derivation uniquely determines

w h

Notation we write M A for M A and A A where is reduction and

ce ce

is weakheadreduction

ceax Prop Type

ce

A s

ce

x fresh cestart

xA x A

ce

C A s

ce ce

x fresh ceweak

xA C

ce

xA B s

ce

cepi

fx AgB s

ce

xA M B

ce

B Type celda

x AM fx AgB

ce

w h

M fx AgB N A A A

ce ce

ceapp

M N N xB

ce

Table A Preliminary Constructive Engine syntaxdirected PCC

the type it derives for M in Consequently Table cannot derive all the structurally dierent

types for M in but only one representative of the conversion class

Notice that for correctness we could allow arbitrary reduction sequences where we have

written weakhead reduction in ceapp but the restriction to deterministic weakhead reduction

is necessary to make this rule syntax directed otherwise we wouldnt know when to stop reducing

in the left premiss and A and B wouldnt b e uniquely determined

We can think of Lemma as saying all uses of conv for expanding a type can b e p ermuted

downwards in a derivation through all premisses of all rules and all uses of conv for reducing

a type can b e p ermuted downwards in a derivation through the left premiss of weak and the

premiss of lda The fact that Table is syntax directed is extremely delicate although we

didnt know this in b ecause the pro of of Lemma is quite straightfoward In PTS it is

still unproven that type expansion can always b e deferred to the end of derivations and we know

by counterexample Example that type reduction cannot always b e p ermuted through the

premiss of lda

Table can already b e thought of as a sound and complete type synthesis algorithm for

PCC but there is one other signicant optimization in the Constructive Engine that is worth

mentioning even though it is not delicate and gives no problems in the case of PTS In the

rules ceweak and ceapp o ccurs in two premisses and its validity must b e checked in

the sub derivations ab ove b oth premisses It is much more ecient to assume we start with a

valid context and only check that it remains valid whenever we extend it This is also more in

keeping with the use of actual implementations where we want to work in a current context

of mathematical assumptions and also of denitions and proved theorems but I do not address

denitions in this note This is shown abstractly in Table The new premisses in ceopi and

ceolda are to check that the extended contexts in the second premisses are valid assuming

that is valid The correctness lemma for this system is

Notation we write M A for M A and A A

ceo ceo

Valid A s

ceo

ceovalid Valid x fresh

xA Valid

ceoprop Prop Type

ceo

ceovar xA x A

ceo

A s xA B s

ceo ceo

ceopi

fx AgB s

ceo

A s x A M B

ceo ceo

B Type ceolda

x AM fx AgB

ceo

w h

M fxAgB N A A A

ceo ceo

ceoapp

M N N xB

ceo

Table An Optimised Constructive Engine

Lemma If M A and Valid then M A

ceo

If M A then there exists A such that A A and M A

ceo

Setting aside the question of how to test conversion we consider Table to b e a go o d algorithm

for typechecking PCC

The remainder of this note

For arbitrary PTS there are several new diculties The most troublesome is that we dont

know how to eliminate the conversion rule in favor of a syntaxdirected system for arbitrary

PTS The diculty in following the Constructive Engine approach is discussed in Section

In Section we give a syntaxdirected presentation of a restricted class of PTS that includes

PCC and the Edinburgh Logical Framework LF Thus we nally have a pro of of an ecient

and natural algorithm for typechecking LF It may b e of interest that the correctness of the

syntaxdirected system for this class of PTS has b een machine checked in LEGO LP except

for a few facts ab out reduction and conversion This class also has the Expansion Postponment

prop erty

In PCC there are only two sorts Prop and Type and PCC has types unique up to conversion

In general a PTS may have innitely many sorts and fail to have unique types Even if we have

a syntaxdirected presentation for a class of PTS where all derivations over a given sub ject

have the same shap e undecidable and nondeterministic side conditions may complicate an

algorithmic interpretation Such issues are well understo o d and I show how to handle them in

Section

Pure Type Systems

In order to x notation we dene PTS and state some well known prop erties A PTS P is a

tuple Cnst Sort Ax Rule where

Cnst a set of constants ranged over by c

Sort Cnst a set of sorts ranged over by s

Ax Cnst Sort a set of axioms of the form Axc s

Rule Sort Sort Sort a set of rules of the form Rules s s

Syntax Let x range over Var an innite set of variables disjoint from Cnst The raw syntax

of terms contexts and judgements of PTS P Cnst Sort Ax Rule is given by

atomic terms x variable

j c constant

terms M atomic

j xM M lambda

j fxM gM Pi

j M M application

contexts empty

j xM

judgement J M M

M N A B C D E a b range over terms over contexts

FV M denotes the free variables of M dened as usual If x A x A then

n n

S

V is dened as the set fx x g and FV as the set fFV A FV A g If

n n

x A we say xA is dened to mean x A implies xA

Reduction Substitution reduction and conversion are dened as usual for such lan

guages Write NxB for captureavoiding substitution of N for free o currances of x in B

w h

A B for A reduces to B A B for A weakhead reduces to B and A B for A con

verts to B reduction has the ChurchRosser CR prop erty nf A B is the relation B is

the normal form of A

Typing The judgements of P are those derivable from the axioms and inference rules of

Table As usual we abuse notation by writing M A to mean the judgement is derivable

We say Valid i there exist M and A with M A

The cognoscenti will notice that the rule weak in Table is not the usual one I have

restricted weakening to atomic sub jects for the purp ose of discussing typechecking since this

presentation is more syntaxdirected It is straightfoward to see that the full weakening rule

is admissible in this system In fact this presentation gives a b etter development of the basic

metatheory b ecause no case of the Generation Lemma except start dep ends on the Thinning

Lemma The basic metatheory of this presentation of PTS has b een formalized in LEGO

Basic Theorems

The basic metatheoretic prop erties of PTS are presented in Bar Ber GN vBJ The

ones we will explicitly use are summarized here

Lemma Thinning Lemma If M A and Valid then M A

ax c s Axc s

A s

start x fresh

xA x A

C A s

weak x fresh

xA C

A s xA B s

Rules s s pi

fx AgB s

xA M B fx AgB s

lda

x AM fx AgB

M fx AgB N A

app

M N N xB

M A B s A B

conv

M B

Table The Typing Judgement of a PTS

Lemma Generation Lemma If c A then there exists s such that Axc s and

A s

If x A then there exists A such that x A and A A

If fxB gD A then there exist s s s such that Rules s s B s

xB D s and A s

If xB d A then there exist s and D such that xB d D fx B gD s and

A fx B gD

If b d A then there exist B D such that b fxD gB d D and A dxB

Lemma Correctness of Types If b B then there exists s such that B s or

B s

Lemma Sub ject and Predicate Reduction If b B b b and B B

then b B

A PTS is called functional if Axc s and Axc s imply s s and Rules s s and

Rules s s imply s s Functional PTS have types unique up to conversion

A First Lo ok at Decidability

We cannot exp ect to decide typechecking for a PTS whose axioms or rules are not decidable

although none of the basic metatheory mentioned so far uses such an assumption so from

now on assume they are decidable

At rst blinded by the b eauty of the Constructive Engine I conjectured that all normalizing

PTS have decidable TCP This b elief is sadly mistaken

th

Example Let Ti n mean the i Turing machine when started with i on its input tape

halts in exactly n steps For the PTS

Cnst natural numbers

Sort natural numbers

undecidabl e

Ax f i n j Ti n g

Rule

th

we have for any i x i x i i there exists n with Axi n i the i Turing machine halts on

input i This PTS is functional and strongly normalizing there are no wel l typed redices but

has undecidable TCP

Most General Type Schemes

Is there hop e to nd systems of syntaxdirected derivations for nonfunctional PTS Supp ose

there are judgements of the shap e b fx B gs and b fx C gfx C gs where the

types are in normal form We wouldnt exp ect a derivation determined by the shap e of

and b to construct b oth of these types since they have dierent shap es In fact this problem

do esnt arise I b elieve the following prop erty was rst observed by Luo for ECC Luo and

indep endently discovered by Jutting for PTS vBJ

Lemma If a A and a B then either i A B or ii there exist s s n

A B

C C such that A fx C g fx C gs and B fx C g fx C gs

n n n A n n B

As a corollary we have that if a A and a B then there is an A obtained by replac

ing some of the sort o ccurrences in A by other sorts such that B A We introduce some

machinery to talk ab out this idea

Sort Variables and Constraints Let b e a new class of sort variables disjoint from Cnst

and Var ranged over by Schematic terms ranged over by X Y Z U are terms that may

contain sort variables as well as sorts

x j c j

X j x X X j fx X gX j X X

SV X is the set of sort variables o ccurring in X

A sort asignment ranged over by is a partial function assigning sorts to a nite set of

sort variables Dom is the domain of as a function

Reduction conversion and sort assignments are extended to schematic terms in the obvious

way We call X an instance of X Notice that resp ects the structure of terms and resp ects

redices so can b e thought of as a bijection b etween the reduction sequences from X and the

reduction sequences from X In particular X has a normal form exactly when X do es

Most General Type Schemes By Lemma if M A then there is an X such that

every type for M in converts with an instance of X The problem is to nd just those instances

of X that actually are correct types for M in

A constraint is any formula whose only free variables are sort variables We have in mind

formulas of the form Axc Rule and C D E F G range over nite sets

of constraints SV C is the set of sort variables o ccurring in C A sort assignment satises a

constraint set written j C i SV C Dom and each of the prop ositions in C is true

A constraint set is satisable or consistent if there is some sort assignment satisfying it

Assume we have sp ecied a class of constraints such that the consistency of every set of

such constraints is decidable For example for a PTS with nite Sort the class including all

formulas of the form Axc Rule and is such a class remember we are

assuming Ax and Rule to b e decidable Let Z b e such a class although we will usually keep

this class implicit

A pair X C where C Z is a most general type scheme mgts for M with resp ect to

Z i i whenever j C then M X and ii whenever M A there is a j C such

that A X

The Type Synthesis Problem TSP for a PTS is to nd a class Z and an algorithm that

given and M computes a most general type scheme X C for M with resp ect to Z

We will now show that for a given PTS if TSP is solvable then TCP is also solvable

Schematic Conversion In order to compute the constraints under which two schematic

terms are convertible we need a sortvariables unication algorithm

f g

1 2

c c x x

C D C D C D

X Y X Y X Y X Y X Y X Y

C D C D C D

fx X gX fx Y gY xX X xY Y X X Y Y

Now we have the schematic conversion algorithm

C

Y nf X X nf Y Y X

C

X Y

C

Lemma For normalizing X and Y if X Y and j C then X Y

C

if X Y then there exists C such that X Y and j C

C

it is decideable whether or not there exists a C such that X Y

This algorithm is not very ecient and in practice we try to minimize the reduction involved

in checking that two terms convert

TCP Now assume that for a given normalizing PTS we have a solution to TSP and we want

to use that to solve TCP we are given M A and want to decide whether or not M A

Let X C b e an mgts for A and Y D b e an mgts for M If C is not consistent then A is

not a type in if D is not consistent then M has no type in If b oth C and D are consistent

E

then A and X are normalizing so use the schematic conversion algorithm to compute X A

If C D E is consistent then M A is derivable otherwise not Some of the algorithms

may return explicit failure which Im reading as returning an inconsistent constraint set

Expansion Postponment and SyntaxDirected derivations

Our rst goal for nding a Type Synthesis Algorithm for PTS is to nd a syntaxdirected

derivation system equivalent to Table in some way analogous to the Constructive Engine

erax c s Axc s

er

A s

er

erstart x fresh

xA x A

er

C A s

er er

erweak x fresh

xA C

er

A s xA B s

er er

Rules s s erpi

fx AgB s

er

xA M B fx AgB s

er er

erlda

xAM fx AgB

er

M fx AgB N A

er er

erapp

M N N xB

er

M A A B

er

erred

M B

er

M A B s B A

erexp

M B

Table The expansionreduction type system ERTS

The only troublesome rule is conv The natural generalization of the Constructive Engine

Table do es not work and to clarify the situation we consider some intermediate systems rst

In informally describing the Constructive Engine I suggested we view the conversion rule as

two rules one for expansion and one for reduction The system ERTS of Table makes this

precise

Lemma M A i M A

er

Pro of By induction on the derivation of M A Assume the derivation ends with

M A B s A B

conv

M B

By IH M A and B s By ChurchRosser B and A have a common reduct B so

er er

M B by red and M B by exp

er er

By induction on the derivation of M A If the derivation ends with erred use

er

Predicate Reduction of PTS if it ends with erexp use conv

Expansion Postponment Continuing by analogy with the Constructive engine we try to

prove that all uses of erexp can b e deferred until the end of a derivation or equivalently that

erexp can b e p ermuted downwards through all premisses of all rules Consider the system

rax c s Axc s

r

A s

r

rstart x fresh

xA x A

r

C A s

r r

rweak x fresh

xA C

r

A s xA B s

r r

Rules s s rpi

fx AgB s

r

xA M B fx AgB s

r r

rlda

x AM fx AgB

r

M fx AgB N A

r r

rapp

M N N xB

r

M A A B

r

rred

M B

r

Table The reduction type system RTS

RTS of Table It is trivial that RTS is sound for PTS ie that M A implies M A

r

However the expansion postponment conjecture that RTS is complete for PTS

Conjecture Expansion Postponment If M A then there exists A such that

A A and M A

r

has resisted all attempts to date for any interesting class of PTS In Section I show that a

class called semifull generalizing the full PTS has this prop erty

If we could prove Conjecture would we have a syntax directed presentation of PTS

Asking which premisses rred can b e p ermuted downwards through we get the system NSDTS

of Table which is equivalent to RTS

Lemma If M A then M A

nsd r

If M A then there exists A such that M A and A A

r nsd

This is straightfoward to prove

In the Constructive Engine reduction could b e deferred through the premiss of lda In

NSDTS reduction gets stuck at the left premiss of nsdlda and for this reason NSDTS is

not syntaxdirected we cannot tell from the shap e of a AM how much reduction to do to

nd B Can we hop e to remove this deciency Consider system SDTS of Table which is

identical to NSDTS except it do esnt allow reduction after the left premiss of the lambda rule

Clearly M A implies M A so we have somewhat inexactly

sd nsd

SDTS NSDTS RTS ERTS PTS

Expansion Postponment is the conjecture that RTS ERTS Now we ask whether

SDTS NSDTS ie whether EP implies a system of syntaxdirected derivation For non

functional PTS this is false

Notation we write M A for M A and A A

nsd nsd

nsdax c s Axc s

nsd

A s

nsd

x fresh nsdstart

xA x A

nsd

C A s

nsd nsd

nsdweak x fresh

xA C

nsd

A s xA B s

nsd nsd

Rules s s nsdpi

fx AgB s

nsd

xA M B fx AgB s

nsd nsd

nsdlda

x AM fx AgB

nsd

M fx AgB N A A A

nsd nsd

nsdapp

M N N xB

nsd

Table The nearly syntaxdirected type system NSDTS

Notation we write M A for M A and A A

nsd sd

sdax c s Axc s

sd

A s

nsd

x fresh sdstart

xA x A

sd

C A s

sd nsd

sdweak x fresh

xA C

sd

A s xA B s

nsd nsd

Rules s s sdpi

fx AgB s

sd

xA M B fx AgB s

sd sd

sdlda

xAM fxAgB

sd

M fx AgB N A A A

nsd sd

sdapp

M N N xB

sd

Table The syntaxdirected type system SDTS

Example We show that NSDTS types terms that SDTS does not type ieSDTS NSDTS

by modifying an example that Jutting vBJ uses to show nonfunctional PTS may not have

Subject Expansion

Cnst 2

Sort 2

pathol og ical

Ax 2

Rule 2 2 2 2

Consider A x To compute al l the types SDTS gives A build the only possible

derivation over A since SDTS is syntaxdirected and try to l l in any holes left undetermined

due to the nonfunctionality of this pathological PTS We wil l use this technique more uniformly

in Section

2 x X Z

sd sd

x X

sd

fxgX 2

sd

sd

x fx gX

sd

A xX

sd

First Z 2 because only the rst rule can be used to type fx gX Now observe that X

or X since these are the only types of But 2 Ax so X is the only solution

and we have only A In fact even in PTS this is the only solution Since A

sd

A but not A this PTS lacks Subject Expansion

Now observe y A z y fz g

nsd

y A y Az y A y A y A

nsd nsd nsd nsd

y Az y A y A fz g 2

nsd nsd

y A z y fz g

nsd

but SDTS does not assign any type to z y in context y A as we see by trying to construct

such a derivation

y A y Az A Y

sd sd

y Az y A

sd

y A fz gA X

sd

y A z y fz gA

sd

so there is no X making this By the analysis above Y but there is no rule for

a correct derivation

This PTS is strongly normalizing as can be seen from the PTSmorphism Geu

Type Type Type 2 Type

into a predicative part of ECC Since this mapping preserves sorts axioms and rules if a term

is wel ltyped in pathological its image is wel ltyped in ECC hence strongly normalizing But

the map also preserves redices so the original term is strongly normalizing It is clearly the

nonfunctionality of pathological that is the problem

What is the Diculty The diculty in proving EP and that in proving SDTS NSDTS

are similar In the lda rule the predicate of the left premiss B o ccurs in the sub ject of the

right premiss fxAgB This is the only rule in which this happ ens For any of the systems ab ove

without full conversion we cannot derive all types of all terms the b est correctness prop erty

we can have allows some extra conversion or reduction after a derivation In lda then the

B o ccurring in the left premiss will b e dierent than the B o ccurring in the right premiss If

we could prove sub ject reduction of RTS the pro of would go through but the pro of of sub ject

reduction for RTS founders on the same diculty We have seen that SDTS NSDTS must

fail in general I dont know whether it is true for functional PTS Is this a hint that EP fails

in general If so is EP true for functional PTS

Recently Jutting has b een lo oking at alternative wellformedness conditions to replace the

right premiss of lda He has had great sucess in nding syntaxdirected systems which can b e

made into typechecking algorithms I do not know whether this sheds any light on EP

SemiFull PTS and Typechecking

A PTS is ful l i for all s s Sort there exists s Sort such that Rules s s In full PTS

the troublesome right premiss of the lda rule can b e simplied Consider the rule

xA M B fx AgB s

lda

x AM fx AgB

The right premiss guarantees the type of the lambda b eing constructed is itself well formed

We know from the left premiss of lda that A s for some s Also by Correctness of

A A

Types applied to the left premiss there is some s such that either xA B s or B s

B B B

In the rst case fullness of a PTS guarantees fx AgB has some type Thus for full PTS we

can soundly replace the right premiss of lda with a side condition that B is not identically a

sort that itself has no sort We can generalize this idea somewhat b eyond full PTS

Denition A PTS is semiful l i for all s Sort if there exist s s Sort such that

Rules s s then for all s Sort there exist s Sort such that Rules s s

While the Pure Calculus of Constructions P and various extensions with Type universes

are full the Edinburgh Logical Framework P is semifull Although HHP proves LF is

decidable it gives an algorithm to compute the normal forms of types The argument b elow

shows why the algorithm actually used in LEGO and probably in ELF is b oth sound and

complete

We will give a syntaxdirected derivation system for semifull PTS and from it derive an

algorithm for typechecking which is a natural generalization of Huets Constructive Engine

Aside on Topsorts

We b egin with a denition and a lemma of Berardi Ber

T

Denition A sort s is a topsort written s Sort i for all t Sort not Axst

T

Lemma If s Sort and M A then

s does not occur in M and

if s occurs in A then s A

sfax c s Axc s

sf

A s

sf

sfstart x fresh

xA x A

sf

C A s

sf sf

sfweak x fresh

xA C

sf

A s xA B s

sf sf

Rules s s sfpi

fx AgB s

sf

T

xA M B A s

B Sort

sf sf

sflda

Rules s s

xAM fxAgB

sf

M fx AgB N A

sf sf

sfapp

M N N xB

sf

M A B s A B

sf sf

sfconv

M B

sf

Table The typing judgement of a semifull PTS SFTS

Prove by straightfoward induction over the derivation of M A Prove similarly

using

The Correctness of Types lemma for PTS is somewhat unsatisfying why do esnt it read

If b B then for some s Sort B s The reason is the existence of topsorts and

we would like to improve Correctness of Types to read If b B then for some s Sort

T

B s or B s and s Sort This is not quite right b ecause even if Ax is decideable

T

Sort may not b e Furthermore topsort is a negative notion we need the more informative

concept

Denition A sort s is a typedsort written s Sort i there exists t Sort such

T

that Axs t

A PTS has the decidable typedsort property DTP i for all s Sort s Sort or s Sort

T T

T

Lemma If a PTS has DTP and b B then s Sort such that B s or s Sort

and B s

Pro of By the Correctness of Types lemma B s or B s In the rst case we are done

In the second case by DTP s Sort or s Sort In the rst case for some t Axst hence

T T

T

B t In the second case s Sort as required

Deriving the Judgement of SemiFull PTS

For semifull PTS with DTP the derivation system SFTS of Table is sound and complete

with resp ect to the system PTS of Table

Lemma For a semiful l PTS with DTP

if M A then M A and

sf

if M A then M A

sf

Pro of By induction over the derivation of M A The only interesting case is lda

so assume the derivation ends with

xA M B fxAgB s

lda

x AM fxAgB

By IH xA M B and fx AgB s By the Generation Lemma for SFTS there exists

sf sf

s s s Sort such that A s x A B s and Rules s s Lemma on

A B sf A sf B A B

T

the right IH shows B Sort Thus by sflda conclude x AM fx AgB

sf

By induction over the derivation of M A The only interesting case is sflda

sf

so assume the derivation ends with

T

xA M B A s

B Sort

sf sf

sflda

Rules s s

xAM fxAgB

sf

T

By IH x A M B and A s By Lemma on the left IH and the fact that B Sort

there is a sort s such that xA B s Since we are in a semifull PTS there is a sort t

B B

with Rules s t By pi and lda conclude x AM fx AgB

B

A SyntaxDirected System for SemiFull PTS

System SFTS is not syntaxdirected but sflda do es not have the troublesome right premiss

It is now straightfoward to give a syntaxdirected system SDSFTS of Table which is sound

and complete for SFTS

Lemma For a semiful l PTS with DTP

if M A then M A

sdsf sf

if M A then there exists A st M A and A A

sf sdsf

Pro of By induction over the derivation of M A noticing that by Lemma SFTS

sdsf

has Predicate Reduction for semifull PTS with DTP We do the case where the derivation ends

with sdsfapp

M fx AgB N A A A

sdsf sdsf

sdsfapp

M N N xB

sdsf

By IH M K where K fx AgB and N A where A A By ChurchRosser

sf sf

A and A have a common reduct A Thus K fx A gB and by Predicate Reduction

M fx A gB By sfapp conclude M N N xB as required

sf sf

sdsfax c s Axc s

sdsf

A s

sdsf

sdsfstart x fresh

xA x A

sdsf

C A s

sdsf sdsf

sdsfweak x fresh

x A C

sdsf

A s xA B s

sdsf sdsf

Rules s s sdsfpi

fxAgB s

sdsf

T

xA M B A s

B Sort

sdsf sdsf

sdsflda

Rules s s

xAM fx AgB

sdsf

w h

M fx AgB N A A A

sdsf sdsf

sdsfapp

M N N xB

sdsf

Table The syntaxdirected semifull type system SDSFTS

By induction over the derivation of M A We do one case Assume the deriva

sf

tion ends with sflda

T

xA M B A s

B Sort

sf sf

sflda

Rules s s

xAM fxAgB

sf

By IH x A M B where B B and A s In order to conclude

sdsf sdsf

T T

xAM fx AgB by sdsflda it remains to show B Sort If B t Sort

sdsf

then B t so t o ccurs in B Notice that xA M B by Lemma applied to the left

premiss hence B t by Lemma but this contradicts the given side condition

Finally we could apply the optimization discussed in Section which avoids duplicating

the context validity check Since this is straightfoward I forego this extra step

A Typechecking Algorithm for SemiFull PTS

SDSFTS of Table is syntax directed In the case of a normalizing functional PTS with nite

Sort we can already view SDSFTS as a type synthesis algorithm in straightfoward generalization

of the PCC example of Section Thus for LF we are done In general two more problems

arise in systems with innite Sort it may b e undecidable if there is an axiom for a given

constant c or a rule for given s s in nonfunctional systems we wont know which of several

axioms for c to choose or which of several rules for s s These problems are reduced to

a decision problem ab out the sorts axioms and rules of the PTS by making these decisions

schematically and collecting the conditions constraining the schematic choices This subsection

follows HP where more details of a related application of the same ideas can b e found The

same technique can b e used to derive algorithms from syntaxdirected derivation systems for

other classes of type theory such as the systems of Jutting

Notation we write M X C for M X C C consistent and X X

ds ds

dsax c fAx c g fresh

ds

A C

ds

dsstart x fresh

xA x A C

ds

X C A D

ds ds

x fresh dsweak

xA X C D

ds

A C xA B D

ds ds

dspi fresh

fx AgB C D fRule g

ds

x A M X C A D

ds ds

fresh dslda

T

xAM fx AgB C D fB Sort g fRule g

ds

w h

E

M fx X gY C N X D C D consistent X X

ds ds

dsapp

M N N xY C D E

ds

Table Derivation schemes for the syntaxdirected semifull type system SDSFDS

Recall the discussion of schematic terms in Section For our current purp oses a constraint

T

is one of the expressions Axc Rule or B Sort We henceforth assume

that the consistency of any set of constraints is decidable notice that this implies DTP For

example if Sort is nite as in LF this is clearly the case a system such as LF extended with

innitely many stratied universes also has this prop erty

Schematic Typing

Table is a system for derivation schemes of the system SDSFTS The judgements of SDSFDS

have the shap e M X C All the constraints that must b e satised for an instance of X

ds

to b e a correct type of M in are collected in C

Lemma For a semiful l PTS with consistency of constraint sets decidable if M X C

ds

then X C is a mgts for M

SDSFDS has an algorithmic interpretation returning failure if M has no type or an mgts for

M

References

Bar Henk Barendregt Introduction to generalised type systems J Functional Program

ming April

Bar Henk Barendregt Lambda calculii with types In Gabbai Abramsky and Maibaum

editors Handbook of Logic in Computer Science volume I I Oxford University Press

Ber Stefano Berardi Type Dependence and Constructive Mathematics PhD thesis Di

partimento di Informatica Torino Italy

CH Thierry Co quand and Gerard Huet The calculus of constructions Information and

Computation FebruaryMarch

Geu Herman Geuvers Type systems for higher order logic

GN Herman Geuvers and MarkJan Nederhof A mo dular pro of of strong normalization

for the calculus of constructions Journal of Functional Programming

April

Hel Leen Helmink Goal directed pro of construction in type theory In Logical Frameworks

Cambridge University Press

HHP Rob ert Harp er Furio Honsell and Gordon Plotkin A framework for dening logics In

Proceedings of the Symposium on Logic in Computer Science pages Ithaca

New York June

HHP Rob ert Harp er Furio Honsell and Gordon Plotkin A framework for dening logics

Journal of the ACM to app ear

HP Rob ert Harp er and Rob ert Pollack Type checking with universes Theoretical Com

puter Science

Hue Gerard Huet The constructive engine March Invited talk at ESOP Not in

pro ceedings

LP Zhaohui Luo and Rob ert Pollack LEGO pro of development system Users manual

Technical Rep ort ECSLFCS LFCS Computer Science Dept University of

Edinburgh The Kings Buildings Edinburgh EH JZ May Up dated version

Luo Zhaohui Luo An Extended Calculus of Constructions PhD thesis Department of

Computer Science University of Edinburgh June

Pfe Frank Pfenning Elf A language for logic denition and veried mataprogramming

In Proceedings of the Fourth Annual Symposium on Logic in Computer Science Asilo

mar California June

vBJ LS van Bentham Jutting Typing in pure type systems Information and Computa

tion To app ear

A Relevant Analysis of Natural Deduction

David Pym and Gordon Plotkin Edinburgh

Abstract

We discuss a rstorder dep endent type theory based on a fragment of intuitionistic

linear logic We discuss the use of this type theory as a framework for the analysis of

natural deduction presentations of weak logics

Fixed p oint and type systems

Christophe Raalli Paris

Abstract

We study an extension of AF type system system F rst order equations This

extension adds two new quantiers on formulas least xp oint inductive types and greatest

xp oint coinductive types We denote them resp ectively by mu and nu

In this system we prove the following results

We have found conditions on types and pro ofs which ensure that all typed terms are

hereditarily solvable their Bohmtree dont contain any b ottom The surprising fact

is that the condition is stronger with least xp oint inductive types than for the

system with only greatest xp oint

The condition for the system with only greatest xp oint is that there is nowhere in

the pro of a subformula nu XF where X is strictly p ositive in F in particular no

nu XX in the pro of Concerning the least xp oint the condition concern all sub

formulas in the pro of and have the same complexity than decision of prop ositional

classical logic

We have also found in this system a representation for inductive and coinductive

data This types are such that each data has a unique normal representation in fact

a unique Bohmtree For instance this allows a construction of the datatype of

streams ensuring unicity of the representation of each stream

We can build a nonstandard representation for natural numbers using the greatest

xp oint with which one can enco de all partial recursive functions

An Overview of the MIZAR Pro ject

Piotr Rudnicki

Department of Computing Science

University of Alb erta

Edmonton Alb erta Canada TG H

email piotrcsualbertaca

June

Abstract

The Mizar pro ject is a longterm eort aimed at developing software to supp ort a work

ing mathematician in preparing pap ers A Trybulec the leader of the pro ject has designed

a language for writing formal mathematics The logical structure of the language is based

on a natural deduction system developed by Jaskowski The texts written in the language

are called Mizar articles and are organized into a data base The TarskiGrothendieck set

theory forms the basis of doing mathematics in Mizar The implemented pro cessor of the

language checks the articles for logical consistency and correctness of references to other

articles

Introduction

The idea that an automatic device should check our logical derivations is by no means new

It can b e traced back not only to Pascal and Leibniz but to Ramon Llull In recent years

several pro jects have aimed at providing computer assistance for doing mathematics Among

the b etter known there are AUTOMATH EKL QUIP Nuprl THEAX

Computational Logic Ontic and the more recent ones such as ALF ELF HOL LEGO

and many others see The sp ecic goals of these pro jects vary However they have

one common feature the human writes mathematical texts and the machine veries their

correctness

The pro ject Mizar started almost years ago under the leadership of Andrzej Trybulec at

the Plock Scientic So ciety Poland Its original goal was to design and implement a software

environment to assist the pro cess of preparing mathematical pap ers For lack of a b etter alter

native the pro ject was based up on the style of doing mathematics used by the mathematicians

of the socalled Polish mathematical school Therefore the pro ject can b e seen as an attempt

to develop software environment for writing traditional mathematical pap ers where classical

logic and set theory form the basis of all future developments

The logical basis of the system is a Polish style of natural deduction Only after years of

using the logic has it b een learned that it was the comp osite system of logic developed by

Stanislaw Jaskowski see and for the English translation Katuzi Ono describ ed a

This work was supp orted in part by NSERC Grant OGP

similar system Various formalizations of set theory have b een tried ZermeloFraenkel Morse

Kelley but nally the TarskiGrothendieck axiomatization has b een adopted

A bit of history

The name Mizar was picked up in for a dierent pro ject a programming environment

that was discontinued but its name has b een recycled

The rst exp eriments in developed a mo dest pro ofchecker for prop ositional logic

The main concern of A Trybulec was the input language to the checker and it turned out to

b e the main concern for all future years The pro of checker was based on a xed set of inference

rules The justication of an inference in the input text required the user to state only the

premises and the conclusion the checker searched for a rule or a sequence of rules to validate

an inference step This approach was abandoned and all future Mizar pro cessors have used

mo del checking

In the language and the checker were extended with quantiers to form Mizar QC

which had neither functional notation nor denitional facilities These were added in subsequent

years to form the Mizar FC system which was used to record a number of larger texts Among

these texts was the initial segment of the b o ok on arithmetics by Grzegorczyk The b o ok is

so rigorous and detailed the Chinese remainder theorem comes as late as page and its pro of

takes pages that the blowup factor in the translation to Mizar FC was negligible

At around the Mizar group started to grow substantially b eing anchored at

Warsaw University Bialystok Branch

In a language called Mizar had b een designed by A Trybulec and implemented

on an ICL by Cz Byli nski H Oryszczyszyn P Rudnicki and A Trybulec The system

was written in Pascal and later p orted to other computers mainframe IBM and also to UNIX

Again the stress was on the input language The pro of checker was rather weak which forced

one to write very detailed pro ofs The language included the following features structured

types type hierarchy comprehensive denitional facilities builtin fragments of arithmetics

and a builtin variant of set theory The translations into Mizar included a number of

recent pap ers in top ology pro jective geometry and some textb o ok algebra In one of the

exp eriments the pigeonhole principle was proven from scratch and compared with the similar

development by van Benthem Jutting in AUTQE the AUTOMATH pro ject The Mizar

text was ab out half as long as the AUTQE text however Mizar and AUTQE were

substantially dierent environments for conducting pro ofs logic based vs type based Among

other works with Mizar there were attempts to prove prop erties of programs and software

sp ecications

In the following years other Mizar languages and their implementations have b een de

veloped but their character was exp erimental Mizar Mizar HPF the systems were not

distributed outside the Mizar group in Bialystok with one exception

1

Mizar Ursae Ma joris is the second magnitude star set in the middle of the Big Dipp ers handle Mizar

Arabic veil cloak burial grounds makes a visual binary with the fainter Alcor Arabic faint one each of the

visual comp onents is a sp ectroscopic binary Mizar is a quadruple star

Incidentally Algol Arabic daemon ghoul Persei is an eclipsing visual binary star sp ectroscopically a

triple probably a quadruple star as well

2

E Post was b orn in Augustow near Bialystok A Lindenbaum was last seen in Bialystok in

3

Address Mizar Group Institute of Mathematics Warsaw UniversityBialystok Branch Bialystok

Poland

A subset of Mizar named Mizar MSE short for MultiSorted with Equality was imple

mented in by R Matuszewski P Rudnicki and A Trybulec and has b een widely used since

then The system is meant for teaching elementary logic with emphasis on the practical asp ects

of constructing pro ofs The Mizar MSE language encompasses raw predicate calculus multi

sorted with equality but the language do es not provide functional notation or sp ecial notation

for denitions There are numerous implementations of Mizar MSE see

In Mizar was implemented as a redesign of Mizar and distributed to several

dozen users Each Mizar article included a preliminaries part where the author could state

some axioms that were not checked for validity

In the design of the language was completed by A Trybulec and the nal language is

named simply Mizar While articles in previous versions of the language must b e selfcontained

the nal Mizar allows for crossreferences among articles Moreover an author of a Mizar text

is not allowed to introduce new axioms Only the predened axioms can b e used everything

else must b e proved The two articles that are not checked for validity contain an axiomatics

of the TarskiGrothendieck set theory see App endix A and denitional axioms of the builtin

concepts and axioms of strong arithmetics of real numbers see App endix B

Recently the main eort in the Mizar pro ject has b een in building the library of Mizar

articles which now numbers almost

The development of Mizar has b een driven by exp erience not only do ctrine ENOD for

short In this case it meant that any idea that made sense was rst of all implemented and

tried by its prop onent However only after other users approved the idea by actually using its

implementation was the idea included into the state of the pro ject The ENOD approach has

b een applied in the development of the Mizar pro cessor the input language although it is

almost exclusively of A Trybulecs creation and the Mizar library

Before giving more information ab out Mizar it may b e worthwhile to recall here the For

mulaire de mathematiques pro ject of Giusepp e Peano quoted from Kennedy p

The end result of this pro ject would b e he hop ed the publication of a collection

of all known theorems in the various branches of mathematics The notions of his

mathematical logic were to b e used and pro ofs of the theorems were to b e given

There were ve editions of the Formulario the rst app eared in and the last

completed in contained some theorems

The pro ject was based on a formal language In the introduction to the second volume of

Formulaire de mathematiques Peano writes quoted from p vol I I

Dans le p etit livre Arithmetices principia nova metho do exp osita a

nous avons p our la premiere fois exp ose toute une theorie theoremes denitions et

demonstrations en symboles qui remplacent toutafait le langage ordinaire

Nous avons donc la solution du probleme prop ose par Leibniz

Anatomy of a Mizar article

Each Mizar article is written as a text le The general structure of such an article is as follows

4

The expression has b een coined by G Kreisel see his contribution in Logic and Computer Science P Odifreddi

ed Academic Press pp

environ

Environment directives

begin

TextProper Section

begin

TextProper Section

The TextProper contains statements of facts with their pro ofs and denitions of new con

cepts with justication of their correctness The Environment directives declare which items of

the Mizar library can b e referenced from the TextProper The directive

vocabulary VocabularyFileName

adds the symbols introduced in the VocabularyFileName to the articles lexicon Vocabulary

les introduce new symbols of Mizar expression constructors The vocabularies also indicate

the binding strength of the introduced symbols for parsing purp oses The authors can use exist

ing vocabularies there are hundreds of symbols there and also are free to create new ones The

lexical makeup of new symbols is governed by a small set of quite lib eral rules The authors

can freely enhance the zo o of mathematical symbols with new symbols of their own design

One vocabulary is automatically attached to every Mizar article It introduces the following

symbols Element Subset DOMAIN Real Nat and the like The information

p ertaining to the usage of these symbols is built into the Mizar pro cessor eg can b e used

as a binary inx predicate symbol with b oth arguments expandable to type set Similarly

requires two arguments of type expandable to Element of Real

Besides vocabularies there are four kinds of data base directives

signature SignatureFileName

definitions DenitionsFileName

theorems TheoremsFileName

schemes SchemesFileName

The directive signature informs the Mizar pro cessor that the article is p ermitted to use

the notation denienda introduced in article SignatureFileName

Any article can dene ways in which the symbols contained in vocabularies can b e used

to form Mizar expressions Each of the Mizar expression constructors functor predicate

mo de can b e syntactically dened in a number of formats These constructors may take various

numbers of arguments of various types and in the case of functors they may return results of

various types This creates a complicated system of overloaded constructors The information

needed for parsing is kept in auxiliary les asso ciated with every article and commonly referred

to as the signature of the article

The remaining three directives allow us to use denitions theorems and schemes that are

dened or proved in another article

The TextProper is a sequence of sections each b eing a sequence of TextItem There are

the the following kinds of items

Reservation is used to reserve identiers for a type If a variable has an identier reserved

for a type and no explicit type is stated for the variable then the variable type defaults

to the type for which its identier was reserved

DenitionBlock is used to dene or redene constructors of Mizar phrases term con

structors functions formula constructors predicates and type constructors mo des

StructureDenition introduces new structures A structure is an entity that consists of

a number of elds that are accessed by selectors

Theorem announces a prop osition that can b e referenced from other articles

Scheme also announces a prop osition visible from outside Second order terms can o ccur

in scheme

AuxiliaryItem introduces ob jects that are lo cal to the article in which they o ccur and are

not exp orted to the library les eg lemmas denitions of lo cal predicates

The goal of writing an article is to prove some theorems and schemes or to dene some new

concepts such that they can b e referenced by other authors Before the theorems and denitions

are included into the library they must b e proved valid and correct

The PC Mizar

PC Mizar is a Mizar pro cessor implemented on IBM PCs under DOS by Cz Byli nski A

Trybulec and S Zukowski and now further developed by the rst two authors

The central concept of Mizar is a Mizar article Such an article can b e viewed as an

extremely detailed mathematical text written in a xed formal notation originally as a text

le There are rather few interesting things that one can prove in a short Mizar article without

making references to other articles Usually we base our work on the achievements of others

The p ower of the Mizar system is in its automatic pro cessing of crossreferences among

articles contained in the Mizar library In order to sp eed up the pro cess of cross reference

checking some internal les derived from the submitted articles are maintained These les

they are not meant to b e read by humans are created in the pro cess of including an article

into the Mizar library

signature les that for each newly dened constructor of Mizar phrases in the article give

information necessary for parsing the constructor o ccurrences

denitions le stores the deniens of every denition in the article the deniendum is

stored in the signature le

theorems le stores the theorems proved in the article without pro ofs

schemes le stores the schemes proved in the article without pro ofs

The Mizar software is a collection of ab out programs that pro cess Mizar articles

The verier must run in the appropriate environment with access to all the vocabulary

and library les referenced in the given article For eciency reasons each checked article

obtains a dedicated environment by a program called accommodator in order to avoid

to o many references to dierent library les

Parsing of Mizar texts is relatively complicated mainly b ecause of the rich Mizar syntax

multiway overloading of names and new denitions or redenitions of Mizar phrase

constructors and their priorities

Checking whether pro ofs are correctly structured requires some pro cessing as Mizar

p ermits a multitude of pro of structures in the spirit of natural deduction prop osed by

Jaskowski

An inference of the form

premise premise premise conclusion

k

is transformed into the conjunction

premise premise premise not conclusion

k

If the checker nds the conjunction contradictory then the original inference is accepted

Unfortunately but inevitably the checker sometimes do es not accept an inference that

is logically correct to get the inference accepted one has to split it into a sequence of

smaller ones or p ossibly use a pro of structure The stress in the inference checker is on

the pro cessing sp eed not p ower

The Input Language

Exp erience has shown that p eople with even minimal mathematical training develop a go o d

idea ab out the nature of the Mizar language just by browsing through a sample article This

is not a big surprise as one of the original goals of the pro ject was to build an environment that

mimics the traditional ways that mathematicians work A sample Mizar article is presented

in App endix C

Because of the richness of the Mizar grammar even a sketchy presentation of it is far

b eyond the scop e of this text

Mizar abstracts

The source texts of Mizar articles tend to b e lengthy as they contain complete pro ofs in a rather

demanding formalism New articles strongly dep end on already existing ones Therefore there

was a need to provide authors with a quick reference to the already collected articles The

solution was to automatically create an abstract for each Mizar article Such an abstract

includes a presentation of all the items that can b e referenced from other articles The abstract

of the article presented in App endix C is contained in App endix D Therefore there is no need

to examine the entire article to make a reference to a single theorem

To make the abstracts resemble a mathematical pap er at least at the lexical level they

are automatically typeset using T X The T Xed Mizar abstract from App endix D is in Ap

E E

p endix E

The typeset Mizar abstracts are p erio dically published by Universite Catholique de Lou

vain as Formalized Mathematics a computer assisted approach with R Matuszewski as editor

5

For more information write to Fondation Philipp e le Ho dey Mizar Users Group Av F Ro osevelt

Bte Brussels Belgium fax

Main Mizar Library

At the b eginning of the Mizar group in Bialystok started collecting Mizar articles and

organizing them into a library that is distributed to other Mizar users

The p erson resp onsible for the library E Woronowicz requires that authors of contributed

articles supply an additional le that describ es the bibliographic data such as title authors

names and aliations and a summary in English The bibliographic information is included

at the b eginning of each typeset abstract

As of June the library consisted of Mizar articles authored by some p eople

theorem les that are referenced from other articles contained theorems there were

crossreferences among articles Totally there were ab out MB of source text les with

articles Although the ma jority of articles have b een authored by p eople from Bialystok many

pap ers have b een written by mathematicians from other universities in Poland and there are

articles written by foreign authors Canada Japan Spain USA

The nature of the articles varies Most of them are Mizar translations of basic mathematics

Few of them contain new results To get an idea ab out the contents of the library lo ok at

Table for a sample of article titles

No Name Inclusion date Title Authors

BOOLE I Boolean Properties of Sets Z Trybulec and

H Swie czkowska

FUNCT IV Functions from a Set to Cz Byli nski

a Set

WELLORD IV Zermelo Theorem and G Bancerek

Axiom of Choice

FRAENKEL I I Function Domains and A Trybulec

Fraenkel Operator

TRANSLAC VI Translations in Ane H Oryszczyszyn and

Planes K Pra zmowski

MEASURE X The additive Measure J Bialas

Theory

ALI VI I Fix Point Theorem for A de la Cruz

Compact Spaces

HEINE XI HeineBorels Covering A Darmo chwal and

Theorem Y Nakamura

MIDSP V Reper Algebras M Muzalewski

Table Sample of titles from Mizar library

The development of the Mizar library may b e p erceived as an exp eriment in the so ciology of

mathematics The acceptance criteria are very lib eral every submitted pap er that is accepted

by the Mizar pro cessor is included into the library There are some eorts towards having

automated reviewers that lo oks for example for rep eated theorems or trivial ones There is

a collection of programs called enhancers and improvers that try to automatically meliorate the

submitted articles The melioration makes changes in the submitted articles that is replaces

a pro of by a one step inference referencing a number of prop ositions or replaces a sequence

of inferences by a single one or removes references to the sup eruous premises in an inference

step

As the Mizar system evolves and this includes the input language there is a need to rewrite

pieces of the library articles to mirror the changes To a large extent this is done automatically

Sometimes however a manual intervention is required

The p eople maintaining the library collect statistics ab out the references across articles

Consideration is given to whether or not the frequently quoted theorems or denition should

b e built into the Mizar verier This was the fate of prop osition TARSKI which stated that

everything was a set see App endix A

Table contains the list of the most frequently quoted theorems

No of of all Name Statement of the theorem

ref ref

BOOLE x X X Y implies x Y

BOOLE x XY i x X x Y

TARSKI X fyg i for x holds x X i x y

BOOLE x XY i x X or x Y

BOOLEdef Z i not ex x st x Z

BOOLE X Y Y Z implies X Z

FINSEQ k len p i Seg k dom p

BOOLE XYZ XYZ

BOOLE X Y i for x holds x X implies x Y

AXIOMS X is Subset of Y i X Y

Table Top theorems of Mizar library

The future

The Mizar language The logical level of the language has long b een xed It is the type

hierarchy that fuels all the changes Recently the development has fo cused on introducing a

mechanism for deriving Mizar structures in the spirit of the ob jectoriented approach and on

deriving new Mizar mo des by adding attributes to existing ones Both prop osed derivation

techniques result in Bo olean algebras of structures and sets of attributes resp ectively According

to A Trybulec b oth these changes will have a dramatic impact on the style of doing mathematics

in Mizar

The language still lacks some p olymorphic or generic facilities such that one has to prove

analogous facts twice for example ab out lower and upp er semilattices

Translations It is planned to implement the mechanical translation of Mizar texts into other

existing systems for doing mathematics and vice versa However H Barendregts optimism on

the time frame required for such a work is not commonly shared

Large data base A large data base would require a ma jor eort from numerous parties and

the administrative problems of such an enterprise should not b e neglected It is estimated that

maintenance of a data base times bigger than the current state ie with ab out articles

by several hundred authors could stabilize a number of issues whose current solutions tend to

b e unstable

Presentation The usefulness of Formalized Mathematics containing typeset abstracts insti

gated some thoughts on typesetting entire Mizar articles Similarly a need arises to develop

some automated techniques for extracting topical monographs from the Mizar library

Accommo dator The pro cess of preparing a lo cal environment for checking a single article

awaits a b etter solution The problem here is similar to linking a newly written program with

library mo dules known to b e a challenge in software engineering An accommo dator is exp ected

to sp eed up the pro cess of checking articles by cutting o the complex data base interaction at

a certain level

Neglected issues There are some asp ects of the Mizar system that draw immediate crit

icism To name a few restriction to IBM PC and compatibles p o or user interface restricted

to the text editor level only textual searches of the data base weak inference checker All of

them have b een recognized as problems to work on but were p erceived as second priority issues

Eventually they have to b e addressed

Hib ernation Freezing the changes in the input language and in the Mizar pro cessor has

b een a goal for quite a while yet it seems to move away like the horizon when you try to

approach it

How to learn Mizar

The Mizar language its pro cessor and the organization of the Mizar library evolve and

therefore there is not much in the way of written do cumentation see

In the face of do cumentation shortages the b est way to learn Mizar is to sp end approxi

mately four weeks in Bialstok and coauthor a Mizar article with a native user of the system

However numerous cases are known of Mizar users who that advanced their knowledge of the

system by studying the existing texts and there are MB of these

Acknowledgements

I am indebted to all members of the Mizar development group which I was a member of

years ago and to all the authors of articles in Mizar Library Sp ecial thanks are to Andrzej

Trybulec Roman Matuszewski Czeslaw Byli nski Edmund Woronowicz Grzegorz Bancerek

and Zbigniew Karno

This commercial has b een written with the hop e that their work meets with the recognition

it deserves

6

Other places include Lodz and Rzeszow in Poland Madrid in Spain and Nagano in Japan

References

Ewa Bonarska An Introduction to PC Mizar Mizar Users Group Fondation Philipp e le

Ho dey Brussels

R S Boyer and J S Mo ore A Computational Logic Handbook Academic Press

RL Constable et al Implementing Mathematics with the Nuprl Proof Development System

PrenticeHall

N G de Bruijn A survey of the pro ject AUTOMATH In J P Seldin and Hindley J R

editors Essays in Combinatory Logic Lambda Calculus and Formalism pages

Academic Press

Andrzej Grzegorczyk Zarys arytmetyki teoretycznej PWN Warszawa

G Huet and G Plotkin editors Proceedings of the st Workshop on Logical Frameworks

ESPRIT BRA Anonymous ftp nuriinriafr

G Huet and G Plotkin editors Proceedings of the nd Workshop on Logical Frameworks

ESPRIT BRA Anonymous ftp colonsaydcsedacuk

S Jaskowski On the rules of supp osition in formal logic Studia Logica

H C Kennedy editor Selected works of Giuseppe Peano University of Toronto Press

J Ketonen EKLa mathematically oriented pro of checker In Proceedings of th Int

Conf on Automated Deduction pages Napa CA May

D A McAllester Ontic The MIT Press

S McCall editor Polish Logic in Clarendon Press Oxford

M Mostowski and Z Trybulec A certain exp erimental computer aided course of logic in

Poland In Proceedings of World Conference on Computers in Education Norfolk VA

Y Nakamura A language for description of mathematicsTHEAX Technical rep ort

Shinshu University FIE Nagano City Japan In Japanese

S Nieva Soto The Reasoner of MIZARLOG Computerized Logic Teaching Bul letin

March

K Ono On a practical way of describing formal deductions Nagoya Mathematical Journal

Giusepp e Peano Opere Scelte Edizioni Cremonese Roma

K Pra zmowski P Rudnicki et al MizarMSE Primer and User Guide TR The

University of Alb erta Department of Computing Science Edmonton

P Rudnicki Obvious inferences Journal of Automated reasoning

P Rudnicki What should b e proved and tested symbolically in formal sp ecications In

th IEEE International Workshop on Software Specication and Design pages

Monterey Ca

P Rudnicki and W Drab ent Proving prop erties of Pascal programs in MIZAR Acta

Informatica Erratum pp

RL Smith et al Computerassisted axiomatic mathematics Informal rigor In O Lecarme

and R Lewis editors Computers in Education pages North Holland

Alfred Tarski Ub er unerreichbare Kardinalzahlen Fundamenta Mathematicae

Alfred Tarski On wellordered subsets of any set Fundamenta Mathematicae

A Trybulec and H Blair Computer aided reasoning In R Parikh editor Logic of

Programs LNCS Springer Verlag

A Trybulec and H Blair Computer assisted reasoning with Mizar In Proceedings of the

th IJCAI pages Los Angeles Ca

Andrzej Trybulec Tarski Grothendieck Set Theory Formalized Mathematics

L S van Benthem Jutting The development of a text in AUTQE In Proceedings

of APLASM Symposium dOrsay sur la Manipulation des Symboles at dUtilisation

dAPL Universite Paris XI

A Tarski Grothendieck Set Theory

The following is the abstract and the actual article on which the Mizar library is built For

obvious reasons the article has not b een checked for validity Unfortunately for the international

audience the comments in text are mainly in Polish First the English summary provided by

A Trybulec author

This is the rst part of the axiomatics of the Mizar system It includes the axioms

of the Tarski Grothendieck set theory They are the axiom stating that everything

is a set the extensionality axiom the denitional axiom of the singleton the def

initional axiom of the pair the denitional axiom of the union of a family of sets

the denitional axiom of the b o olean the p ower set of a set the regularity axiom

the denitional axiom of the ordered pair the Tarskis axiom A introduced in

see also and the Frnkel scheme Also the denition of is

introduced

REL BOOLE FAM OP environ vocabulary EQUI

Andrzej Trybulec

Teoria mnogosci Tarskiego Grothendiecka

begin

reserve xyzu for Any

NM XYZ for set

axiom Tarski wszystko jest zbiorem

canceled as obvious x is set

axiom Tarski ekstensjonalnosc zbiorow

for x holds x X iff x Y implies X Y

Singletony i pary

definition

let y func f y g set means

TARSKI def

x it iff x y

let z func f y z g set means

TARSKI def

x it iff x y or x z

end

axiom Tarski definicja singletonu

X f y g iff for x holds x X iff x y

axiom Tarski definicja pary nieuporzadkowanej

X f yz g iff for x holds x X iff x y or x z

definition let XY

pred X c Y means

TARSKI def

x X implies x Y

reflexivity

end

definition let X

func union X set means

TARSKI def

x it iff ex Y st x Y Y X

end

axiom Tarski definicja unii rodziny zbiorow

X union Y iff for x holds x X iff ex Z st x Z Z Y

axiom Tarski definicja zbioru potegowego

X bool Y iff for Z holds Z X iff Z c Y

axiom Tarski aksjomat regularnosci

x X implies ex Y st Y X not ex x st x X x Y

scheme Fraenkel f A set PAny Any g

ex X st for x holds x X iff ex y st y A Pyx

provided for xyz st Pxy Pxz holds y z

definition let xy

func xy means

TARSKI def

it f f xy g f x g g

end

axiom Tarski definicja pary uporzadkowanej

xy f f xy g f x g g

definition let XY

pred X Y means

TARSKI def

ex Z st

for x st x X ex y st y Y xy Z

for y st y Y ex x st x X xy Z

for xyzu st xy Z zu Z holds x z iff y u

end

Alfred Tarski

Ueber unerreichbare Kardinalzahlen

Fundamenta Mathematicae vol pp

Axiom A Axiom der unerreichbaren Mengen Zu jeder Menge N gibt es

eine Menge M mit folgenden Eigenschaften

A N M

A ist X M und Y c X so ist Y M

A ist X M und ist Z die Menge die alle Mengen Y c X und keine

andere Dinge als Element enthaelt soist z M

A ist X c M und sind dabei die Menge X und M nicht gleichmaechtig

so ist X M

takze

Alfred Tarski

On Wellordered Subsets of any Set

Fundamenta Mathematicae vol pp

A For every set N there exists a system M of sets which satisfies

the following conditions

i N M

ii if X M and Y c X then Y M

iii if X M and Z is the system of all subsets of X then Z M

iv if X c M and X and M do not have the same potency then X M

axiom Tarski

ex M st N M

for XY holds X M Y c X implies Y M

for X holds X M implies bool X M

for X holds X c M implies X M or X M

B Builtin Concepts

The English summary provided by A Trybulec author

This abstract contains the second part of the axiomatics of the Mizar system the

rst part is in abstract The axioms listed here characterize the Mizar builtin

concepts that are automatically attached to every Mizar article We give denitional

axioms of the following concepts element subset Cartesian pro duct domain non

empty subset sub domain non emptysubset of a domain set domain domain

consisting of sets Axioms of strong arithmetics of real numbers are also included

Numerous axioms that were needed some time ago have b een cancelled they have b een built

into the pro cessor and they are now obvious to the verier The trace of them is required to

prop erly pro cess older articles that made references to the axioms

Polish comments have b een deleted from the text

Andrzej Trybulec

environ

vocabulary Boole signature Tarski

begin

reserve xyz for Any

XXXXXY for set

axiom AXIOMS ex x st x X implies x is Element of X iff x X

canceled as obvious

axiom AXIOMS

X is Subset of Y iff X c Y

axiom AXIOMS

z XY iff ex xy st x X y Y z xy

axiom AXIOMS

X is nonempty implies ex x st x X

axiom AXIOMS

XXX XXX

axiom AXIOMS

XXXX XXXX

reserve DDDD for nonempty set

axiom AXIOMS for X being Element of DD holds X is TUPLE of D D

canceled as obvious

axiom AXIOMS for X being Element of DDD holds X is TUPLE of D D D

canceled as obvious

axiom AXIOMS for X being Element of DDDD holds X is TUPLE of D D D D

canceled as obvious

reserve D for nonempty set

axiom AXIOMS

D is nonempty Subset of D iff D c D

axiom AXIOMS D is SET DOMAIN

canceled as obvious

reserve xyz for Element of REAL

axiom AXIOMS

x y y x

axiom AXIOMS

x y z x y z

axiom AXIOMS

x x

axiom AXIOMS

x y y x

axiom AXIOMS

x y z x y z

axiom AXIOMS

x x

axiom AXIOMS

x y z x y x z

axiom AXIOMS

ex y st x y

axiom AXIOMS

x implies ex y st x y

axiom AXIOMS

x y y x implies x y

axiom AXIOMS

x y y z implies x z

axiom AXIOMS

x y or y x

axiom AXIOMS

x y implies x z y z

axiom AXIOMS

x y z implies x z y z

axiom AXIOMS

for XY being Subset of REAL st

ex x st x X ex x st x Y

for xy st x X y Y holds x y

ex z st

for xy st x X y Y holds x z z y

axiom AXIOMS x is Real

canceled as obvious

axiom AXIOMS

x NAT implies x NAT

axiom AXIOMS

for A being set of Real

st A for x st x A holds x A holds NAT c A

reserve ijk for Nat

axiom AXIOMS

k f i ik g

C A Mizar article

The following is the text of an article from the Main Mizar Library This article is unusualit is

shortest in the library In order to decrease the number of text lines and with hop e of improving

readability I have manipulated the white space of the original submission The characters of

a

extended ASCI I have b een replaced by some symbols available in L T X The Mizar pro cessor

E

restricts the length of input lines to characters The text b elow violates this restriction for

presentation purp oses

Alicia de la Cruz

Fix Point Theorem for Compact Spaces

environ

OP REAL vocabulary METRYKA SFAMILY POWER FINITE SEQ SEQ SEQM SUB

TOPCON PCOMPS FUNC TOP FAM OP BOOLE FINITER ALI FUNC REL

signature FINSET METRIC FUNCT FUNCT PRE TOPC POWER BOOLE FUNCOP

TARSKI COMPTS PCOMPS SETFAM TOPS TOPS SEQ SEQ SEQM

REAL NAT SUBSET

definitions COMPTS TARSKI TOPS FUNCT

theorems METRIC SUBSET REAL PCOMPS REAL COMPTS POWER BOOLE SEQ

SEQ SERIES SEQM AXIOMS SETFAM TARSKI SEQ PRE TOPC TOPS

DOMAIN FUNCOP ZFMISC SQUARE

schemes SETFAM SEQ GROUP FINSET NAT

begin

reserve M for MetrSpace x y for Element of the carrier of M

theorem VIT

for F being set st F is finite F

for B C being set st B F C F holds B c C or C c B

ex m being set st m F for C being set st C F holds m c C

proof pred Pset means

implies ex m being set st m for C being set st C holds m c C

let F be set such that

Z F is finite and Y F and

X for B C being set st B F C F holds B c C or C c B

A P

B now let x B be set such that j x F B c F PB

now per cases we have to prove PB Ufxg

case j not ex y being set st y B y cx

assume B U fxg take m x x fxg by TARSKIdef

hence m B U fxg by BOOLE let C be set assume C B U fxg then

CB or Cfxg by BOOLE then jCB or Cx by TARSKIdef

j not C cx or Cx by j TARSKIdef C F by j BOOLE j

hence m c C by j X j

case ex y being set st y B y cx then consider y being set such that

j y B y cx assume B U fxg consider m being set such that

jm B and

j for C being set st C B holds m c C by j j BOOLEdef

m c y by j j then jm c x by j BOOLE

take m thus m B U fxg by j BOOLE

let C be set assume C B U fxg then C B or C fxg by BOOLE

hence m c C by j j TARSKIdef end

hence PB U fxg end

PF from FiniteZ A B

hence thesis by Y end

definition let M be MetrSpace

mode contraction of M Function of the carrier of M the carrier of M

means DD ex L being Real st L L

for x y being Point of M holds distitx ityLdistx y

existence proof consider x being Point of M

the carrier of M x is Function of the carrier of M the carrier of M proof

thus dom the carrier of M x the carrier of M by FUNCOP

ccrng the carrier of M x c fxg by FUNCOP

fxg c the carrier of M by ZFMISC

hence rng the carrier of M x c the carrier of M by BOOLE cc end

then reconsider f the carrier of M x

as Function of the carrier of M the carrier of M

take f hence aa by SEQ SQUARE

let z y being Point of M fzx fyx by FUNCOP

def distz y by METRIC then bb distfz fy by METRIC

hence distfz fydistz y by bb aa REAL end

end

compact theorem for f being contraction of M st TopSpaceMetrM is

ex c being Point of M st fc c exists a fix point

for x being Point of M st fxx holds xc exactly fix point

proof

let f be contraction of M consider L being Real such that

a L L and

a for x y being Point of M holds distfx fyLdistx y by DD

assume a TopSpaceMetrM is compact consider x being Point of M set adistx fx

now assume a

consider F being SubsetFamily of the carrier of TopSpaceMetrM such that

kkk for B being Subset of the carrier of TopSpaceMetrM holds BF iff

power n g ex n being Nat st B f x where x is Point of M distx fx aL to

from SubFamEx

TopSpaceMetrM TopStructthe carrier of M Family open setM by PCOMPS def then

d the carrier of M the carrier of TopSpaceMetrM

power g set B f x where x is Point of M distx fx aL to

B is Subset of the carrier of M from SubsetD then B F by kkk d then

d F by BOOLEdef

a F is centered proof thus F by d

let G be SubsetFamily of the carrier of TopSpaceMetrM such that

finite b G and b G c F and b G is

for B C being set st B G C G holds B c C or C c B proof

let B C be set assume hB G C G then h B F C F by b BOOLE

B is Subset of the carrier of TopSpaceMetrM by SETFAM h

then consider n being Nat such that

h B f x where x is Point of M distx fx aL to power n g by kkk h

h C is Subset of the carrier of TopSpaceMetrM by SETFAM

then consider m being Nat such that

h C f x where x is Point of M distx fx aL to power m g by kkk h

lemma for n m being Nat st nm holds L to power m L to power n proof

let n m being Nat such that iii nm

def now per cases by iii REAL

case nm then L to power n L to power m by POWER a

hence L to power n L to power m by REAL def

power n L to power m end case nm hence L to

hence thesis end

lemma for n m being Nat st nm holds aL to power m aL to power n proof

let n m being Nat such that iii nm

now per cases

case c a then aL to power m by REAL aL to power n by REAL c

hence aL to power m aL to power n

case a cc a by METRIC L to power m L to power n by iii lemma

power m aL to power n by cc REAL end hence aL to

hence thesis end

now per cases by AXIOMS

case inm thus C c B proof let y be Any assume y C

then consider x being Point of M such that

C y x and C distx fx aL to power m by h

aL to power m aL to power n by i lemma then

distx fx aL to power n by AXIOMS C

hence y B by C h end

case iimn thus B c C proof let y be Any assume y B

then consider x being Point of M such that

C y x and C distx fx aL to power n by h

power n aL to power m by ii lemma then aL to

distx fx aL to power m by AXIOMS C

hence y C by C h end end

hence B c C or C c B end then consider m being set such that

n m G and n for C being set st C G holds m c C by VIT b b

n m c meet G by SETFAM b n n m F by n BOOLE b

h m is Subset of the carrier of TopSpaceMetrM by SETFAM n

CC L by a distxfx a by REAL aL to power by POWER CC

power g then then x f x where x is Point of M distx fx aL to

P f x where x is Point of M distxfx aL to power g by BOOLEdef

P for k being Nat st fx where x is Point of M distx fx aL to power kg

holds fx where x is Point of M distxfx aL to power kg

power kg proof let k be Nat assume fx where x is Point of M distxfx aL to

then consider z being Any such that

s zf x where x is Point of M distx fx aL to power k g by BOOLEdef

power k by s consider y being Point of M such that yz and s distyfy aL to

L by a REAL def then s Ldistyfy LaL to power k by REAL s

s LaL to power k LaL to power k by AXIOMS aLL to power k by AXIOMS

power k by AXIOMS aL to power L to power k by POWER aLL to

aL to power kL to power by AXIOMS aL to power k by POWER a

distfy ffy Ldisty fy by a then

distfy ffy aL to power k by s s AXIOMS then

fy f x where x is Point of M distx fx aL to power k g

power k g by BOOLEdef hence f x where x is Point of M distxfxaL to

end

for k being Nat holds f x where x is Point of M distxfx aL to power kg

from IndP P then m by h kkk n

hence meet G by BOOLE n end

F is closed proof let B being Subset of the carrier of TopSpaceMetrM

assume B F then consider n being Nat such that

power n g by kkk mm B f x where x is Point of M distx fx aL to

A TopSpaceMetrMTopStructthe carrier of M Family open setM by PCOMPS def

then reconsider V B as Subset of the carrier of M set B B

for x being Point of M st x V ex r being Real st r Ballx r c V proof

power n let x be Point of M such that m x V take r distx fxaL to

then r distx fxaL to power n by REAL then

m distxfxr aL to power n by REAL not xB by m SUBSET then

distxfxaL to power n by mm then distxfxaL to power n by REAL

hence r by SEQ

let z be Any assume m z Ballx r Ballx r c the carrier of M by AXIOMS

then reconsider yz as Point of M by BOOLE m m distx yr by METRIC m

distx y disty fy distx fy by METRIC then

m distxydistyfydist fyf x distxfydistfyfx by REAL

distx fy distfy fx distx fx by METRIC then

distx ydisty fydistfy fxdistx fx by m AXIOMS then

disty fydistx ydistfy fxdistx fx by AXIOMS then

m disty fydistx ydistfy fxdistx fx by AXIOMS

m distx y disty x by METRIC m distfy fxLdisty x by a

disty x by METRIC then Ldisty xdisty x by REAL a

then distfy fxdisty x by m AXIOMS then

m distfy fxdisty x disty xdisty x by REAL

then distx yr by m REAL then

m disty fy distx y disty fy r by REAL

distfy fxdisty x disty x by m SQUARE then

disty x distfy fx disty x by AXIOMS then

distyfydistyxdistf yf xdi sty fy d ist yx by REAL

then disty fydistx ydistx fx by m AXIOMS m

then disty fyrdistx fx by REAL m then

power n by m REAL not ex x being Point of M st yx distxfxaL to

then m not y B by mm the carrier of M by DOMAIN

hence z V by SUBSET m A end then

B Family open setM by PCOMPS def then B is open by A PRE TOPCdef

closed by TOPS hence B is

end then

meet F by COMPTS aa then consider c being Point of TopSpaceMetrM such that

d cmeet F by SUBSET

Sequence such that reconsider c c as Point of M by d consider s being Real

b for n being Nat holds snL to power n from ExRealSeq set s a 2 s

b s is convergent lim s by a SERIES b then

b s is convergent by SEQ

by REAL b lim s a by b SEQ

consider r being Real Sequence such that

b for n being Nat holds rndistc fc from ExRealSeq

constant by SEQM def b then b r is convergent by SEQ b r is

now let n be Nat set B f x where x is Point of M distx fx aL to power ng

B is Subset of the carrier of M from SubsetD then B F by kkk d then

d then c B by d SETFAM

d ex x being Point of M st c x distx fx aL to power n

d rn distc fc by b sn asn by SEQ def aL to power n by b

hence rn sn by d d end then

c lim r lim s by SEQ b b rdistc fc by b then

SEQ b then distc fc distc fc by c b METRIC

distc fc by AXIOMS

hence ex c being Point of M st distc fc

end then consider c being Point of M such that

XX distc fc

take c

thus a fc c by METRIC def XX

def let x be Point of M assume a fxx assume xc then a distxc by METRIC

distx c by METRIC then distx c by REAL def a then

Ldistx cdistx c by a REAL

hence contradiction by a a a

end

D A Mizar abstract

Here is the abstract of the article presented in App endix C The abstracts are extracted me

chanically from the submitted articles and the reference identication of Mizar items is au

tomatically inserted If one wants to make a reference to another article they have to use

reference names as presented in the articles abstract

Alicia de la Cruz

Fix Point Theorem for Compact Spaces

environ

OPREAL TOPCON vocabulary METRYKASFAMILYPOWERFINITE SEQ SEQ SEQ MSUB

PCOMPSFUNCTOPFAM OPBOOLEFINITERALIFUNC REL

signature FINSET METRIC FUNCT FUNCT PRE TOPCPOWERBOOLEFUNCOP

PCOMPS SETFAM TOPS TOPS SEQ SEQ SEQM TARSKICOMPTS

SUBSET REAL NAT

begin

reserve M for MetrSpacexy for Element of the carrier of M

theorem ALI

for F being set st F is finite F

for BC being set st B F C F holds B c C or C c B

ex m being set st m F for C being set st C F holds m c C

definition let M be MetrSpace

mode contraction of M Function of the carrier of M the carrier of M

means ALIdef

ex L being Real st L L for xy being Point of M holds

distitxityLdistxy

end

theorem ALI

compact for f being contraction of M st TopSpaceMetrM is

ex c being Point of M st fc c exists a fix point

for x being Point of M st fxx holds xc

E A T Xed Mizar abstract

E

Mizar abstracts are further mechanically pro cessed typeset using T X and published see

E

fo otnote on page Each author of an article accepted to the library must provide a title

the authors name and address and a summary in English that are included into the typeset

abstract

The next two pages contain a copy of the typeset version of the abstract from App endix D

One can consider the English of the text rather p o or but it should b e remembered that this

text has b een generated mechanically The pro cess of mechanical translation from Mizar into

English is still b eing worked on

Kripke Semantics for a Logical Framework

Alex K Simpson

alsdcsedacuk

Department of Computer Science University of Edinburgh

JCMB The Kings Buildings Edinburgh EH JZ

July

Abstract

We present a semantic analysis using Kripke lambda mo dels of a metalogic minimal

implicational predicate logic with quantication over all higher types with emphasis on its

use as a logical framework An ob jectlogic is enco ded by a metatheory axiomatising its

consequence relation Prop erties of the enco ding such as adequacy are analysed in terms

of corresp onding semantic prop erties In the case of adequacy we are able to prove the

interesting faithfulness direction by showing that the metatheory has a certain kind of

mo del The semantics is also used to analyse conditions under which the admissibility of an

inference rule is provable in the metalogic

Introduction

The aim of this pap er is to give a semantic analysis of the use of a metalogic as a logical

framework

The metalogic we consider is a fragment of intuitionistic predicate logic with quantication

over all higher types The idea of using such a logic as a framework go es back to the Edinburgh

Logical Framework LF although this was itself partly inspired by de Bruijns AUTOMATH

and MartinLofs system of arities Although LF is a dep endentlytyped lambda

calculus it can b e viewed as a fragment of intuitionistic logic using the prop ositions as types

corresp ondence Intuitively however it is quite natural to separate types from prop ositions

For example the LF type we follow the notation of

o otrue true

can b e read naturally as the prop osition

o o true true

One is thus replacing the judgements as types principle of with some kind of meta

axiomatisation This separation b etween prop ositions and types has b een made explicit in

the applications of Isab elle and Prolog as logical frameworks see

There are a number of advantages to the LF approach One merit is the obvious simplicity of

having a calculus with only one connective dep endent pro duct Another is that the judgements

Supp orted by SERC grant no

as types principle enables pro ofs to b e explicitly represented as terms of the framework With

this understanding the type is the natural type for the introduction rule which given two

formulae and together with a pro of of constructs a pro of of Finally the idea of

separating prop ositions and types though natural in some cases might b e less so in general

The single ontology of LF allows for the maximum exibility in making enco dings

Nevertheless there are also go o d reasons for separating prop ositions and types One is

that a framework should distinguish b etween syntax and logical consequence Syntax will still

b e represented by terms of appropriate type but now consequence is expressed by a meta

axiomatisation However these kind of separations can also b e made to go o d eect in a wholly

typetheoretical setting see A second argument is to prefer the metalogical approach

on the grounds that the main b enet oered by the typetheoretic approach explicit pro of

representation is neither imp ortant nor desirable Pro of representation is unimp ortant if one

takes the p oint of view that the feature of a logic of real interest is its consequence relation see

section An argument for the undesirability of pro of representation based on eciency is

given in A further argument against the kind of pro of representation oered by LF is that

it is to o crude to capture many interesting pro of systems two sided sequent calculi for example

In fact the numerous examples in testify to LF as b eing go o d for representing consequence

in the general case but go o d for representing pro ofs only in particularly wellbehaved cases

However the main reason we are interested in distinguishing prop ositions and types is that

we wish to consider a logical framework as a metalogic We want to understand the enco ding

of the logic as a commitment to certain metaprop ositions ab out the logic the prop osition

for example In order to understand these metaprop ositions mathematically we require a

semantics for the metalogic Moreover we want to relate the metaprop ositions to the enco ded

logic So the semantics should b e able to provide links b etween the enco ded logic and its meta

theory These links will turn out to b e very concrete For example in section we build a

mo del of a metatheory out of mo dels of the logic it enco des

The structure of this pap er is as follows In section we introduce the metalogic In

section we give it a Kripke semantics proving soundness and completeness Section is then

a necessary preliminary to the rest of the pap er In it we survey various elementary prop erties

of consequence relations The bulk of the pap er is contained sections and In the former we

consider how the metalogic can b e used to enco de logics The prop erty we are most interested in

is the adequacy of an enco ding This is given a semantic characterisation which is then used

to give an example pro of of adequacy Finally in section we consider a notion of admissible

rule for a logic The semantics is used to analyse under what conditions the admissibility of a

rule is provable in the metatheory representing a logic

Throughout this pap er we consider many dierent sequentstyle judgements with sets for

the antecedent In these we adopt the standard notational conventions of writing for

omitting set delimiters from singleton sets and omitting explicit mention of the empty set

The metalogic

The metalogic is minimal implicational predicate logic with universal quantication over all

higher types It is quite similar to the logics considered in

We use A B and C to range over simple types M and N to range over terms of the

simplytyped calculus and and to range over formulae lower case Greek letters will b e

reserved for formulae of the ob jectlogic

We assume given four countably innite disjoint sets a set of type constants a set of

predicate symbols a set of term constants and a set of variables We use P to range over the

predicate symbols c to range over the term constants and x to range over the variables

A theory is generated by a presentation which is a quadruple T P A where each of

T P and A are sets as sp ecied b elow Mostly but not exclusively we consider nite

presentations ie those in which all four sets are nite

T is a subset of the set of type constants Types are generated from this set by the grammar

A j A B

where ranges over elements of T As usual when brackets are omitted asso ciates to

the right P is a set of predicate declarations of the form P hA A i where n is p ossibly

n

zero such that each predicate symbol P app ears only once in the set is a set of constant

declarations of the form c A such that each term constant c app ears only once in the set The

requirements on A are given b elow Henceforth everything will b e parameterised over T and P

and these sets will usually b e left implicit Thus we often refer to the presentation as A

A context is a nite set of variable declarations of the form x A such that each variable

x app ears only once in the set The abstract syntax of terms and formulae is given by the

following grammar

M c j x j x A M j M N

P M M j j x A

n

We assume that the reader understands the notion of free and b ound variable We write N M x

and M x for the substitution of M for all free o ccurrences of x in N and resp ectively

Lambdaterms and quantied formulae are considered identied up to equivalence

The term calculus is just the simplytyped lambda calculus for which a go o d reference is

We write  M A to mean that M is term over with type A in context We

shall only b e concerned with equality b etween terms We note but shall not use that

equality b etween terms is decidable A term M such that  M A is said to b e in long

normal form with resp ect to and if it has the form

x A x A hM M

n n m

where n m h is either a variable or a constant x A x A  hM M

n n m

for some type constant and each M i m is in long normal form with resp ect to

i

x A x A and Clearly any M in long normal form with resp ect to and is

n n

also in long normal form with resp ect to and The crucial prop erty of long

normal forms is the following see if  M A then there is a unique term M in

long normal form with resp ect to and such that M M

In Figure we give a formal system for deriving judgements of the form  prop We

often write simply  prop to mean that the given judgement is derivable in which case

we say that is wel lformed in and When is the empty set it is omitted from such

statements will only b e omitted when it can b e understo o d from the context

The fourth comp onent of the presentation A is a set of formulae the axioms such that

each formula in A is wellformed in

Logical consequence for A

H

A

 M A  M A P hA A i P

n n n

 P M M prop

n

x A  prop  prop  prop

 prop  x A prop

Figure Wellformedness rules for formulae

Ax A Ass H

H H

A A

Sub H M x M N

A

H N x

A

I H E H H

A A A

H H

A A

I x A H E H x A  M A

A A

H x A H M x

A A

Restriction on I x do es not o ccur free in H

Figure Rules for metalogical consequence

relates H and where H is a set of formulae the hypotheses and each formula in H fg

is wellformed in and This relation is given by the formal system of Figure

In the sequel we shall require the following elementary derived result ab out consequence

Lemma weakening If H and al l formulae in H are wel lformed in

A

then H H

A

The easy pro of by induction on the structure of derivations is omitted

Semantics

As the metalogic is intuitionistic with quantication over all higher types we seek a semantics

in terms of Kripke mo dels in which all typed lambda terms can b e interpreted at each world

The Kripke lambda mo dels of Mitchell and Moggi are thus a natural choice Although we

follow their pap er quite closely the reader is advised that some of our notation and terminology

diers from that of

An extensional Kripke T P prestructure is a sextuple

AB A

hW fA g fP g f g fi gi

w w

w w w

where

W is a set of worlds partially orded by

fA g is a family of sets A indexed by types A and worlds w

w w

fP g is a family of relations P A A indexed by predicate symbols

w w w n w

P with declarations P hA A i in P and worlds w

n

AB AB

A B A B indexed by pairs of g is a family of functions f

w w w

w w

types A B and worlds w

A A

A A g is a family of functions i fi indexed by types A and pairs of

w w

w w w w

worlds w w

sub ject to the conditions given b elow In these and henceforth we adopt the following nota

AB

f a When tional conventions When f A B and a A we write f a for

w w

w

A

a A and w w we write a a for i

w w w w

w w

The conditions are

A

identity For all worlds w i is the identity

w w

A A A

i i comp osition For all w w w i

w w w w w w

A AB AB AB B

i i naturality For all w w i

w w w w w w w w

extensionality If f g A B and for all w w for all a A

w w w w

f a g a

w w

then f g

w w

p ersistency If P a a then for all w w P a a

w w nw w w nw

Thus a prestructure is an extensional Kripke applicative structure in the terminology of

together with an extra parameter fP g used for interpreting the predicates of the logic

w

A partial element p of type A in a prestructure is given by an upp erclosed subset domp

W its domain and a family of elements fp g indexed by worlds w domp such that for all

w

A

p p w w domp p A and i Given p A we write p for the induced

w w w w w w

w w

partial element of type A with domain fw j w w g given by the elements p A A

w w

global element is a partial element p for which domp W

A structure is an tuple

AB AB C A A A

1 2

g fK g fS gi g fi hW fA g fP g f

w w

w w w w w

AB AB C

which is a prestructure extended by fK g and fS g where

w w

AB

K is a global element of type A B A such that for all worlds w for all a A

w

AB

ab a for all b B K

w

w

AB C

S is a global element of type A B C A B A C such that

for all worlds w for all f A B C for all g A B for all a A

w w w

AB C

f g a f ag a S

w

A structure is a tuple

A A A AB AB C

1 2

g fi hW fA g fP g fc g f g fK g fS gi

w w w

w w w w w

which is a structure extended by fc g where

w

fc g is a family of global elements c of type A indexed by constants c with decla

w

rations c A in

Henceforth we refer to a structure as W leaving the other comp onents implicit

An environment is a function from variables to partial elements We say that interprets

at w if for all x A x is a partial element of type A with w domx Clearly if

interprets at w and w w then interprets at w to o Also any environment interprets

the empty context at any world Given an environment and an element a A we write

w w

x a for the environment that agrees with on variables other than x and which assigns

the induced partial element a to x If interprets at w and a A then clearly x a

w w

interprets x A at w

If M has type A in and interprets at w then the interpretation M A of M

w

w

by at w is dened inductively on the structure of M by

c c

w

w

x x

w

w

x A M the unique f A B where A B is the type of

w w

w

x A M in such that for all w w for all a A

w w

xa

f a M

w w

w

M N M N

w w w

As in the existence of the f required in the x A M clause is given by the S and K

w

combinators and its uniqueness is guaranteed by extensionality Clearly if M is welltyped in

is indep endent of so we just write M the empty context then the value of M

w

w

We now give some lemmas concerning the interpretation of terms in structures

A

M M Lemma If  M A interprets at w and w w then i

w

w w w

Lemma If x A  M B  N A and interprets at w then M N x

w

xN

M

w

N Lemma If  M A M N and interprets at w then M

w w

The rst two lemmas are proved by straightforward inductions on the structure of M The

third is proved by an induction on derivations in the usual formal system for equality of

M N using Lemma in the verication equality

If is wellformed in and interprets at w then the forcing relation w j is

dened inductively on the structure of by

w j P M M i P M M

n w n

w w

w j i for all w w if w j then w j

w j x A i for all w w for all a A w j

w w xa

If H is a set of formulae each wellformed in and interprets at w then we write w j H

to mean that w j for all H If is wellformed in the empty context then whether

w j holds or not is indep endent of so we write w j We write W j to mean

for all w W w j

The lemmas b elow give basic prop erties of the forcing relation

Lemma If w j and w w then w j

Lemma If  M A and interprets at w then w j M x if and only if

w j

xM

Both these lemmas are proved by induction on the structure of The base case of the rst

uses Lemma together with the p ersistency prop erty of the structure

A Amodel is a structure W such that for all A W j

Theorem soundness and completeness The two statements below are equivalent

H

A

For al l Amodels W for al l w W for al l interpreting at w if w j H

then w j

We devote the rest of this section to an outline of the pro of of the theorem

Soundness ie is proved by a straightforward induction on the derivation of

H Lemma is used in the verication of b oth the E rule and in conjunction

A

with Lemma the Sub rule

To prove completeness we construct a particular mo del W based on the pre

A A

sentation A The set of worlds is just

W f H j every formula in H is wellformed in g

A

Its partial order is given by

H H i and H H

A

The interpretations of the other comp onents of the structure are

A fM j  M A M is in long normal formg

H

P M M i H P M M

H n A n

c c

H

AB

M N M N

H

A

i M M

H H

AB

K x A y B x

H

AB C

S x A B C y A B z A xz y z

H

Prop osition W is a structure

A A

A

is b ecause Pro of First all the comp onents are clearly welldened in particular i

H H

long normal forms are preserved by context extensions So we need only check the vari

ous conditions Identity comp osition and naturality all follow trivially from the denitions of

AB A

Persistency is an immediate consequence of weakening Lemma To and i

H H H

prove extensionality supp ose M M A B are such that for all for all H

H

H for all N A M N M N Then in particular for x A

H fxAgH

where x do es not app ear in M x M x and so M x M x But then

x A M x x A M x and so by equality M M But M and M are b oth in

AB

long normal form so M M proving extensionality It remains to check that K and

AB C

S satisfy the required equalities but these follow easily from the rule of typed lambda

calculus 2

Given a context we construct a canonical environment as follows If for some

A x A then x is the partial element with domain f H j g given by

x x Otherwise if there is no A such that x A then x is the trivial

H

partial element with domain Clearly for all interprets at H

We can now state the basic prop erties of W

A A

Lemma If  M A and then M M

H

Pro of By an easy induction on the structure of M 2

Lemma H if and only if H j

A

Pro of By induction on the structure of The cases are

P M M Immediate from denition of P

n H

 Supp ose H Take any and H H such that H j

A

Clearly H j So by the induction hypothesis H Now

A

H so H Then by the induction hypothesis again

A A

H j so clearly H j all the variables in are in Thus we

have shown that H j as required

Conversely supp ose H j Now H so by the induction

A

hypothesis H fg j But then by the supp osition H fg j

So again by the induction hypothesis H Thus clearly H

A A

8x A Supp ose H x A Take any H H and M A

A H

Thus  M A and H x A so H M x Now by the in

A A

duction hypothesis H j M x so clearly H j M x Thus by

Lemma H j () Then by Lemma H j as

xM

xM

M is necessarily in long normal form We have therefore shown that H j

x A as required

Conversely supp ose H j x A Then x A So

fxAgH

fx Ag H j Then by the induction hypothesis x A H

fxAg A

So clearly H x A

A

2

Corollary W is a Amodel

A A

Pro of Immediate 2

We now nish the pro of of completeness Supp ose that holds Then in particular

H j So by Lemma H as required

A

It is worth comparing our use of Kripke lambda mo dels with the use in In b oth cases

the role of the partial order is to mo del intuitionistic entailment But there are dierences

in emphasis due to the dierent logical languages considered In although it is remarked

that the mo dels interpret full intuitionistic predicate logic with quantication over all higher

types only the interpretation of equations is given explicitly This is b ecause their interest is

in obtaining a completeness theorem for the usual equational consequence relation of the typed

lambdacalculus when empty types are p ermitted In this pap er we to o are not making full use

of the scop e of the mo dels We consider only a fragment of the full intuitionistic logic and we

have no equality predicate in the logic The absence of equality means that the denition of

mo del could b e simplied in various ways For example it would b e p ossible to insist that the

A

are injections However such restrictions are unnatural we shall have use for a co ercions i

w w

mo del in which the co ercions are not inclusions Furthermore we wish to keep the denition

of mo del in its full generality to allow the logic to b e extended with equality and indeed the

other connectives if desired Note that a completeness pro of for the logic with equality would

require a mo del built out of equivalence classes of terms as in for unique long normal

forms would no longer b e available

Logics as consequence relations

The emphasis of this pap er is to b e on the use of the metalogic as a logical framework In

order to investigate this formally we need to consider what it means to enco de a logic So as

a preliminary step it is necessary that we establish a precise notion of logic

We consider a logic to b e a pair L where L is a countable set of formulae and

L L is a p ossibly noncompact consequence relation This viewp oint is over simplistic

on at least two counts First there is no analysis of the underlying syntax of formulae

Second many wellknown logics have consequence relations that are not ordinary One might

also criticise on the grounds that pro oftheory and semantics ought to b e imp ortant comp onents

in the denition of a logic But generally the consequence relation really is the fundamental

characteristic of a logic Though one is often interested in many dierent pro of systems and

semantics for the same logic the consequence relation remains invariant However it is to b e

hop ed that natural extensions of the ab ove notion of logic taking syntax pro oftheory and

semantics into account will arise

Actually even according to the ab ove approach semantic issues are not entirely overlooked

It turns out that the consequence relations we consider corresp ond exactly to the entailment

relations of languages with a certain kind of validitystyle semantics It is this corresp ondence

that motivates the choice of denition of consequence relation It is fair to say that the semantic

corresp ondence is not very deep but this is inevitable when we work with such a sup ercial

notion of syntax

For the moment we supp ose a given L and an arbitrary L L We use and

to range over elements of L and to range over subsets of L Every set of formulae

determines a theory Th dened by

Th f j g

We dene Theories fTh j Lg the set of theories of Note that L itself may

well b e a theory it wil l b e whenever is a consequence relation It will b e a recurring theme

that the inconsistent theory will not b e distinguished thus enabling many denitions to b e

more uniform If desired all denitions could b e easily repaired to treat the inconsistent theory

separately

Denition consequence relation is a consequence relation if it satises the fol low

ing two conditions

CR If then

CR If and for al l then

A consequence relation is said to b e compact if whenever there is a nite

such that

Denition validitystyle semantics A validitystyle semantics for is a pair Mod j

where Mod is a set of models and j Mod L is a satisfaction relation satisfying

i for al l M Mod if for al l M j then M j

Theorem The fol lowing are equivalent

is a consequence relation

Th is a closure operation on L

has a validitystyle semantics

Pro of It is easy to check that is equivalent to and that implies To see that

implies assume that is a consequence relation We now exhibit a validitystyle semantics

for The set of mo dels is

Mod L

and the satisfaction relation is dened by

j i

It is easy to check that this is indeed a validitystyle semantics for 2

Theorem gives the promised corresp ondence b etween consequence relations and semantics

One way in which it is rather shallow is that it says nothing ab out the existence or nature of

interesting mo dels

Henceforth we take to b e a consequence relation over L and Mod j to b e a chosen

validitystyle semantics for

We now x some notation that we shall use later on Each set of formulae determines

a set of mo dels Mods dened by

j

Mods fM j for all M j g

j

We say that M Mods is a model of In fact the set of mo dels is determined by the

j

theory of that is Mods Mods Th Note again that the inconsistent theory

j j

L is not treated sp ecially in that Mods L may b e nonempty Conversely each set of mo dels

j

S determines a theory Th S dened by

j

Th S f j for all M S M j g

j

It is easy to check that Th S is indeed a theory

j

The denition of consequence relation ab ove is standard except that we do not follow the

common practice of assuming compactness In essence it is equivalent to the relations considered

ever since Tarski introduced his consequence op erators There are two reasons for not

assuming compactness One is that many interesting noncompact logics exist The second is

that without compactness we obtain the equivalences of Theorem The notion of validity

style semantics used in the theorem is a familiar one from abstract mo del theory The

corresp ondence b etween consequence relations and semantics is similar to Scotts truthvaluation

motivation for his twosided consequence relations

Enco ding logics in the metalogic

We now consider how the metalogic can b e used to enco de the consequence relation of a logic

An encoding of L is given by a presentation T P A containing a distinguished type

constant o T and a distinguished predicate true with declaration true hoi P together

with a bijective function

L fM j M o M is in long normal formg

mapping formulae of the ob jectlogic to their representing terms in the metalogic

For an enco ding to b e of any use it must resp ect the consequence relation of the enco ded

logic The enco ding is said to b e ful l if

implies true true

A

where true denotes the set ftrue j g It is said to b e faithful if

true true implies

A

An enco ding which is b oth full and faithful is said to b e adequate Adequacy is a minimal

correctness condition Without it there is a mismatch b etween the consequence relation of the

logic and its representation in the metalogic

Clearly any logic that has an adequate enco ding must b e compact this is b ecause of the

evident compactness of metalogical consequence In fact the converse holds any compact logic

has an adequate enco ding We do not go into details as the enco ding is obtained in a wholly

unilluminating way for example one includes separate term constants for each L and is

in general innite A more interesting result might b e obtainable by considering some suitable

notion of eective consequence relation The compactness of such a consequence relation ought

to follow from an adaptation of the MyhillShep erdson theorem of recursive function theory

The desired theorem would b e that the notion of eective consequence relation coincides with

that of consequence relation with an adequate nite presentation

The two halves of adequacy each corresp ond to conditions on the class of Amo dels

Given a Amo del W dene form W L by

form w f j w j true g

We write form W for the set fform w j w W g

Prop osition The fol lowing are equivalent

The encoding is ful l

For al l Amodels W form W Theories

Pro of Supp ose the enco ding is full Let W b e any Amo del and take any w W

We must show that form w Theories Supp ose then that form w By fullness

trueform w true But by denition of form w for all form w w j

A

true So by the soundness of the metalogic w j true But then form w So

indeed form w Theories

Conversely supp ose that for all Amo dels W form W Theories Supp ose

further that We must show that true true For this we use the

A

mo del W constructed in the pro of of completeness in section By Corol

A A

lary we know this is indeed a Amo del Consider the world true By the

initial supp osition form true Theories But clearly form true so

form true as any theory is closed under consequence Therefore true j

true So by the denition of W true true 2

A A A

Prop osition The fol lowing are equivalent

The encoding is faithful

There exists a Amodel W such that Theories form W

Pro of Supp ose the enco ding is faithful We will show that the Amo del W

A A

has the required prop erty Take any T Theories We must show that there exists H

W with form H T For this we take the world true T Clearly from the de

A

nition of W T form true T We now show that form true T T

A A

Supp ose that form true T Then true T j true so trueT

A

true Therefore by faithfulness T Thus indeed T as T is closed under con

sequence

Conversely supp ose there exists a Amo del W such that Theories form W

Supp ose further that true true We must show that Let w W b e such

A

that form w Th such a w is guaranteed to exist by the assumed prop erty of W

Clearly for all w j true So by soundness w j true But then form w

so Th Thus as required 2

The ab ove prop ositions give the basic connections b etween the semantics of the metalogic

and the use of the metalogic as a logical framework Due to the universal quantication over

mo dels Prop osition is of mainly formal interest In contrast Prop osition is genuinely

useful and will provide an imp ortant to ol in the sequel

One imp ortant use of Prop osition will b e to establish the adequacy of enco dings Proving

adequacy is a three stage pro cess First it is necessary to dene the enco ding function and

show that it is indeed a bijection as required This task can only b e done syntactically usually

by an easy induction on the long normal forms of appropriate types Second it is necessary

to establish fullness Normally the easiest way to do this is to start with a pro of system

for the enco ded logic and map pro ofs of logical consequence in this system to pro ofs of the

representation of the consequence in the metalogic Again this step is usually straightforward

Lastly faithfulness remains to b e proved The standard technique is to show that the mapping

of pro ofs used in establishing fullness is itself a bijection onto metalogical pro ofs in a certain

normal form However in order to do this it is necessary that the metatheory do es stand in

the right relationship to the pro of system of the ob jectlogic Often this will not b e the case

either b ecause of the inability of the metalogic to exactly mimic the pro of system or more

p ositively b ecause the metatheory allows other still valid inferences not directly avilable in

the original pro of system see the next section No doubt even in such dicult cases it is

still p ossible to prove faithfulness by a syntactic argument However Prop osition oers

an alternative approach It is enough to construct a Amo del with the requisite prop erty

which is usually apparent These two approaches to proving faithfulness are analogous to the

two standard approaches to proving the underivability of a formula in logic using on the one

hand a normalform result for derivations and on the other a mo del refuting the formula

We conclude this section with an example semantic pro of of adequacy We shall show that

the presentation T P A the A subscript stands for arithmetic the Q subscript

A A A Q

stands for system Q in Figure gives an adequate enco ding of the consequence relation

L of Robinsons arithmetic Q The language of Q is that of rstorder arithmetic with

A Q

terms t and formulae in accordance with the grammar b elow

t x j j st j t t j t t

t t j j j x

For simplicity we just consider two connectives implication and negation and one the univer

sal quantier which is enough as the logic is classical Again we assume that the notions of

free and b ound variable are understo o d As usual a sentence is a formula with no free variables

Although we have b een informally referring to L as the formulae of the ob jectlogic here we

take L to b e the sentences of arithmetic is just classical rstorder entailment over L

A Q A

sub ject to the validity of the axioms for Q Note that we are considering Q as a logic and

hence as a consequence relation This is a slight abuse of terminology Q should really refer to

a particular theory the sentences for which However we are more interested in the

Q

logic than the theory as T P A will turn out to b e adequate for logical consequence

A A A Q

It is also of practical interest to enco de the consequence relation For example we might want

to consider derivations from true or even false unprovable formulae such as Godels sentence

or various forms of induction

T f og

A

P ftrue hoig

A

f o o o o o o o o

A

s g

A f o o true

Q

o o o true

o o true

o t truex x t

t truet t

o o true true true

o o x true x true x x

o t t truet t truet truet

truex y sx sy x y

truex sx

truex x y x sy

truex x x

truex y x sy sx y

truex x

truex y x sy x y xg

Figure A presentation of Robinsons Q

Before proving adequacy we give a brief informal explanation of the presentation in Fig

ure There are two type constants for terms and o for formulae The term constructors

in generate the rstorder language for arithmetic Implication is delib erately distinguished

notationally from metalogical implication and universal quantication is distinguished from

its metalogic counterpart by a dierent convention of usage For readability we write

and as inx op erators using standard conventions for example asso ciates to the right

We also write x for x The axioms of the presentation divide naturally into groups

The rst ve give axioms for classical rstorder logic with equality and the next three give

rules of inference each of these groups sub divides further into a prop ositional part a quanti

cational part and an equality part The system presented is a quite standard Hilb ert system

though our slavery to Okhams razor means there is unlikely to b e an identical system in the

literature The next seven axioms are just the axioms of Q These consist of Peanos six axioms

together with the additional axiom x x y x sy necessary in the absence

of induction

Given our notational conventions it is now a simple matter to dene the mapping from

L to long normal forms of type o If is a sentence then is also the notation for a

A

to b e the identity map on notation To see that term of the metalogic Thus we take

this has the correct prop erties one proves by an easy induction on the structure of terms and

formulae that if all free variables in t and are contained in the nite set X of variables then

fx j x X g  t and fx j x X g  o and moreover t and are b oth in long

A A

normal form Further by induction on the structure of long normal forms of terms of type

and o in contexts of the form fx j x X g one shows that all such terms arise uniquely from

a t or a resp ectively Thus sp ecialising to the case X we have that is a bijection as

required

Next we should prove fullness This step is easy in principle but tedious to carry out in

detail so we give only the general outline Take any Hilb ert system for rstorder logic with

equality together with the axioms for Q note that the Hilb ert system chosen do es not have

to b e the same as that implicitly given in A We want to translate derivations of from

Q

assumptions in the Hilb ert system where all the are sentences onto

n n

pro ofs of true true true For this it is necessary to translate derivations

n A

A Q

of op en formulae from op en formulae Supp ose then that are formulae with all free

n

variables contained in the nite set X fx x g We write X for the metaformula

k

x x One can now prove by induction on derivations in the Hilb ert system that

k

if follows from then

n

X true X true X true

n A

A Q

Again sp ecialising this to the case X gives the desired result

Only adequacy remains to b e proved To this end we construct a A mo del satisfying

A Q

the condition of Prop osition Let Mod b e the set of all classical mo dels of Q For each

Q

M in Mod we distinguish its internal structure as N s We are going to

Q M M M M M

construct a A mo del W The of worlds is given by W

A Q Q Q Q Q

Mod the reader who is b othered by the size problem should make some suitable

Q

restriction such as only considering mo dels M with domain N contained in a given innite

M

set A world is thus a subset S Mod Before giving the interpretations of the dierent

Q

comp onents of the structure at each world we rst interpret the type structure p ointwise

A

at each M Mod The interpretation at S is then given by the S indexed direct pro duct of

Q

the relevant p ointwise interpretations

Let M b e any mo del of Q The p ointwise interpretation of types at M is given by the full

type hierarchy

N

M M

o

M

A

M

A B B

M

M

where ftt g the set of truth values Rather than give an exhaustive treatment of the

constants in we dene a representative sample The interpretation of and at

A

N

M

N

N N N

M

M M M

and N M will b e elements

M M M M

M

resp ectively These are dened by

tt if b

b

M

if b tt

tt if for all a N f a tt

M

f

M

otherwise

tt if a a

a a

M

otherwise

a a a a

M M

In short the constants are interpreted in line with their real world meanings according to the

Tarskian semantics of rstorder logic

AB AB C

The combinators K and S are given the usual p ointwise interpretations For example

B

M

AB A AB

M

ab a A is dened by K K

M

M M

The ab ove interpretations of constants at M can b e extended to all welltyped terms just by

taking the usual interpretation of the typed lambda calculus in the full type hierarchy Thus if

 M A and is a environment function mapping each variable x with declaration x A

i i i

A

in to an element of A then M has an interpretation M A When M is closed

i M M

M

we just write M A The crucial prop erty of the p ointwise interpretation the mimicry

M M

of the Tarskian semantics is given by the lemma b elow

Lemma If  o then tt if and only if M j

M

A

Pro of The pro of is by induction on the structure of The induction passes through op en

formulae and terms using the established corresp ondences b etween these and long normal

forms of appropriate type

For terms supp ose all variables in t are contained in the set X fx x g Given

k

X N recall N one shows by an induction on t similar to but easier than

M M M

the induction on given b elow that t is just the usual rstorder interpretation of t in M

M

according to the environment

Now for formulae supp ose all free variables in are contained in X as ab ove We show

by induction on that for all as ab ove tt if and only if M j The four cases

M

are

t t t t tt if and only if by denition of t t if and only if

M

M M M

by established result on terms M j t t

: tt if and only if by denition of if and only if by induction

M

M M

hypothesis M j if and only if M j

) Similar to

8x X tt if and only if by denition of for all a N X

M M

M

xa

a tt if and only if for all a N tt using an obvious notation

M

M M

for up dating if and only if by induction hypothesis for all a N M j

M xa

if and only if M j x

The lemma follows by sp ecialising to X 2

We can now dene all the remaining comp onents of the structure W Types

A Q Q

constants and combinators are interpreted at S by

A A

S MS M

c fc g

S M MS

AB AB

K fK g

MS

S M

AB C AB C

S fS g

MS

S M

The only predicate true is given the interpretation

true fb g i for all M S b tt

S M MS M

A AB

where S S are dened by and i Finally

SS S

AB

ff g fa g ff a g

M MS M MS M M MS

S

A

fa g fa g i

M MS M MS

SS

It is straightforward to check the required conditions showing that the construction ab ove do es

indeed give a structure

A

A basic but imp ortant prop erty of the dened structure relates the interpretation of

A

terms at S to their p ointwise interpretations at all M S

Lemma Suppose  M A and interprets at S Dene for M S a function

A

X A where X is the set of variables in by

M

M

x a where x fa g

M S M MS

M

M

Then M fM g

MS

S M

Pro of By a straightforward induction on the structure on M 2

Finally we are in a p osition to establish the facts we need to prove the faithfulness of

A In the results b elow we make frequent use of the notation introduced on page

A Q

Lemma form S Th S

j

Pro of We must show that S j true if and only if for all M S M j But

S j true if and only if fttg if and only if by Lemma for all M S

S MS

tt if and only if by Lemma for all M S M j 2

M

Prop osition W is a A model

Q Q A Q

Pro of We must show that for all A W j First note that for the last

Q Q Q

seven axioms of A in Figure this follows immediately from Lemma Of the other eight

Q

metaaxioms we validate three

o o true

Supp ose we have S and with fa g and fb g Then

S M MS S M MS

f a b a g by Lemma

M M M M M MS

S

ftt g

MS

So S j true as required

o o x true x true x x

Supp ose we have S and with fb g and ff g such that

S M MS S M MS

S j x true x Then for all fa g S j true

M MS S xfa g

M

x So by Lemma for all a N b f a tt But then

M M M M M M

b f tt by the usual reasoning And thus again by Lemma

M M M M

ftt g So S j true x x as required x x

MS

S

o t t truet t truet truet

Supp ose we have S and with ff g t fa g and t

S M MS S M MS S

fb g such that S j truet t and S j truet Then applying Lemma

M MS

as ab ove it is easy to see that for all M S a b and f a tt so obviously

M M M M

f b tt Now again by Lemma S j true t as required

M M

The other axioms are validated in a similar way 2

The faithfulness of A now follows easily We need only show that W has the

A Q Q Q

prop erty required by Prop osition Let T b e a theory of We must show that T

Q

form S for some S W Dene S Mods T By the completeness theorem for rst

Q T j

order logic T if and only if for all M S M j So by Lemma T form S

T T

Note that the reader who has taken W to b e dened over mo dels M with N contained in a

Q M

given innite set must do a little more work In this case S is dened to b e the set of mo dels

T

of T of the appropriate form so an appropriate weak form of the LowenheimSkolem theorem

is required to give completeness in terms of the mo dels considered

Perhaps the ab ove pro of of adequacy seems rather longwinded Indeed a syntactic pro of

along the lines of those in would have probably b een shorter However now that we have

constructed the mo del and established its prop erties we are free to exploit it without rep eating

the eort This we will do on page to establish very easily the adequacy of an extension

of A Another b enet of the semantic pro of is that the mo del constructed gives us some

A Q

intuition as to the meaning of metalogical prop ositions

Clearly the ab ove pro of do es not rely on any prop erties particular to Robinsons Q In

fact analogous metho ds work for any rstorder theory However now we confess to why we

considered Q in preference to Peano Arithmetic PA One would like to axiomatise the induction

schema by a single metaaxiom

o true x x sx xx

And indeed adding this axiom to A we call the new set A do es give an adequate presen

Q PA

tation of PA Unfortately the structure constructed following the ab ove metho d out of

A

mo dels of PA is not a A mo del The problem is easy to identify The axiom giving the

A PA

induction principle has the full p ower of the secondorder induction axiom in the structure

A

Thus it can not hold at any world sets of mo dels of PA that contains a nonstandard mo del of

arithmetic One might try to patch this by restricting the p ointwise interpretations of predicate

types to arithmetically denable relations Thus o and o would b e resp ec

M M

tively the unary and binary arithmetic relations in M Unfortunately this attempted remedy

is also do omed Semantically we must b e able to apply any element of o to any

M

element of and obtain an element of o But if we apply a binary arithmetic rela

M M

tion to a nonstandard element of N the resulting unary relation is no longer arithmetically

M

denable

One way of avoiding the problem is to take in place of the ab ove metaaxiom for induction

all instances of the following metaschema

true x x sx xx

where ranges over f j  o is in long normal formg With this schema the

A

constructed structure do es indeed give a mo del However this is clearly an unsatisfactory

A

solution The presentation is innite whereas A is an nite presentation of PA

A PA

It is p ossible to prove the adequacy of A by constructing a syntactic mo del over

A PA

the of theories of PA We do not give details as there is an example of a of similar but

simpler construction in the next section A syntactic mo del could also b e used to prove the

faithfulness of A However we preferred to give the ab ove pro of to show how in some

A Q

cases an entirely semantic pro of is p ossible

Admissible rules

In this section we develop a simple theory of sequent rules for an arbitrary logic Given an

enco ding of the logic each rule has a corresp onding metaformula expressing its admissibility

We use the semantics to investigate under what conditions the metaformulae corresp onding to

admissible rules are theorems in the metatheory given by an adequate presentation

Throughout this section L is an arbitrary consequence relation When referred to A

is assumed to b e a presentation giving by means of the mapping an adequate enco ding of

L

In examples we will often assume that each L has a binary implication connective By

this we mean that there is a distinguished injective function from L L to L and we write

for the value of this function when applied to and We say that satises modus

ponens if

for all and if and then

We say that satises the deduction theorem if

for all and if then

A sequent is a nonempty nite sequence of formulae Normally one would

m

write The reason for using such a neutral notation is that the symbols

m

and are already tied up A rule has the form

S S

n

S

where n and S S S are all sequents A sequent is said to b e valid

n m

if A rule of the ab ove form is said to b e admissible if

m

for all if for all i i n S is valid then S is valid

i

Thus for example the rule

is admissible for all and if and only if the deduction theorem holds for

Given a sequent S consider the metaformula which we call S b elow

m

true true true

m

Intuitively this metaformula expresses the metaprop osition that holds Now

m

given a rule R of the general form dene its translation R to b e the metaformula b elow

S S S

n

Intuitively this metaformula expresses that the rule is admissible The ab ove intuitions will

b e given substance by results b elow

It is worth commenting on our notions of rule and admissibility and how these relate to

the usual notions The most common notion of admissible rule is that given by Troelstra

x see also pages However there the notion of rule is one b etween formulae

rather than sequents and the notion of admissibility is with resp ect to a xed theory rather

than a consequence relation For us the consequence relation is of primary interest It is for this

reason that we consider a more general form of rule with sequents for premisses and conclusion

Now the notion of admissibility for a rule of the form dep ends on how we stipulate that this

rule is to b e applied Supp ose S i m and S

i i im i m

i

One p ossibility would b e to stipulate that the rule is only applicable when for all i n

in which case one deduces that Clearly this notion of rule

i im i m

i

application induces a dierent notion of admissibility from ours Our denition of admissibility

is motivated instead by the naturaldeduction conception of rule application Written in a more

suggestive format we think of the rule ab ove as

m n nm

1 n

n m

So the rule is applicable if for all i n and for all i m

i im i i

i

in which case we deduce the formulae in b eing carried around as unused assumptions

With a little shuing of the conseqences it is easy to see that our denition of admissibility

is now the appropriate one We remark here that it would b e interesting to consider notions

of admissibility for the more general higherorder rules of SchroederHeister However the

secondorder rules we consider include all the natural deduction rules in common usage

One serious defect in our notion of rule is that each rule is considered only with resp ect

to xed formulae Usually rules are schematic The deduction theorem would normally b e

considered as just one rule in the shap e of schematic over and One would then prefer

the following translation which we henceforth call DT

o o true true true

The problem with this approach is that in order to make sense of a general notion of schematic

rule we require some theory of prop ositional connectives in L Similarly for DT to b e well

T fog

m

P ftrue hoig

m

f o o o a o b og

m

A f o o true

m

o o o true

o o true true true g

A A ftrue a trueb truea trueag

m

m

Figure Presentations of prop ositional minimal implicational logic

formed we require a consant o o o in Further there would have to b e extra

conditions on the translation ensuring preservation of connectives and comp ositionality

These are p erfectly reasonable requirements see for example but would take us away from

A

the simpleminded notion of logic of section However when p ossible we shall consider DT

in the examples that follow

A rst and simple connection b etween the adequacy of rules and the theoremho o d of their

metalogical translations is given by the prop osition b elow Remember that A is assumed

to give an adequate enco ding of L

Lemma For al l sequents S S is valid if and only if true S

A

Pro of A sequent S is valid if and only if if and only if

m m

true if and only if true S true by adequacy true true

A A

n

2

Prop osition For al l rules R if R then R is admissible

A

Pro of Supp ose S S S Take an arbitrary such that for all i

A

n

i n S is valid We must show that S is valid Now by the lemma for all i

i

i n true S So clearly true S But then again by the lemma

A A

i

S is valid as required 2

In it is noted that the metalogic has no facility for induction so there is no general

way of proving the admissibility of inference rules However we are only considering instances

of rules rather than quantied schematic rules so induction can play no part Nevertheless

as we prove b elow the converse of Prop osition still fails in general there are admissible

rules R such that R It is therefore natural to consider extensions of A with unprovable

A

translations of admissible rules Dene Adm fR j R is an admissible ruleg Let R b e a

subset of Adm We say that A is safe for R if A R is adequate Given that A

is adequate and for each R R R is admissible it might b e imagined that A is always

safe for R However this is not the case It is p ossible that the addition of the translation of

an admissible rule to an adequate signature can result in the loss of adequacy We now develop

an example to show all this

in Figure gives an adequate presen We rst show that the presentation T P A

m m m

m

tation of minimal implicational logic over two prop ositional constants L The formulae

m m

in L are given by the grammar

m

a j b j

The consequence relation is just intuitionistic entailment over L

m m

The mapping from formulae to long normal forms of type o is evident again it is

the identity map on notation so we omit the app endage Bijectivity is proved by an easy

induction on the structure of long normal forms Similarly there is an evident mapping from

pro ofs in the usual Hilb ert system for see for example page of to

m n

pro ofs of true true true so the fullness of A is easy to establish

n A m m

m m

The fullness of A follows as A A

m m

m m

To prove faithfulness we construct a suitable A mo del Although such a mo del could

m

m

b e constructed out of Kripke mo dels of we construct instead a mo del of the syntactic kind

m

alluded to in the discussion at the end of section The mo del is dened over the discrete

partial order W where W Theories The type structure is the same at each world

m m

m

and is given by the extensional collapse of the closed terms of Thus the interpretation of

m

A is the quotient of fM j M Ag by an equivalence relation where is inductively

A A

m

dened by setting to and dening

o

M M i for all N N if N N then M N M N

AB A B

It is easy to show by induction on types that is a partial equivalence relation It is also

A

easy to see that c c for the three constants in as they are at worst rstorder Now the

A m

reexivity of for all A follows from the wellknown Basic Lemma of logical relations see

A

x

The entire structure is dened as follows

m

A fM j M Ag

T A

m

true M i M for some T

T

c c

T

AB

M N M N

T

AB

K x A y B x

T

AB C

S x A B C y A B z A xz y z

T

A A

is only dened for T T as the partial order is discrete so i There is no need to sp ecify i

TT TT

in which case it must b e the identity Of the various conditions that have to b e satised for

W to b e a structure the most interesting is extensionality However this is easily

m m

shown by induction on the structure of types The other conditions are trivially veried

It is now p ossible to prove the adequacy of A

m

m

model Prop osition W is a A

m m

m

Pro of We must show that for all A W j

Q Q

m

The three axioms in A are all validated easily We consider only the third

m

o o true true true

Supp ose we have T and with M N such that T j true and

T T

T j true But M and N must corresp ond to formulae of L and say not to

m

b e confused with the metavariables But then T and T so by mo dus p onens

T Thus clearly T j true as required

For the fourth axiom

truea trueb truea truea

Supp ose we have T such that T j truea trueb true a Now supp ose for contradiction

that T j truea Then as the partial order is discrete it is clear that T j truea trueb

So T j truea giving the desired contradiction 2

In this case the prop erty required by Prop osition is evident Given T Theories it is

m

is indeed faithful immediate from the construction of the mo del that form T T So A

m

m

and hence adequate Note that we have also established the adequacy of A

m m

We now address the issues raised ab ove providing a counterexample to the converse of

Prop osition and showing that the stated problem with safety do es indeed arise It is well

known that satises the deduction theorem So setting

m

R ftrue a true b truea b

truea b a truea truea b a ag

we have that R Adm Either of the metaformulae in R provides a counterexample to the

m

converse of Prop osition We just show one case

Prop osition truea trueb truea b

A

m

m

Pro of By soundness of the metalogic it is enough to nd a T such that T j true a

trueb truea b in W Dene T Th Then clearly T j true if and only

m

m

if is a theorem of minimal logic Thus T j truea so as the partial order is discrete T j

truea true b But also T j true a b so indeed T j truea trueb truea b

2

The ab ove prop osition was also observed by Randy Pollack who proved it syntactically The

problem with safety is illustrated by the fact that A R is not adequate hence inciden

m

m

tally neither is A fDTg It is easy to show that truea b a a

m A R

m m

m

but it is wellknown that a b a a Therefore A though adequate is not

m m

m

safe for R ab ove

In the ab ove example the source of the problem with safety is the axiom

truea trueb truea truea

This is redundant A which do es not contain the axiom is also adequate Intuitively

m m

gives metaimplication an asp ect of classical b ehaviour it is an instance of Peirces Law

is adequate as there is no need for ob jectlevel implication to b ehave in the same way A

m

m

as metaimplication However when R is added the two implications are forced to b ehave alike

in two critical cases and thus ob ject implication inherits unwanted classical prop erties

In view of the problem with safety it is natural to consider conditions under which A is

safe for an arbitrary R Adm Clearly this is so if and only if A is safe for Adm itself

A semantic condition for A to b e safe for Adm is given by Corollary b elow

Lemma If W is a structure with form W Theories such that for al l T

form w there exists w w with form w T then for al l sequents S for al l w W

w j S if and only if S is form w valid

1

Private communication

Pro of Let W b e any structure satisfying the stated condition Take any sequent

S and any w W

m

true Let w w b e such that true Supp ose w j S ie w j true

m

form w Th form w f g such a w is guaranteed to exist by the condition

m

on W Then w j true i m so w j true But then form w so

i

form w by required prop erty of w Thus indeed S is form w valid

m

Conversely supp ose S is form w valid ie form w Now supp ose w w

m

is such that w j true i m Then form w f g form w But

m

i

form w Theories by the condition on W so form w Thus w j true

true as required 2 true This shows that w j true

m

Prop osition If W is a structure with form W Theories such that for al l

T form w there exists w w with form w T then for al l rules R W j R

if and only if R is admissible

Pro of Let W b e any structure satisfying the stated condition Let R b e any rule of

the general form

S Supp ose further that all S Supp ose W j R ie for all w W w j S

n

S i n are valid Then clearly all the S are Th valid Let w b e any world such

i i

that form w Th the existence of w is guaranteed by the condition on W Then

i n so clearly w j S But then again by the lemma S by the lemma ab ove w j S

i

is Th valid and hence valid Thus R is indeed admissible

Conversely supp ose R is admissible Take any w W such that w j S i n Then

i

by the lemma all S are form w valid So by admissibility S is form w valid But then

i

again by the lemma w j S So for all w W w j S S S as required 2

n

Corollary If W is a Amodel with form W Theories such that for al l T

form w there exists w w with form w T then A is safe for Adm

Pro of By the prop osition W is a A Adm mo del So by Prop osition A

Adm is faithful and hence adequate 2

Note that by prop ositions and we can always nd a Amo del with form W

Theories Thus the only extra condition to satisfy is that on the relationship b etween and

Intuitively the only prop erty of a world w in which we are interested is the contents of

form w The condition establishes that form is a zigzag morphism see from W

to the lattice Theories

We can now show that A is safe for Adm and thus unsurprisingly b etter b e

m m

m

haved than A To this end we construct a A mo del satisfying the condition

m m m

m

of Corollary This time the mo del is built over the partial order W where again

m

W Theories All the comp onents of the mo del are exactly as in the discrete case ab ove

m

m

A

for T T but this is simply This time it is necessary to dene i

TT

A

i M M

TT

It is readily checked that the resulting structure is a a A mo del the pro of go es through

m m

exactly as b efore It is also easy to see that the conditions of Corollary are satised as form

is the identity morphism from the lattice Theories to itself So indeed A is safe

m m

m

for Adm

m

To investigate the applicability of the theory developed in this section we return to the

enco ding A of Robinsons Q given in the previous section First we show that there are

A Q

admissible rules not provable in A It is wellknown that the deduction theorem holds

A Q

for classical logic and hence for remember we are only considering consequence b etween

Q

sentences Thus every rule of the form is admissible Let G b e any sentence in the language

of arithmetic for which neither G nor G Godels Theorem guarantees the existence of

Q Q

such a G Now true G true trueG is clearly the translation of a

rule of the form and thus of an admissible rule However trueG true

A

A Q

trueG and thus DT This fact can b e proved by considering

A

A Q

a A mo del W dened as W but with the discrete partial order We do

A Q Q Q Q

not go into details but it is easy to prove that in this mo del that the world Mod refutes the

Q

sentence Prop osition will show that this fact can not b e proved using W

Q Q

As there are admissible rules which are unprovable in A we would like to know at

A Q

least that A is safe for Adm Unfortunately W fails the condition of Corol

A Q Q Q

Q

lary To see this consider the world where N is the standard mo del of arithmetic

y

S fM j M is mo del of Q not elementary equivalent to Ng

y

Lemma if and only if for al l M S M j

Q

Pro of The lefttoright implication is by classical soundness For the converse supp ose the

y

contrary Then there is a such that for all M S M j but By classical

Q

y

completeness there exists a mo del M of Q such that M j This mo del cannot b e in S so

it must b e elementary equivalent to N It is now clear that for any true sentence of arithmetic

for all mo dels M of Q M j Therefore again by completeness But then

Q

Q fg gives a nite axiomatisation of the true sentences of arithmetic which is imp ossible

2

y y

So Th Th S form S the rst equality is by the lemma the second is by

j

Q

y

Lemma Now let T b e the set of all true sentences of arithmetic Clearly T form S

N N

y

However there can b e no S with S S such that form S T For such an S must b e

Q N

nonempty as form L but any M S must satisfy the negation of some sentence in

A

T as it can not b e elementary equivalent to N So the condition of Corollary do es indeed

N

fail

One way of showing that A is safe for Adm is to mo dify the denition of W

A Q Q Q

Q

Redene

W fMods T j T Theories g

Q j

Q

The rest of the mo del is constructed as b efore This time Corollary do es apply as form is

now an isomorphism from W to Theories A dierent and more detailed pro of

Q Q

Q

will b e given b elow exploiting prop erties of the implication connective

When a logic has implication and satises b oth mo dus p onens and the deduction theorem

it turns out that all admissible rules are reducible to instances of these two cases Supp ose then

that L is a logic satisfying these conditions Thus the following are b oth subsets of Adm

MP ftrue true true j Lg

S

DT ftrue true true j Lg

S

Again we assume that A is an adequate enco ding of the logic

Prop osition If for al l MP DT then R if and only if R is

S S A A

admissible

Pro of The only if direction is by Prop osition For the if direction we rst dene some

notation Given a sequent S dene

m

S

m

Now supp ose R of the general form is admissible Dening fS S g we

n

have for all i n that by m applications of mo dus p onens

i i im i

i

where S In short all the S are valid So by the admissibility of

i i im i i

i

R where S Now by m applications of the deduction

m m

theorem ie S S S Hence by adequacy

m n

trueS true S trueS But now using DT for the lefthand side and

n A S

S So clearly R 2 S MP for the right it is easy to see that S

A A S

n

Corollary A is safe for Adm if and only if it is safe for MP DT

S S

Pro of The lefttoright implication is obvious Supp ose then that A is safe for MP DT

S S

The result follows immediately from the ab ove prop osition applied to A MP DT 2

S S

We can now give the promised pro of that A is safe for Adm A is a logic

A Q A Q

Q

with implication satisfying b oth mo dus p onens and the deduction theorem As A contains the

Q

following axiom

o o true true true

it is clear that for all MP Thus by Corollary it is enough to show that

S A

A Q

A is safe for DT In fact we will show that A fDT g is adequate

A Q S A Q

Prop osition W is a A fDTgmodel

Q Q A Q

Pro of We need only show that for all S W S j DT Supp ose then that we have a

Q

world S and an environment with fa g and fb g b oth these in

S M MS S M MS

o such that S j true true Let M b e any element of S Clearly S fMg so if

S Q

fMg j true then fMg j true Thus a or b tt But then by Lemma

M M

ftt g So S j true as required 2

MS

S

We have already shown that W has the prop erty required by Prop osition so the

Q Q

faithfulness and hence adequacy of A fDTg is immediate

A Q

It is easy to show that Prop osition implies by the soundness of the metalogic together

with Prop osition that W j R if and only if R is admissible As we have shown

Q Q

that W fails the condition of Prop osition the condition is seen to b e sucient but

Q Q

not necessary

It is also clear using Prop osition and the established adequacy result that

R i R is admissible

A fDT g

A Q

So this presentation proves all admissible rules

The rather simple connection of Prop osition showing that the provable admissibility

of any inference rule is reducible to mo dus p onens and the deduction theorem is a testimony

to the oversimplicity of our notion of inference rule With a reasonable notion of schematic

inference rule the situation is likely to b e a go o d deal more interesting Still there are enough

surprises even with the simpler notion such as the p otential problem with safety to justify our

investigation at this level

The most natural way of extending this work to deal with more complex notions of rule

would b e to consider rst more elab orate notions of logic One p ossible development would

b e to include language structure in the denition of logic allowing for b oth connectives and

quantiers Another extension would b e to consider logics with other notions of consequence

such as multiple judgements At the logical level these notions are already established see

for example However such ideas have yet to b e approached using the semantic metho ds of

this pap er

At least whatever extensions to the notion of logic are considered the semantics of section

is already in place to b e applied However whether or not the fruitful connections of sections

and will generalise remains to b e seen

Acknowledgements

I gratefully acknowledge the supp ort of my sup ervisors Gordon Plotkin and David Pym

References

A Avron F Honsell and I Mason Using typed lambda calculus to implement formal sys

tems on a machine LFCS Rep ort Series ECSLFCS Lab oratory for the Foundations

of Computer Science Computer Science Department University of Edinburgh

J Barwise Axioms for abstract mo del theory Annals of Mathematical Logic

N G de Bruijn A survey of the pro ject automath In J P Seldin and J R Hindley

editors To H B Curry Essays in Combinatory Logic Lambda Calculus and Formalism

pages Academic Press

A Felty Specifying and Implementing Theorem Provers in a HigherOrder Logic Program

ming Language PhD theses University of Pennsylvania

P Gardner Representing Logics in Type Theory PhD Thesis Department of Computer

Science University of Edinburgh

R Harp er F Honsell and G Plotkin A framework for dening logics In Proceedings of

nd Annual Symposium on Logic in Computer Science pages

J R Hindley and J P Seldin Introduction to Combinators and the Calculus London

Mathematical So ciety Student Texts Cambridge University Press

G Huet A unication algorithm for typed calculus Theoretical Computer Science

J C Mitchell Type systems for programming languages In J van Leeuwen editor

Handbook of Theoretical Computer Science volume I I pages Elsevier Science

Publishers

J C Mitchell and E Moggi Kripkestyle mo dels for typed lambda calculus Journal of

Pure and Applied Logic

B Nordstrom K Petersson and J Smith Programming in MartinLofs Type Theory

Oxford University Press

L Paulson The foundation of a generic theorem prover Journal of Automated Reasoning

P SchroederHeister A natural extension of natural deduction Journal of Symbolic Logic

D S Scott On engendering an illusion of understanding Journal of Philosophy

A Tarski Logic Semantics Metamathematics Oxford University Press

AS Troelstra Metamathematical investigations of intuitionistic arithmetic and analysis

Lecture notes in mathematics

J van Bentham Corresp ondence theory In D Gabbay and F Guenther editors Handbook

of Philosophical Logic volume I I pages D Reidel Publishing Company

A Normalization Pro of for an Impredicative Type System with

Large Elimination over Integers

Benjamin Werner

INRIA Ro cquencourt

August

Abstract

We prove strong normalization for a type system that includes system F dep endent

types primitive integers and the ability to dene types by primitive recursion over integers

We give some applications motivating this feature

Introduction

The aim of this note is to show how one can prove strong normalization for a type system

in which types can b e dened by case and by recursion over some inductive structure here

integers thus setting the bases for a consistency pro of of systems like the one implemented in

Co q Let us sketch the technical motivations for these systems

Need for inductive types

In Co quand and Paulin give a uniform presentation of inductive denitions which can

b e added to the Calculus of Constructions or nearly any other GTS To simplify one may

say that this denition scheme generalizes the primitive integers of Godels system T

It is wellknown that in an impredicative framework as is the Calculus of Constructions in

ductive structures integers lists sums pro ducts may b e dened internally using enco dings

like Churchs integers However Co quand and Paulin listed some drawbacks of this

technique thus motivating the introduction of their extension essentially

Eciency for Churchs integers the predecessor cannot b e calculated in constant time

The induction scheme in the case of integers Peanos axiom cannot b e proven internaly

Moreover the induction principle do es not corresp ond to recursion anymore

It is imp ossible to prove in the system

In what follows we are mainly fo cusing on the third p oint Let us try to explicit it proving

means precisely exhibiting a predicate P over natural numbers such that one can prove

P and the negation of P In the pure Calculus of Constructions there is no hop e to

dene such a predicate b ecause ultimately all we can do is quantify over all predicate variables

b enjaminwernerinriafr

Nat Prop The right and elegant way to formalize this argument is to use the erasure

map which transforms any type resp pro of of the Calculus of Constructions into a type of

F resp a term of F inhabiting the corresp onding type Supp ose we had a closed pro of p of

the prop osition

P Nat Prop P P S Q Prop Q

then by mapping p into F we would get a closed term inhabiting the type

which we know is imp ossible as there is no closed term of type

Large elimination schemes

So it is the mechanism for dening dep endent types in CoC which app ears to b e unsatisfactory

Here we want to enhance it at least in the case of inductive structures like natural numbers

Co quand and Paulin suggest to introduce a second elimination scheme for each inductive struc

ture which allows to build types through structural recursion over say a natural number Let

us illustrate this p oint In system T there exist an elimination scheme rec with the following

corresp onding reduction rules

rec t t  t

S

rec S t t s  t t rec t t t

S S S

The natural type of rec in the Calculus of Constructions is precisely Peanos axiom

n NatP Nat Prop P m NatP m P S m P n

Co quand and Paulins suggestion can b e understo o d as the introduction of a second elimi

nation scheme Rec with the same reduction rules but of the following type

n NatT Nat Type T m NatT m T S m T n

This means we can dene a type ie an ob ject of type Prop recursively over an integer

For instance a predicate trivially veried by and not veried by S could b e

n NatRec n n NatProp P Prop P P m Natq Prop P Prop P

We will call Rec the Large elimination scheme by opp osition to the usual smal l elimination

scheme rec

Of course this is generalized to all inductive types The question we try to address here is

the normalization and hence the consistency of type systems including such features In what

follows we restrict ourselves to the simplest p ossible system including such a feature combined

with p olymorphism

The system

Therefore the calculus dened b elow can b e seen as the system F enriched by

natural numbers a la system T

dep endent types

the essential novelty which is the Rec op erator shown ab ove

In other words it is the type system P with primitive natural numbers and the two elimination

schemes Note that dep endent types are not strictly sp eaking necessary for the denition of the

system but without them types dened using Rec would have no interesting inhabitants

1

This terminology is to our knowledge due to Thorsten Altenkirch

2

Actually all inductive types with only monomorphic constructors also called small inductive types

We should also mention that Jan Smith prop osed to add large elimination over integers to

MartinLofs Type Theory Actually the system he describ es in is quite similar to the one

given b elow so the idea of our normalization pro of should also apply to his extension

The syntax

In order to simplify as much as p ossible the normalization pro of we chose a little more

complicated syntax than the usual GTS style presentations and also than the one of the

few examples ab ove We introduce a syntactic distinction b etween the term variables and the

predicate variables Moreover every predicate variable comes along with its arity or degree

a variable of type Prop will b e of degree a variable of type Nat Prop will b e of degree

etc Consequently the inference rules are more numerous and slightly redundant but the

whole construction of interpretating the predicates in terms on reducibility candidates is more

straightforward

We consider as given a set V t of term variables whose elements will generally b e written as

x and for any natural number i a set V T of predicate variables of degree i which will denote

i

the symbol All these sets are supp osed distinct and the equality over them decidable the

i

S

V T symbol will b e used to designate any element of V T which is dened as

i

iN

We now dene the set of pro ofterms noted as t the sets of predicates of degree i written

T and of kinds of degree i written K

i i

K T

i 0

t j t T j j Sftg j rec ft t tg xt j t t j t x j

i i

T j Nat j x T T j K T j T t j Rec ft T T g

i i

T

0

xT j T t T j

i i i i

K Prop

K x T K

i i

Furthermore we will call objects the elements of the union of the sets dened ab ove The

substitution is dened for all kind of variables in the usual way and noted tx n t or t n T

etc A type is a predicate of degree We will not deal with alphaconversion

Denition We dene the reduction by

T

xt t t x n t

t

K

t T t n T

t

T

xT t T x n t

T

rec f t t g t

S

t

rec fSftg t t g t t rec ft t t g

S S S

tS

Rec f T T g T

T

Rec fSftg T T g T n Recft T T g t

T S

i

We will write M  M to say that M rewrites to M by reduction of a subterm M  M

designing a sequence of i reductions The transitivereexive closure of  will denote the symbol

 and the transitivesymmetricalreexive closure will b e designed by the inx symbol

Remark The reductions preserve the syntactic class So we can sp eak of the arity of an

Lemma The reduction is ChurchRosser in the set of objects

Proof By the usual TaitMartinLof metho d

Denition A context generally written is a list of pairs comp osed either by a term variable

and a type x T or a predicate variable and a kind of the same degree K The empty

i i

context is written

Type system sp ecic rules

t Nat

Nat Nat Prop zero Nat successor

Sftg Nat

t Nat T Nat Prop t T t n Nat T n T Sfng

S

rec

rec ft t t g T t

S

t Nat T Prop Prop T Nat Prop

S

Rec

Rec ft T T g Prop

S

GTS Rules P

x T K Type

Prop Prop Type Kind

x T K Type

T Prop x T T Prop K Type K T Prop

i i i

Prod

x T T K T Prop Prop

i i

T Prop x T K Type

i

x T K Type

i

x T T Prop x T t T

Abs

T

0

xt x T T

x T K Type x T T K

i i i

T

0

xT x T K

i i

K T Prop K t T

i i i i

K

i

t K T

i i i

t x T T t T t K T T K

i i i i

App

t t T x n t t T T n T

i i i

T x T K t T

i i

T t K x n t

i i

T Prop T T T Prop t T

redT

t T

K Type K K K Type T K

redK

T K

V S u U

a V S V t T fProp g V T K fType g

i i

weak

a V u U

and u U t T T K

i i

u U a V in

u U t T T K

i i

var

a V

and a V V t T V T K

i i

Pure pro ofterms

We dene the term algebra by

u x j u u j xu j j Sfug j rec fu u ug

We will call pure terms the elements of The symbols u v u etc will b e used to denote

pure terms

We dene the following map from pro ofterms to

dxe x

T

d xte xdte

dt t e dte dt e

K

d te dte

dt T e dte

d e

dSftge Sfdteg

drec ft t t ge rec fdte dt e dt eg

s S

We may easily map the reduction dened over pro ofterms to reductions over pure terms

We will call N the set of strongly normalizable pure terms

Lemma The reduction is ChurchRosser in the set of pure terms

Proof TaitMartinLof metho d again it is the usual pro of for system T

The reader familiar with normalization pro ofs will understand that we will start by proving

strong normalization for pure terms Hence the pro of b elow has a lot of similarities with the

ones found in There is however a ma jor dierence due to the presence of the large

elimination scheme we cannot get rid of the dep endent types in the pro of Actually the main

originality of our pro of is the way we interpret of the types dened by recursion over integers On

the other hand we should also say that it is p erfectly p ossible to do a similar pro of for dep endent

types without rst proving strong normalization for pure terms for example could very well

b e adapted for our type system So the choice b etween typed or untyped reducibility candidates

is still a matter of convenience and taste

Denition Pure terms of the following forms are said to b e neutral x u u and recfu u u g

S

Denition A predicate interpretation C of degree is a set of pure terms A predicate interpre

tation of degree i is a total function f mapping any pure term to a predicate interpretation

of degree i

Denition An interpretation I is a pair comp osed of

A total function mapping a term to every term variable

A total function mapping a predicate interpretation of degree i to every predicate variables

of degree i for any i

If I f g we will write I x resp I for f x resp g The rst comp onent of

any interpretation straightforwardly denes a substitution over the free variables of any pure

term If u is a pure term we will write uI for the substituted term

We will write I x u resp I C for the interpretation which has the same values

than I on all p oints but x for which it will have value u resp for which it will have value

C Note that all variables are substituted in parallel I x u y u I y u x u

provided that x y A simple but essential prop erty is ux n u I uI x u I Note

also that dtn T eI dteI dteI C

Denition A reducibility candidate of degree is a set of pure terms such that

C is closed under reduction

Every element of C is strongly normalizable

let u b e a neutral pure term If for every term u such that u  u we have u C then

u C Note that a reducibility candidate of degree is never empty since it contains all

the term variables

For n a reducibility candidate of degree n is a predicate interpretation f of degree n

such that for any pure term u f u is a reducibility candidate of degree n such that if

u u then f u f u

Denition Let T b e any predicate of any degree i By structural induction over T we dene

jT j for any interpretation I If i then jT j is a set of pure terms and a total function from

I I

terms to some set otherwise

If T then jT j I

i I i

If T Nat then then jT j N

I

If T x T T then jT j fu u jT j u u jT j g

I I I xu

T

jT j where the intersection ranges over all If T K T then jT j

I C i i I

i i

C

i

reducibility candidates not all interpretations of degree i

If T T t then jT j jT j dteI

i I i I

T

0

xT then jT j is the function that to any term u asso ciates jT j If T

I I xu

If T Rec ft T T g then jT j is dened by cases on the normalizability of dteI

I

If dteI admits no normal form then jT j N

I

If dteI weakly normalizes to u we dene the set C v I T T by structural

recursion over the normal pure term v

C I T T jT j

I

C Sfv g I T T jT j v

I C v I T T

0 0 1 0

C v I T T N otherwise

We then may dene jT j C u I T T

I

Lemma For any x T t and I we have jT x n tj jT j

I I xdteI

Proof By straightforward structural induction over T

If T y T T with x y and y not free in t then T x n t y T x n tT x n t The

induction hypothesis applies for jT x n tj and jT x n tj for any u The result

I I y u

0

follows immediately

If T T t then

i

jT x n tj jT x n t t x n tj

I i I

which by induction hypothesis is equal to

jT j dt eI x dteI jT j dt x n teI

i I xdteI i I xdteI

The result follows

T

0

y T with x y and y not free in t then jT x n tj is the function that to u If T

I

asso ciates jT x n tj which is equal to

I y u

0

jT j jT j

I y u xdteI y u I xdteI y u

0 0 0

If T Rec ft T T g then jT x n tj is dened by cases over the normalizability of

I

dt ex n dteI which is equal to dt eI x dteI The result follows with straightforward

use of the induction hypothesis in the dierent cases

All other cases are immediate

Lemma For any T T and I we have jT n T j jT j

i i i i I I jT j

i i I

3

This is obviously a classical resonning It is p ossible to make this pro of constructive but this would imply to

dene jT j provided some wellchosen conditions We b elieve the classical pro of is simpler and more enlighting

I

4

We recall that the normal form is unique as the reduction is ChurchRosser note that in this pro of we do

need CR for the pure terms but not for the annotated pro of terms

Proof Again we pro ceed by simple structural induction over T We only detail the Rec case

all the other ones are straightforward

If T Rec ft T T g we have seen that dteI dt n T e dte The case where dte

i i

admits no normal form is thus trivial Now for the case where dte do es admit a normal form

we prove by induction over the normal pure term u that

C u I T n T T n T C u I jT j T T

i i i i i i I

Again we do not cop e with conversion thus admitting that is not free in T

If u

C I T n T T n T jT n T j

i i i i i i I

which is equal to

jT j

I jT j

i i I

b ecause of the rst induction hypothesis and by denition equal to

C I jT j T T

i i I

If u Sfu g the second induction states that

C u I T n T T n T C u I jT j T T

i i i i i i I

By denition

C Sfu g I T n T T n T jT n T j

i i i i i i I C u I T nT T nT

0 0 i i 1 i i 0

which b ecause of the equality ab ove is equal to

jT n T j

i i I C u I jT j T T

0 i i I 0 1 0

jT j

I C u I jT j T T jT j

0 i i I 0 1 0 i i

I ; C (u I ; jT j T T )

0 0 1 0

i i

I

But as is not free in T this last term can b e simplied into

jT j

I jT j C u I jT j T T

i i I 0 i i I 0 1 0

Which is precisely the denition of C Sfu g I jT j T T

i i I

The case where u neither reduces to nor to Sfu g is trivial

Denition An predicate interpretation f of degree i is said to b e invariant if for any

u and u such that u u one has f u f u Furthermore if i then f u has to b e

invariant also

An interpretation I is said to b e invariant if and only if for any I is

i i

invariant

Lemma Let I be a invariant interpretation Then the fol lowing holds

For any T of degree at least jT j is invariant

I

Furthermore for any T x u and u such that u u one has jT j jT j

I xu I xu

Proof By structural induction over T

T is immediate

T Nat is immediate

T y T T The second induction hypothesis applies for T and T Therefore

jT j fu u jT j u u jT j g

I xv I xv I xv

fu u jT j u u jT j g

I xv I xv

jT j

I xv

T K T for any reducibility candidate C of degree i I C is invariant

i i i

b ecause C is invariant if i Therefore by induction hypothesis jT j is also

I C

i

invariant The result follows

T T t jT j jT j dteI x u which is equal to jT j by the

i I xu i I xu I xu

induction hypothesis Furthermore if i jT j is invariant b ecause jT j is

I I

T

0

xT is similar T

T Rec ft T T g Because of ChurchRosser for pure terms dteI x v has a

normal form if and only if dteI x v has Furthermore if these normal forms exist

they are equal The result follows by considering the dierent cases of the denition of

jT j

I

Denition An interpretation I is said to b e a candidate interpretation if for any I is a

i i

reducibility candidate of degree i

Lemma For any predicate T and any candidate interpretation I jT j is a reducibility can

I

didate of the same degree than T

Proof Structural induction over T again Most of the cases reect what is done in other

pro ofs of the literature Of course we use the fact that the previous lemma applies as I is

invariant

If T By denition I is a candidate interpretation

i

If T Nat We have to prove that N is indeed a reducibility candidate It is easy to see

that it is closed under reduction and it is of course contained by itself Also a term

that only reduces to strongly normalizable terms is itself strongly normalizable

If T x T T then jT j and jT j are reducibility candidates of degree for any

I I xu

pure term u by induction hypothesis Let u b e an element of jT j and u any element of

I

jT j Then as u u is strongly normalizable so is u Also if u  u then u u  u u

I

thus u u is in jT j and hence u is in jT j

I xu

Finally given any neutral term u that reduces only to elements of jT j we may prove

by induction over the maximum number of reduction steps of u that u u is indeed

element of jT j It is neutral and we show it only reduces to elements of jT j

I xu I xu

u is element of is element of jT j and thus u u but then u u u  u

I

jT j

I xu

u u  u u but the maximum number of reduction steps inside of u is

strictly less than in u So we can apply the induction hypothesis and jT j

I xu

jT j

I xu

For the case T K T we have to prove that any intersection of reducibility

i i

candidates of degree is still a reducibility candidate This is done straightforwardly

The case T T t is a simple application of the induction hypothesis

i

T

0

xT the induction hypothesis says that for any term u jT j is a reducibility If T

i i I xu

candidate of degree i The previous lemma ensures that the function jT j is invariant

I

through conversion of its argument

If T Rec ft T T g

If dteI admits no normal form we saw that N was a reducibility candidate

If dteI normalizes to u we prove by induction over u that the set C u I T T as it

is dened in the denition of jT j is indeed a reducibility candidate

I

if u then jT j is a candidate by induction hypothesis

I

if u Sfu g then C u I T T is a reducibility candidate by induction hypoth

esis Therefore I C u is a candidate interpretation and jT j is a

I C u

0

reducibility candidate

For all other cases we saw that N was a reducibility candidate

Denition Consider a context A candidate interpretation I is said to b e admissible for if

and only if for any x T of one has I x jT j

I

Theorem Consider a context and I an interpretation which is admissible for Then

the fol lowing holds

for any wel lformed judgement t T we have dteI jT j

I

K if T  T for any wel lformed judgement T K and for any judgement T

i i i i

i i

j then jT j jT

i I

i

Proof Now for the ght We pro ceed by structural induction over the derivation of the typing

judgement the dierent cases to consider are each of the typing rules In what follows and if

t resp t t etc is a pro of term then u resp u u etc is the corresp onding substituted

pure term dteI resp dt eI dt eI etc

The rules Nat zero successor are trivial

The rec rule drec ft t t geI is neutral and we show it only reduces to elements of

S

jT tj As in we reason by induction over u u u l u where is the

I S

maximal number of reduction steps in a term and l u the length number of symbols

of the normal form u of u

rec fu u u g may reduce to

S

g where which is element of jT t j jT tj by induction hy u rec fu u

I I

S

p othesis

u if u which is element of jT j by induction hypothesis

I

u u rec fu u u g if u Sfu g

S S

By induction hypothesis we know that

rec fu u u g jT u j

S I

Therefore

u u jT t T Sft gj

S I

and this implies that

u u recfu u u g jT Sft gj jT tj

I I

S S

Formation rule for t t The induction hypothesis ensures that u jT j and u

I

jx T T j Hence by denition of jx T T j and b ecause of the adequacy lemma

I I

we know that u u jT j jT x n t j

I xu I

2

T

0

xt The induction Hyp othesis ensures that for any term u jT j Formation rule for

I

T

0

we have uI x u jT j xteI xu jx T T j To prove that d

I xu I

0

we have to show that given any term u jT j xu u jT j We do so by

I I xu

0

induction over u u The term xu u is neutral it may reduce to

are resp ectively reducts of u and u This term is element where u and u xu u

of jT j b ecause of the last induction hypothesis

I xu

0

ux n u But this is element of jT j as we have seen

I xu

0

K K

i i

teI dteI j K T j t We have to prove that d Formation rule for

i i i I i

Let C b e any reducibility candidate of degree i Then I C is admissible for

i i

K and so u jT j

i i I C

i

Formation rule for t T We have dteI u j K T j and so dt T eI u

I

jT j jT n T j

I jT j I

I

T T

0 0

xT may only reduce to xT Formation rule for

T

0

xT with T  T By induction hypothesis for any u jT j jT j

I xu I xu

The result follows

T T T

0

0 0

xT j xT j j By denition xT with T  T

I I

Formation rule for T t If t  t we know that jT tj jT t j If t  T by

I I

T

0

xT by denition and the induction hypothesis jT tj jT tj Finally if T

I I

adequacy lemma we have jT tj jT x n tj

I I

The Rec rule T Rec ft T T g may reduce to

Rec ft T T g in which case we have already seen that jT j remains unchanged

I

the reduction takes place in a pro ofsubterm

g In which case the induction hypothesis easily T g or Rec ft T T Rec ft T

enables us to prove that jT j remains unchanged by induction over the denition of

I

jT j

I

T if dteI but then we have jT j jT j

I I

T n Rec ft T T g t if dteI Sft g But by induction hypothesis we know

that dteI is strongly normalizable the desired equality follows

The var rule Immediate by denition

The weak rule Any interpretation which is admissible for a V is also valid for

The result follows

The redT rule All we have to check is that if T and T are welltyped and T T then

there is a path from T to T which only go es through welltyped predicates This is true

b ecause sub jectreduction holds and b ecause of the ChurchRosser prop erty

The RedK rule Similar

Strong normalization for erased terms implies strong normal

ization for typed terms

As in we will prove the strong normalization for all the welltyped ob jects using a co ding

But instead of co ding our types as simply typed lambda terms we will co de the welltyped

kinds and predicates as pro ofterms

In what follows o and c are resp ectively a fresh type variable and a fresh term variable

o

We supp ose also that to each predicate variable we may asso ciate a distinct term variable

which we will supp ose has not b een used b efore

Denition We dene the application from kinds to predicates

Prop o

x T K x T K

Denition For any context we dene the context by

o Prop c o

o

x T x T

K K K

We may also dene

T

D c D xD

o xT K K

Prop

which of type K in any context in which K is welltyped

T

C o C xC

xT K K

Prop

which is of type K in any context in which K is welltyped

5

Note that this is the only case where we use the reducibility prop erty for a pro of term inside a predicate

Now to any ob ject M pro ofterm predicate or kind we may asso ciate the following pro of

term M

x x

t t t t

T T o

xt x t T

K K o

t t K

K

t T T t T

rec ft t t g rec ft t t g

S S

T t T t

T T o

T T xT x

o

Recft T T g r ecft T T n og

o T o T

1 1

x T T xT c T

o

K K o

K T T K D C

K K

Prop o

o

K T x T K

t T Lemma If t T then

Proof By structural induction over the typing judgement For induction loading one also

proves that if T K then T K and K o

Lemma If t  t then dte  dt e

Proof By induction over t and b ecause of the facts

dtx n t e dtex n dt e

n dT e dt n T e dte

Theorem Any wel ltyped object is strongly normalizable

Proof The lemma ab ove and theorem imply that any welltyped pro ofterm is strongly

normalizable It is easy to show that this fact also implies the strong normalization of any

welltyped kind or predicate

Some remarks ab out large elimination schemes

Let us try to give some examples of useful or amusing ways to use large elimination schemes

In what follows we do not restrict large elimination schemes to integers We will also use the

notation of the system Co q Not all the examples given b elow can b e run in the currently

distributed version of the system b ecause no large elimination is provided for computational

inductive types at the moment

6

xTt for abstraction and xTT for quantication

Inversion of inductive predicates

In the hitherto developed Co q examples this is probably the most widely used application of

large elimination schemes Actually it is a generalization of the pro of We will simply

give an example taken from the pro of of sorting algorithms The problem is to dene what

it means for a list to b e sorted Lists are dened as usual

Variable ASet

Inductive Set list nil list cons A list list

Given a binary predicate variable over A one denes the sorting prop erty as an inductive

predicate

Variable inf A A Prop

Inductive Definition listLowert aA list Prop

nillow listLowert a nil

conslow bAllistinf a blistLowert a cons b l

Inductive Definition sort list Prop

nilsort sort nil

conssort aAllistsort llistLowert a lsort cons a l

This denition is quite natural The problem is that in practice one often needs prop erties

like

sort cons a llistlowert a l

or similarly

listlowert a cons b linf a b

The p oint is that this is based on the fact that nillow cannot b e used to prove sort a l

ie it implicitly uses the fact that nil and cons are dierent Therefore in order to prove the

prop erties ab ove we dene two new predicates using large elimination which are resp ectively

equivalent de listlowert and sort

Definition listLowert

aAllistProp Match l with

nil True

cons b l bAllistHPropinf a b

Definition sortinv

llistPropMatch l with

nil True

cons a l aAllistHPropsort llistLowert a l

It is easy to prove the equivalences which allows us to get the desired prop erties

sort cons a l is equivalent to sortinv cons a l which reduces to

sort llistlowert a l Similar examples can b e found in

ML dynamics

The original motivation for large elimination schemes was to enhance the system from a logical

p oint of view ie b eing able to prove new prop erties As long as the normalization problem

was op en not very much attention was paid to the p ossibility to use them in the computational

part This example and the ones b elow are meant to show that large elimination schemes allow

to type new interesting programs

It is easy to dene an inductive structure which is trivially isomorphic to the types of simple

typed calculus For example

Inductive Definition MLtype Set

MLnat MLtype

MLarrow MLtype MLtype MLtype

allows us to represent the types of functions and functionals over natural numbers Adding

other base types sums pro ducts etc is of course no problem

The p oint is that the large elimination scheme allows us to build the actual simple type out

of its representation of type MLtype

Definition MLtrad rTMLtype

SetMatch rT with

MLnat nat

MLarrow T T

TMLtypeSSetTMLtypeSSetSS

MLtype Set

The remarkable p oint is that say MLtrad MLarrow MLnat MLnat will actually reduce ie

is syntactically equivalent to the type natnat This is exactly what we need in order to

dene Dynamics like in ML but without any extension of the type system A dynamic is a

pair comp osed of a type representation and an element of the corresp onding type

Inductive Definition MLdyn Set

Dynintro TMLtypeMLtrad TMLdyn

Note that this construction can b e extended in order to represent for instance p olymorphic

system F types and dynamics

Polymorphism

One may notice that in order to dene dynamics in the paragraph ab ove we did not make use

of p olymorphism hence this construction can b e done in a rstorder system On the other

hand the new ability to represent types as rstorder ob jects and then translate them back into

types allows us to dene certain p olymorphic functions The p oint b eing that we can quantify

over type representations

Definition Church aMLtype

MLtrad a

MLtrad aMLtrad a

MLtrad a

Definition Church aMLtypexMLtrad afMLtrad aMLtrad ax

Definition ChurchS nChurch

aMLtype

xMLtrad afMLtrad aMLtrad a

f n a x f

It is worth noting that this type system

is strictly more expressive that ML p olymorphism we can imp ose that the argument of

some function is p olymorphic For instance ChurchS can only b e applied to a p olymorphic

argument

do es not embed system F we cannot represent universally quantied type like T and

hence we cannot apply its representation to some Church integer for instance

Mutually recursive types

The large elimination feature oers a p ossible solution to the problem of mutually recursive

types Again the idea is b est explained through an example The following denition do es not

at rst t into the framework of

expr Num nat expr

closure expr Env expr

and env nil Env

cons term Env Env

We may however dene an inductive family of Sets indexed by b o oleans

Inductive Definition P bool Set

Num nat P true

closure P trueP falseP true

nil P false

cons P trueP falseP false

Env P false expr P true

The p oint is that we may now get the exp ected recursive elimination schemes thanks to large

elimination For example we can prove

QEnvPropQ nil

EEnvQ EtexprQ cons t E

FEnvQ F

Acknowledgements

A lot of the presented material is due to or has b een shown to me by Christine PaulinMohring

I would also like to thank Hugo Herb elin and Thorsten Altenkirch for their insightful remarks

References

M Abadi L Cardelli B Pierce G Plotkin Dynamic Typing in a Statically Typed

Language Conference version in Pro ceedings of POPL Extended version in ACM

Transactions on Programming Languages and Systems vol pp

Th Co quand J Gallier A Pro of of Strong Normalization For the Theory of Construc

tions Using a Kripkelike Interpretation Pro ceedings of the rst BRA workshop on Log

ical Frameworks G Huet and G Plotkin Eds Antibes

Th Co quand Ch PaulinMohring Inductively Dened Types Pro ceedings of COLOG

P MartinLof and G Mints Eds LNCS Tallin

G Dowek A Felty H Herb elin G Huet Ch PaulinMohring B Werner The Co q

Pro of Assistant Users Guide Version INRIA Technical Rep ort

G Huet The Gildbreath Trick A case study in axiomatisation and pro of development

in the Co q pro of assistant INRIA research rep ort

J Gallier On Girards Candidats de Reductibilite Logic and Computer Science P

Odifreddi Ed Academic Press pp London

H Geuvers MJ Nederhof A Mo dular Pro of of Strong Normalization for the Calculus

of Constructions Journal of Functional Programming

JY Girard Interpretation fonctionnelle et elimination des coupures de larithmetique

dordre superieur These dEtat Universite Paris VI I

JY Girard Pro ofs and Types Cambridge University Press

K Godel Ub er eine bisher no ch nicht b en utzte Erweiterung des niten Standpunktes

Reprinted with English translation in the Collected Works vol pp Oxford

University Press Original pap er in Dialectica Vol

JL Krivine Lambdacalcul types et mo deles Masson

Ch PaulinMohring Extraction de Programmes dans le Calcul des Constructions These

de Do ctorat Universite Paris VI I

Ch PaulinMohring B Werner Synthesis of ML programs in the system Co q Submit

ted to the Journal of Symbolic Computation

J Smith Prop ositional Functions and Families of Types Notre Dame Journal of Formal

Logic Vol number