-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththesis.lagda
More file actions
2468 lines (2154 loc) · 109 KB
/
Copy paththesis.lagda
File metadata and controls
2468 lines (2154 loc) · 109 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[
digital, %% This option enables the default options for the
%% digital version of a document. Replace with `printed`
%% to enable the default options for the printed version
%% of a document.
twoside, %% This option enables double-sided typesetting. Use at
%% least 120 g/m² paper to prevent show-through. Replace
%% with `oneside` to use one-sided typesetting; use only
%% if you don’t have access to a double-sided printer,
%% or if one-sided typesetting is a formal requirement
%% at your faculty.
notable, %% This option causes the coloring of tables. Replace
%% with `notable` to restore plain LaTeX tables.
nolof, nolot %% This option prints the List of Figures. Replace with
%% `nolof` to hide the List of Figures.
%% More options are listed in the user guide at
%% <http://mirrors.ctan.org/macros/latex/contrib/fithesis/guide/mu/fi.pdf>.
]{fithesis3}
%%\usepackage{fontspec}
%%\usepackage{yfonts}
%%\usepackage{unicode-math}
%%\usepackage{xunicode}
\usepackage[main=english]{babel}
\usepackage{csquotes}
\thesissetup{
date = \the\year/\the\month/\the\day,
university = mu,
faculty = fi,
type = mgr,
author = {Bc. Adam Krupička},
gender = m,
advisor = {RNDr. Martin Jonáš},
title = {Coinductive Formalization of SECD Machine in Agda},
TeXtitle = {Coinductive Formalization of SECD Machine in Agda},
keywords = {SECD Agda formalization coinduction},
TeXkeywords = {SECD Agda formalization coinduction},
abstract = {We give a formalization of SECD machine in a language called
Agda. We take full advantage of the presence of dependent types in Agda and
define typed assembly code for this machine. Then we give semantics to the typed
assembly by the use of coinduction. Finally, we define a λ calculus and give a
compilation procedure to SECD assembly, using a well-known
approach.},
thanks = {I would like to thank my friends and family for supporting
me throughout this work. You have been instrumental in its completion.
I would also like to thank my supervisor for believing in me and this
topic and for willing to advise me while I worked remotely.
I would also like to thank many users of the Freenode IRC network for
helpful discussions regarding various topics connected to matters contained in
this thesis. This list includes, but is not limited to, Ahmad Salim Al-Sibahi,
Guillaume Allais, Miëtek Bak, Paolo G. Giarrusso, and Andrea Vezzosi.},
bib = bibliography.bib
}
%% \usepackage{makeidx} %% The `makeidx` package contains
%%\makeindex %% helper commands for index typesetting.
%% These additional packages are used within the document:
%%\usepackage{amsmath} %% Mathematics
%%\usepackage{mathtools} %% Mathematics
%%\usepackage{amsthm}
%%\usepackage{amsfonts}
\usepackage[backend=biber]{biblatex}
\usepackage{amssymb}
\usepackage{booktabs}
\usepackage{url} %% Hyperlinks
%%\theoremstyle{definition}
%%\newtheorem{theorem}{Theorem}
%%\newtheorem{definition}{Definition}
%%\newtheorem{notation}{Notation}
\usepackage{agda}
\usepackage{newunicodechar}
\newunicodechar{λ}{\ensuremath{\mathnormal\lambda}}
\newunicodechar{ƛ}{\ensuremath{\mathnormal\lambda}}
\newunicodechar{ι}{\ensuremath{\mathnormal\iota}}
\newunicodechar{τ}{\ensuremath{\mathnormal\tau}}
\newunicodechar{ℕ}{\ensuremath{\mathnormal\mathbb{N}}}
\newunicodechar{ℤ}{\ensuremath{\mathnormal\mathbb{Z}}}
\newunicodechar{↝}{\ensuremath{\mathnormal\leadsto}}
\newunicodechar{ᵈ}{\ensuremath{^d}}
\newunicodechar{ᶜ}{\ensuremath{^c}}
\newunicodechar{★}{\ensuremath{\mathnormal\star}}
\newunicodechar{+}{\ensuremath{\mathnormal+}}
\newcommand{\A}{\AgdaArgument}
\newcommand{\D}{\AgdaDatatype}
\newcommand{\I}{\AgdaInductiveConstructor}
\newcommand{\F}{\AgdaFunction}
\makeatletter
\renewcommand{\@chapapp}{}% Not necessary...
\newenvironment{chapquote}[2][2em]
{\setlength{\@tempdima}{#1}%
\def\chapquote@author{#2}%
\parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
\itshape}
{\par\medskip\normalfont\hfill---\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
\makeatother
\begin{document}
\chapter{Introduction}
\begin{chapquote}{George Orwell, \textit{Homage to Catalonia}}
There are occasions when it pays better to fight and be beaten than not to
fight at all.
\end{chapquote}
Ever since the dawn of functional programming languages, there was a need for an
efficient and practical execution model which would serve as the compilation
target for the high-level functional languages. The first of these was the
SECD machine, introduced by Landin in 1964.
Statically typed languages have many advantages over those lacking in this area.
They give higher assurances to the correctness of the programs therein written,
and they allow for stronger optimizations by the compiler. Perhaps most of all,
however, they give the programmer a solid framework in which to reason about the
code being written.
On the other hand, typed low-level assembly languages are an area that perhaps
has not received much focus: all the current mainstream assembly languages do
not possess a static type system. The compiler generating this low-level code is
trusted to only generate valid programs. This is something we wish to address in
this work by introducing a type system for SECD machine instructions.
Still another direction of interest is that of formalizing programming
languages. The challenges lie especially in formalizing typed languages, as here
we must choose a practical representation of the typed code. Another
consideration is that of giving semantics from within a total language (a
language where every function is provably terminating), such as Agda, to a
language with unlimited recursion. One possible approach is that of using
coinduction, as we show in this work.
In Chapter 2, we give a quick overview of constructivism, Intuitionistic logic,
and type theory.
In Chapter 3, the language Agda is introduced by way of example. We give
considerations especially to the concepts used in the rest of this thesis.
In Chapter 4, we show how the syntax and semantics of typed systems can be
formalized in Agda. We introduce some common machinery and, as an example,
perform a rudimentary formalization of the Simply Typed λ Calculus.
In Chapter 5, we present the formalism of SECD machines. We also introduce an
extension of this formalism used in Chapter 6.
Chapter 6 presents the main matter of this thesis. We formalize typed SECD code
and then proceed to give it semantics by way of an embedding into Agda, using
coinduction. Lastly, we define a high-level λ language and implement compilation
from this into typed SECD code.
\chapter{Logic, Constructivism, Type Theory}
\begin{chapquote}{Richard Feynman}
What I cannot create, I do not understand.
\end{chapquote}
This chapter presents a quick overview of several rather complex areas. However,
the information here presented should be sufficient for understanding the rest
of this thesis.
Previous knowledge of mathematical logic and computability theory would be
helpful in order for the reader to be able to appreciate all of the below
content, however it is not assumed.
\section{Intuitionistic logic}
Intuitionistic logic~\parencite{brouwer1907foundations, brouwer1908unreliability}
is a logic that, unlike most of current mathematics, only allows for
constructive arguments. In practice, the main difference is that proof by
contradiction is not allowed: in order to show that something is the case, it is
not enough to show that the opposite is not the case. In theory, this is
achieved by disallowing the law of the excluded middle (LEM), which states that
for any proposition $P$, $P$ either does or does not hold:
\[
∀P. \; P ∨ ¬P
\]
Certain other well-known classical tautologies, such as double negation
elimination,
\[
∀P. \; ¬¬P → P
\]
are equivalent to this principle. It is also the case that the axiom of
choice, as formulated in set theory, implies the law of the excluded middle, a
result by Diaconescu~\parencite{diaconescu1975axiom}.
Intuitionistic logic began as an attempt by Brouwer to develop a base for all
mathematics that would more closely follow the intuitions of the human mind.
Futhermore, the Stanford Encyclopedia of Philosophy's entry on
Intuitionism~\parencite{sep-logic-intuitionistic} states,
\begin{displayquote}
(…) to Brouwer the general LEM was equivalent to the a priori assumption that
every mathematical problem has a solution — an assumption he rejected,
anticipating Gödel’s incompleteness theorem by a quarter of a century.
\end{displayquote}
In practice, there are considerations with regards to constructive approaches
other than a purely philosophical one. Under the standard
Brouwer-Heyting-Kolmogorov interpretation of the Intuitionistic
logic~\parencite{troelstra2011history}, working in this setting means that every
proposition proven amounts to a recipe, an algorithm, on how to transform the
assumptions, or inputs, into the result, or output. For this reason,
Intuitionistic logic should be of high interest especially to computer scientists.
As an instructive example, consider the normalization of proofs in some theory.
It has been discovered that if one can establish soundness and completeness of
this theory with regard to some suitable semantics, this naturally gives rise to
a normalizer for this theory~\parencite{coquand2002formalised}. In a
constructive setting, the proof of an implication consists of a function, and so
proofs of soundness and completeness give us a way to convert between the
syntactic and semantic world. Reflecting a proof into the semantical structure
(soundness), and reifying from the semantical structure back into syntax
(completeness), we obtain a normalized version of the original proof. This
approach to normalization is commonly referred to as normalization by evaluation
and has been used as early as 1975 by Martin-Löf in order to establish
decidability of type\-checking for his Intuitionistic Theory of (dependent)
Types theory~\parencite{martin1975intuitionistic}, albeit not under the moniker
of normalization by evaluation~\parencite{abel2013normalization}.
\section{Type Theory}
Type theory was first introduced by Russell and Whitehead in 1910 in their
transformational work Principia Mathematica~\parencite{whitehead1912principia} as
a response to Russell's discovery of inconsistency of the naïve set
theory~\parencite{frege1982philosophical} in 1901. In type theory, every
expression has an associated type, and there are rules for the formation of
values and types dependent on these. Compare this with set theory, where
propositions such as $2 ∈ 3$ can be formulated\footnote{The above being, in
fact, true, as per the standard construction of natural numbers in set theory
due to von Neumann~\parencite{von1923introduction}.}.
The next breakthrough in type theory was the discovery of the Simply Typed λ
Calculus~\parencite{church1940formulation} by Church in 1940. This, too, came as a way to
avoid paradoxes present in the Untyped λ Calculus~\parencite{church1932set},
which was found to be inconsistent by Kleene and
Rosser~\parencite{kleene1935inconsistency}. The Untyped λ calculus was introduced
as a universal model of computation, a point at which it succeeded, as it is
equivalent in strength to Turing machines~\parencite{turing1937computability}.
\subsection{Curry-Howard Correspondence}
It was later observed by Howard that the Simply Typed λ Calculus (STLC) could be
viewed as a language for construction of proofs in Natural
Deduction~\parencite{howard1980formulae} (ND), an intuitionistic proof calculus
introduced originally by Gentzen in 1934~\parencite{gentzen1935untersuchungen} as
an attempt at a more natural language for expressing proofs. This correspondence simply
states that \textit{propositions} of ND are isomorphic with \textit{types} in
STLC, \textit{proofs} of ND with \textit{terms} (or programs) of STLC, and
\textit{normalization} of proofs in ND with \textit{conversion into normal form}
of terms of STLC.
This leads to the realization that we can prove theorems by writing computer
programs, and that subsequently we can have these proofs verified by a
type checker. However, in order to be able to express more interesting
properties, we need a type system stronger than STLC.
\subsection{Dependent Types}
In order to extend the expressivity to non-trivial propositions, dependent types
were proposed first by de Bruijn~\parencite{de1967description} in 1967 in his
project Automath, aiming at creating a language for encoding computer verified
mathematics. Later, in 1972, Martin-Löf formulated his Intuitionistic Theory of
Types~\parencite{martin1975intuitionistic}, in which dependent types play a
central role. More recently, starting in the mid 2000's, Voevodsky introduced
Univalent Foundations~\parencite{voevodsky2011univalent}, which aim to give
practical foundations for modern mathematics in a way that allows for
computer-verified proofs.
Dependent types are types which can depend on values. They correspond with
quantifiers from predicate logic, thus allowing one to naturally express more
involved propositions. They are also useful in programming, allowing one to
express very descriptive types, e.g. the type of vectors of fixed length.
The type that corresponds to universal quantification $∀$ is the type of
dependent functions $Π(a : A).B(a)$, where the type of $B$ can depend on the
value $a$. A proof of such a proposition consists of a function which for any
value $a$ produces the proof of $B(a)$. Note that if we choose $B(a) = C$ to be
constant, we obtain the regular function type $A → C$. For example, consider the
statement
\[
Π(n : \mathbb{N}).even(n) ∨ odd(n).
\]
A proof of this proposition would consist of a decision procedure which for
any natural number $n$ determines whether $n$ is even or odd and returns a proof
of this fact.
Corresponding with existential quantification $∃$ is the type of dependent
products $Σ(a:A).B(a)$. A proof would consist of a pair of some value $a$ of
type $A$ and a proof of $B(a)$. Similarly to dependent function, choosing $B(a)
= C$ constant, we obtain the regular (cartesian) product $A×C$. As an example,
consider the statement that there exists a prime number,
\[
Σ(n:\mathbb{N}).prime(n).
\]
One possibility of a proof would be the number $2$ and a proof that $2$ is
prime, which would hopefully be self-evident.
\subsection{Inhabitance}
An important concept is that of inhabitance of some type. An inhabited type is a
type that is non-empty, i.e., there are some values of this type. This is
analogous to the proposition that this type corresponds to a provable
proposition. Thus the values of some type are sometimes called witnesses to
(the provability of) the corresponding proposition.
\chapter{Agda}
\begin{chapquote}{From the topic of the official Agda IRC channel}
Agda: is it a dependently-typed programming language? Is it a proof-assistant
based on intuitionistic type theory?
\verb| ¯\(°_0)/¯| Dunno, lol.
\end{chapquote}
Agda~\parencite{norell2007towards} is a functional programming language with
first-class support for dependent types. As per the Curry-Howard correspondence,
well-typed programs in Agda can also be understood as proofs of inhabitance of
their corresponding types; types being understood as propositions.
This section is meant as a crash-course in Agda syntax, not semantics. In other
words, those not familiar with dependently typed programming languages and/or
proof assistants would do better to follow one of the books published on this
topic. See~\parencite{friedman2018little} for an introduction to dependent types
as a whole, or~\parencite{stump2016verified} for an in-depth introduction to
dependendly typed programming and theorem proving in Agda.
\section{Overview}
Due to the presence of dependent types, functions defined in Agda must be by
default\footnote{This restriction can be lifted, however it is at the user's own
risk.} provably terminating. Failure to do so would result in type-checking
becoming undecidable. However, this does not cause the loss of
Turing-completeness; indeed in section~\ref{coinduction} we present how
possibly non-terminating computations can still be expressed, with some help
from the type system.
Agda has strong support for mixfix operators\footnote{Operators that can have
multiple name parts and are infix, prefix, postfix, or
closed~\parencite{mixfix}.} and Unicode identifiers. This often allows for
developing a notation close to what one has come to expect in mathematics. For
example, the following is valid Agda syntax:
\begin{code}[hide]
kek : Set₁
kek = Set
module HiddenSyntax where
infix 10 _,_
infix 10 _⇒_
postulate
α β Γ : Set
_⊢_ _⇒_ _,_ : Set → Set → Set
\end{code}
\noindent\begin{minipage}[]{\textwidth}\begin{code}
MP : ∀ {Γ α β} → α , Γ ⊢ β
---------
→ Γ ⊢ α ⇒ β
\end{code}\end{minipage}
As an aside, there is also some support for proof automation in
Agda~\parencite{auto}, however from the author's experience, the usability of this
tool is limited to simple cases. In contrast with tools such as
Coq~\parencite{barras1997coq}, Isabelle~\parencite{nipkow2002isabelle}, or
ACL2~\parencite{kaufmann1996acl2}, Agda suffers from a lower degree of
automation: there are no built-in tactics, though their implementation is
possible through reflection~\parencite{agda-manual}.
\subsection{Trivial Types}
A type that is trivially inhabited by a single value is often refered to as
\textit{Top} or \textit{Unit}. In Agda,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
data ⊤ : Set where
⋅ : ⊤
\end{code}\end{minipage}
declares the new data type \AgdaDatatype{⊤} which is itself of type
\AgdaPrimitiveType{Set}\footnote{For the reader familiar with the Haskell type
system, the Agda type $Set$ is akin to the Haskell kind \textit{Star}. Agda has
a stratified hierarchy of universes, where $Set$ itself is of the type $Set_1$, and
so on.}. The second line declares a value constructor for this type, here
called simply \AgdaInductiveConstructor{⋅}, which constructs a value of type
\AgdaDatatype{⊤}\footnote{Again for the Haskell-able, note how the syntax here
resembles that of Haskell with the extension \texttt{GADTs}.}.
The dual of \AgdaDatatype{⊤} is the trivially uninhabited type, often called
\textit{Bottom} or \textit{Empty}. Complete definition in Agda follows.
\noindent\begin{minipage}[]{\textwidth}\begin{code}
data ⊥ : Set where
\end{code}\end{minipage}
Note that there are no constructors declared for this type. Due to the inner
workings of Agda, this guarantees us an inhabited type.
\pagebreak
The empty type also allows us to define the negation of a proposition,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
¬_ : Set → Set
¬ P = P → ⊥
\end{code}\end{minipage}
Here we also see for the first time the notation for mixfix operators. Note the
underscore \texttt{\_} in the name declaration of this function: it symbolizes
where the argument is to be expected.
\subsection{Booleans}
A step-up from the trivially inhabited type \AgdaDatatype{⊤}, the type of
booleans is made up of two distinct values.
\noindent\begin{minipage}[]{\textwidth}\begin{code}
data Bool : Set where
tt ff : Bool
\end{code}\end{minipage}
Since both constructors have the same type signature, we take advantage of a
feature in Agda that allows us to declare such constructors on one line,
together with the shared type.
Now we can declare a function that will perform the negation of Boolean values,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
not : Bool → Bool
not tt = ff
not ff = tt
\end{code}\end{minipage}
Here we utilize pattern matching to split on the argument and transform each
boolean value into the opposite.
Another function we can define is the conjunction of two boolean values, using a
similar approach,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
_∧_ : Bool → Bool → Bool
tt ∧ b = b
ff ∧ _ = ff
\end{code}\end{minipage}
\subsection{Products}
A more interesting type is that of Cartesian products. Here we already need to
parametrize our type by two other types of values in the product.
To define the product type, it is customary to use a record. This will give us
implicit projection functions from the type. The syntax to achieve this follows,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
record _×_ (A : Set) (B : Set) : Set where
constructor _,_
field
proj₁ : A
proj₂ : B
\end{code}\end{minipage}
\begin{code}[hide]
open _×_
infixr 4 _,_
module HiddenProducts where
\end{code}
Here we declare a new record type, parametrized by two other types,
\AgdaArgument{A} and \AgdaArgument{B}. These are the types of the values stored
in the pair, which we construct with the operator
\AgdaInductiveConstructor{\_,\_}.
As an example, we can create a pair of two boolean values,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
_ : Bool × Bool
_ = tt , ff
\end{code}\end{minipage}
Here we see another use of the underscore: we can use it as a placeholder in the
place of an identifier. This is useful in situations where we wish to give some
example we won't be using in the future.
To showcase the use of projections, we can define an uncurried version of
\F{\_∧\_} as a function from products of two boolean values,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
conj : Bool × Bool → Bool
conj r = proj₁ r ∧ proj₂ r
\end{code}\end{minipage}
In practice, however, it can often be less cumbersome to instead employ pattern
matching together with the constructor syntax in order to de-structure a record,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
conj' : Bool × Bool → Bool
conj' (a , b) = a ∧ b
\end{code}\end{minipage}
\subsection{Natural numbers}
To see a more interesting example of a type, let us consider the type of natural numbers. These can be implemented using Peano encoding, as shown below.
\noindent\begin{minipage}[]{\textwidth}\begin{code}[hide]
module Hidden where
\end{code}\end{minipage}
\noindent\begin{minipage}[]{\textwidth}\begin{code}
data ℕ : Set where
zero : ℕ
suc : ℕ → ℕ
\end{code}\end{minipage}
Here we have a nullary constructor for the value zero, and then a unary value
constructor, which corresponds to the successor function. As an example,
consider the number 3, which would be encoded
as~\AgdaInductiveConstructor{suc(suc(suc\ zero))}.
As an example of a function on the naturals, let us define the addition function.
\noindent\begin{minipage}[]{\textwidth}\begin{code}
_+_ : ℕ → ℕ → ℕ
zero + b = b
suc a + b = suc (a + b)
\end{code}\end{minipage}
We proceed by induction on the left argument: if that number is zero, the result
is simply the right argument. If the left argument is a successor of some number
\AgdaArgument{a}, we inductively perform addition of \AgdaArgument{a} to
\AgdaArgument{b}, and then apply the successor function to the result.
\section{Propositional Equality}
In this section, we take a short look at one of the main features of
intuitionistic type theory, namely, the identity type. This type allows us to
state the proposition that two values of some data type are \textit{equal}. The
meaning of \textit{equal} here is that both of the values are convertible to the
same value through reductions. This is the concept of propositional equality.
Compare this with definitional equality, which only allows us to express when
two values have the same syntactic representation. For example, definitionally it
holds that $2=2$, however $1+1=2$ only holds propositionally, because a
reduction is required on the left-hand side.
We can define propositional equality in Agda as follows.
\noindent\begin{minipage}[]{\textwidth}\begin{code}
data _≡_ {A : Set} : A → A → Set where
refl : {x : A} → x ≡ x
\end{code}\end{minipage}
\noindent\begin{minipage}[]{\textwidth}\begin{code}[hide]
open import Relation.Binary.PropositionalEquality using (_≡_; refl)
\end{code}\end{minipage}
The curly braces denote an implicit argument, i.e., an argument that is to be
inferred by the type-checker. The equality type is polymorphic in this
underlying type, \AgdaArgument{A}.
The only way we have to construct values of this type is by the constructor
\AgdaInductiveConstructor{refl}, which says that each value is propositionally
equal to itself. Propositional equality is thus an internalization of
definitional equality as a proposition: we say that two values are
propositionally equal if there is a chain of reductions which lead to
establishing definitional equality between the two values.
Unlike in axiomatic treatments of equivalence, symmetry and transitivity of
\AgdaDatatype{\_≡\_} are theorems in Agda:
\noindent\begin{minipage}[]{\textwidth}\begin{code}
sym : {A : Set} {a b : A} → a ≡ b → b ≡ a
sym refl = refl
trans : {A : Set} {a b c : A} → a ≡ b → b ≡ c → a ≡ c
trans refl refl = refl
\end{code}\end{minipage}
By pattern-matching on the proofs of equality we force Agda to unify the
variables \A{a}, \A{b}, and \A{c}. This is possible because there are no other
conditions on the variables here. In more complex situations, Agda may fail to perform
unification: in such a case we are required to explicitly de-structure the
involved terms until unification can succeed. After all the variables are
unified, we are \textit{de facto} constructing a proof of \A{a} \D{≡} \A{a}, which
we do with the \I{refl} constructor.
Finally, let us see the promised proof of $1+1=2$,
\noindent\begin{minipage}[]{\textwidth}\begin{code}[hide]
module Hidden2 where
open import Data.Nat using (zero; suc; _+_)
\end{code}\end{minipage}
\noindent\begin{minipage}[]{\textwidth}\begin{code}
1+1≡2 : 1 + 1 ≡ 2
1+1≡2 = refl
\end{code}\end{minipage}
The proof is trivial, as $1+1$ reduces directly to two. A more interesting proof
would be that of associativity of addition,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
+-assoc : ∀ {a b c} → a + (b + c) ≡ (a + b) + c
+-assoc {zero} = refl
+-assoc {suc a} = let a+[b+c]≡[a+b]+c = +-assoc {a}
in ≡-cong suc a+[b+c]≡[a+b]+c
\end{code}\end{minipage}
\noindent\begin{minipage}[]{\textwidth}\begin{code}
where ≡-cong : {A B : Set} {a b : A}
→ (f : A → B) → a ≡ b → f a ≡ f b
≡-cong f refl = refl
\end{code}\end{minipage}
Here we proceed by induction on the variable \A{a}, which is given as an
implicit argument: hence in the definition we surround the argument by curly
braces in order to be able to access it. We have no need for the arguments \A{b}
and \A{c}, and as they are implicit as well, we simply do not write them in the
left-hand side of the definition.
In the base case when $a = 0$ we are asked to prove that
\[
0+(b+c)≡(0+b)+c.
\]
By the definition of addition, the left side simplifies to $b+c$. The right side
simplifies to $b+c$ as well, therefore we are permitted to close the case by
\I{refl}.
In the general case we are to prove
\[
suc\ a+(b+c)≡(suc\ a+b)+c.
\]
First we observe how this simplifies according to the definition of addition:
the left side simplifies to $suc\ (a+(b+c))$, whereas the right side first to
$suc\ (a+b)+c$ and then to $suc\ ((a+b)+c)$. Therefore we are to prove that
\[
suc\ (a+(b+c))≡suc\ ((a+b)+c).
\]
To this end we obtain the inductive assumption,
\[
a+(b+c)≡(a+b)+c.
\]
Now all we need is to insert the \I{suc} into this assumption, which we do by a
call to the lemma \F{≡-cong}, which proves that propositional equality is a
congruence with respect to unary functions, such as \I{suc}.
The reader may also notice the use of the quantifier $∀$ in the type of
\F{+-assoc}. This is an instruction to Agda to infer the types of the variables
in the type signature, in this case inferring \A{a}, \A{b}, and \A{c} to be of
the type \D{ℕ}. It does \textit{not} have the meaning of universal
quantification, instead all function types are universally quantified
by default, similarly to e.g. Haskell.
\section{Decidable Equality}
A strengthening of the concept of propositional equality is that of
\textit{decidable equality}. This is a form of equality that, unlike
Propositional equality, can be decided programatically. We define this equality
as a restriction of propositional equality to those comparisons that are
decidable. Firstly, we need the definition of a decidable relation.
\noindent\begin{minipage}[]{\textwidth}\begin{code}
data Dec (R : Set) : Set where
yes : R → Dec R
no : ¬ R → Dec R
\end{code}\end{minipage}
This data type allows us to embed either a \I{yes} or a \I{no} answer as to
whether \A{R} is inhabited. For example, we can state that the type \D{⊤} is
inhabited by producing the witness \I{⋅},
\noindent\begin{minipage}[]{\textwidth}\begin{code}[hide]
module HiddenDec where
\end{code}\end{minipage}
\noindent\begin{minipage}[]{\textwidth}\begin{code}
_ : Dec ⊤
_ = yes ⋅
\end{code}\end{minipage}
and that the type \D{⊥} is not,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
_ : Dec ⊥
_ = no λ()
\end{code}\end{minipage}
by using the absurd lambda, $λ()$. The constructor \I{no} takes a value
of type \F{¬}\D{⊥}, which stands for \D{⊥} → \D{⊥}. Since the left-hand side is
absurd, Agda allows us to conclude anything, even \D{⊥}, by this syntax.
Now we can define what it means for a type to possess decidable equality,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
Decidable : (A : Set) → Set
Decidable A = ∀ (a b : A) → Dec (a ≡ b)
\end{code}\end{minipage}
Here we specify that for any two values of that type we must be able to produce
an answer whether they are equal or not.
As an example, let us define decidable equality for the type of Naturals. We
also use this as an excuse to introduce the keyword \AgdaKeyword{with} which can
be used to make a case-split on some expression,
\noindent\begin{minipage}[]{\textwidth}\begin{code}[hide]
open import Data.Nat using (ℕ; zero; suc)
\end{code}\end{minipage}
\noindent\begin{minipage}[]{\textwidth}\begin{code}
_≟ℕ_ : Decidable ℕ
zero ≟ℕ zero = yes refl
(suc _) ≟ℕ zero = no λ()
zero ≟ℕ (suc _) = no λ()
(suc m) ≟ℕ (suc n) with m ≟ℕ n
… | yes refl = yes refl
… | no ¬m≡n = no λ m≡n → ¬m≡n (suc-injective m≡n)
where suc-injective : ∀ {m n} → suc m ≡ suc n → m ≡ n
suc-injective refl = refl
\end{code}\end{minipage}
Given a proof of equality of two values of a decidable type, we can forget all
about the proof and simply ask whether the two values are equal or not,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
⌊_⌋ : {A : Set} {a b : A} → Dec (a ≡ b) → Bool
⌊ yes p ⌋ = tt
⌊ no ¬p ⌋ = ff
\end{code}\end{minipage}
\noindent\begin{minipage}[]{\textwidth}\begin{code}[hide]
open import Data.Integer using (ℤ)
open import Data.Integer.Properties renaming (_≟_ to _≟ℤ'_)
open import Data.List using (List; []; [_]; _∷_; null; all; length)
import Relation.Nullary as N
import Data.Empty as E
_≟B_ : Decidable Bool
tt ≟B tt = yes refl
ff ≟B ff = yes refl
tt ≟B ff = no λ()
ff ≟B tt = no λ()
_≟ℤ_ : Decidable ℤ
a ≟ℤ b with a ≟ℤ' b
… | N.yes refl = yes refl
… | N.no ¬p = no λ x → ⊥⊥ (¬p x)
where ⊥⊥ : E.⊥ → ⊥
⊥⊥ ()
\end{code}\end{minipage}
\section{Coinduction}
\label{coinduction}
Total languages, such as Agda, are sometimes wrongfully accused of lacking
Turing-completeness. By a total language is meant a language in which every
function terminates. Since it is well-known that the problem of termination is
undecidable in general, in actuality we are limited to languages in which every
function is not only total, but provably so.
In reality, there are ways to model possibly non-terminating programs — given
some time limit for their execution. One such way is to introduce a monad that
captures the concept of a recursive call~\parencite{mcbride2015turing}.
In this section we introduce the concept of coinduction on the example of
streams and then proceed to define a monad that will be used later on in
chapter 5 to give semantics to the execution of SECD machine code.
For a more in-depth overview of coinduction in Agda and especially the
aforementioned monad, please refer to~\parencite{coinduction}.
The concepts presented can be made precise in Category Theory, where given a
functor $F$ we can speak of $F-$coalgebras. Coinduction, then, is a way of
proving properties of such systems. Morally, the distinction between induction
and coinduction is that induction proceeds by breaking down a problem into some
base case, whereas coinduction starts with a base case and iteratively extends
to subsequent steps.
Well-known examples of $F-$coalgebras include streams and transition systems.
The moral distinction here is that while elements of algebraic structures, or
data, are constructed, elements of coalgebraic structures, or codata, are
observed.
For a more in-depth introduction to coalgebra, please
see~\parencite{jacobs_2016}.
\subsection{Streams}
Streams are infinite lists. For example, consider the succession of all natural
numbers: it is clearly infinite. In some functional languages, such as Haskell,
this can be expressed as a lazily constructed list. Agda, however, being total,
does not allow for such a construction directly: an infinite data structure is
clearly not inductively constructible. It is, however, observable: as with a
regular list, we can peek at its head \AgdaField{hd}, and we can drop the head
and look at the tail \AgdaField{tl} of the stream.
To capture this in Agda, we define a record with these projections and mark it
as \AgdaKeyword{coinductive},
\noindent\begin{minipage}[]{\textwidth}\begin{code}[hide]
open import Size
open import Data.Maybe using (Maybe; just; nothing)
\end{code}\end{minipage}
\noindent\begin{minipage}[]{\textwidth}\begin{code}
record Stream (A : Set) : Set where
coinductive
field
hd : A
tl : Stream A
\end{code}\end{minipage}
\noindent\begin{minipage}[]{\textwidth}\begin{code}[hide]
open Stream
module HiddenX where
open import Data.Nat using (⌊_/2⌋; _+_; _*_)
open import Data.Sum using (inj₁; inj₂) renaming (_⊎_ to _∨_)
open import Data.Product using (Σ) renaming (_,_ to _⹁_)
even? : ℕ → Bool
even? zero = tt
even? (suc zero) = ff
even? (suc (suc n)) = even? n
mapˢ : ∀ {A B} → (A → B) → Stream A → Stream B
hd (mapˢ f as) = f (hd as)
tl (mapˢ f as) = mapˢ f (tl as)
atˢ : ∀ {A} → ℕ → Stream A → A
atˢ zero xs = hd xs
atˢ (suc n) xs = atˢ n (tl xs)
\end{code}\end{minipage}
As an example, consider the aforementioned stream of natural numbers, starting
from some \A{n},
\noindent\begin{minipage}[]{\textwidth}\begin{code}
nats : ℕ → Stream ℕ
hd (nats n) = n
tl (nats n) = nats (n + 1)
\end{code}\end{minipage}
Here we employ a feature of Agda called copatterns. Recall that we are
constructing a record: the above syntax says how the individual fields are
to be realized. Note also that the argument to \F{nats} is allowed to be
structurally enlarged before the recursive call, something that would be
forbidden in an inductive definition.
Given such a stream, we may wish to observe it by peeking forward a finite
number of times, thus producing a \D{List},
\noindent\begin{minipage}[]{\textwidth}\begin{code}
takeˢ : ∀ {A} → ℕ → Stream A → List A
takeˢ zero xs = []
takeˢ (suc n) xs = hd xs ∷ takeˢ n (tl xs)
\end{code}\end{minipage}
Now we can convince ourselves that the above implementation of \F{nats} is,
indeed, correct,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
_ : takeˢ 7 (nats 0) ≡ 0 ∷ 1 ∷ 2 ∷ 3 ∷ 4 ∷ 5 ∷ 6 ∷ []
_ = refl
\end{code}\end{minipage}
For a more interesting example of a stream, consider the Hailstone
sequence~\parencite{crandall19783}, with a slight modification to the single
step function, given next.
\noindent\begin{minipage}[]{\textwidth}\begin{code}
step : ℕ → ℕ
step 1 = 0
step n with even? n
… | tt = ⌊ n /2⌋
… | ff = 3 * n + 1
\end{code}\end{minipage}
The sequence itself, then, can be given by the following definition,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
collatz : ℕ → Stream ℕ
hd (collatz n) = n
tl (collatz n) = collatz (step n)
\end{code}\end{minipage}
For example, observe the sequence starting from the number $12$,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
_ : takeˢ 11 (collatz 12)
≡ 12 ∷ 6 ∷ 3 ∷ 10 ∷ 5 ∷ 16 ∷ 8 ∷ 4 ∷ 2 ∷ 1 ∷ 0 ∷ []
_ = refl
\end{code}\end{minipage}
As an aside, using a dependent product, we can express the predicate that a
stream will eventually reach some given value,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
Reaches : ∀ {A} → Stream A → A → Set
Reaches xs a = Σ ℕ (λ n → atˢ n xs ≡ a)
\end{code}\end{minipage}
Here the binary function \F{atˢ} is used, which returns the $n$-th element of
the stream \A{xs}.
Hence, the Collatz conjecture can be stated as follows:
\noindent\begin{minipage}[]{\textwidth}\begin{code}[hide]
postulate
\end{code}\end{minipage}
\noindent\begin{minipage}[]{\textwidth}\begin{code}
conjecture : ∀ n → Reaches (collatz n) 0
\end{code}\end{minipage}
\subsection{The Delay Monad}
The Delay monad captures the concept of unbounded recursive calls. There are two
ways to construct a value of this type: \I{now}, which says that execution has
terminated and the result is available, and \I{later}, which means the result is
delayed by some indirection and \textit{might} be available later. In Agda, we
define this as a mutual definition of an inductive and coinductive data-type as
follows,
\label{delay_monad}
\noindent\begin{minipage}[]{\textwidth}\begin{code}
mutual
data Delay (A : Set) (i : Size) : Set where
now : A → Delay A i
later : ∞Delay A i → Delay A i
record ∞Delay (A : Set) (i : Size) : Set where
coinductive
field
force : {j : Size< i} → Delay A j
\end{code}\end{minipage}
Here we use the built-in type \D{Size} which serves as a measure on the size
of the delay. Note that the field \AgdaField{force} requires this to strictly
decrease. This measure aids the Agda type-checker in verifying that a definition
is \textit{productive}, that is, some progress is made in each iteration
of \AgdaField{force}. The type \D{Size<} \A{i} is the type of all sizes
strictly smaller than \A{i}.
For any data-type we may define an infinitely delayed value,
\noindent\begin{minipage}[]{\textwidth}\begin{code}[hide]
open ∞Delay public
\end{code}\end{minipage}
\noindent\begin{minipage}[]{\textwidth}\begin{code}
never : ∀ {i A} → Delay A i
never {i} = later λ where .force {j} → never {j}
\end{code}\end{minipage}
This can be used to signal an error in execution has occurred. The implicit size
argument has been written explicitly for the reader's sake.
Here we also see for the first time the anonymous syntax for constructing
records by copatterns. The above is synonymous with
\noindent\begin{minipage}[]{\textwidth}\begin{code}
mutual
never' : ∀ {i A} → Delay A i
never' = later ∞never'
∞never' : ∀ {i A} → ∞Delay A i
force ∞never' = never'
\end{code}\end{minipage}
In other words, anonymous records allow us to succinctly construct codata by use
of copatterns, without the need of writing unwieldy mutual blocks.
Given a delayed value, we can attempt to retrieve it in a given finite number of
steps,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
runFor : ∀ {A} → ℕ → Delay A ∞ → Maybe A
runFor zero (now x) = just x
runFor zero (later _) = nothing
runFor (suc _) (now x) = just x
runFor (suc n) (later x) = runFor n (force x)
\end{code}\end{minipage}
This idiom is useful for executing a computation that periodically offers
its environment a chance to interrupt the computation, or proceed further on.
\D{Delay} is also a monad, with the unit operator\footnote{In Haskell
terminology, \textit{return}.} being \I{now} and the bind
operator given below,
\noindent\begin{minipage}[]{\textwidth}\begin{code}
_>>=_ : ∀ {A B i} → Delay A i → (A → Delay B i) → Delay B i
now x >>= f = f x
later x >>= f = later λ where .force → (force x) >>= f
\end{code}\end{minipage}
This allows us to chain delayed computations where one depends on the result of
another.
\noindent\begin{minipage}[]{\textwidth}\begin{code}[hide]
open import Data.Integer using (+_; _+_; _-_; _*_)
\end{code}\end{minipage}
\chapter{Formalizing Type Systems}
\begin{chapquote}{Philip Wadler}
λ calculus isn't invented, it's discovered.
\end{chapquote}
In what follows, we take a look at how we can use Agda to formalize
deductive systems and/or typed calculi. We concern ourselves with the
simplest example there is, the Simply Typed λ Calculus.
Deductive systems are formal languages which allow the statement and proof of
propositions in a manner that makes the conclusions indisputable, as long as one
can agree on assumptions used in the proof and laws of reason encompassed by the
system.
For a more in-depth treatment of the topic of formalizing programming languages
and programming language theory in Agda, please refer
to~\parencite{wadler2018programming}.
λ calculi are arguably the simplest model of computation. They almost invariably
contain the basic concepts, which are variables, function formation, and
function application. They come in many forms and can be adapted to model any
specific requirements we may have, e.g. resource-conscious linear
calculi~\parencite{girard1987linear}, concurrency-oriented process
calculi~\parencite{boudol1989towards}, or calculi modeling quantum
computing~\parencite{van2004lambda}.
For a brief history of λ calculi, please refer to chapter 2.
\section{De Bruijn Indices}
Firstly, we shall need some machinery to make our lives easier. We could use
string literals as variable names in our system, however this would lead to
certain difficulties further on, such as increased complexity of the
formalization due to the need to handle string comparisons and such. Instead, we
shall use the concept commonly referred to as De Bruijn
indices~\parencite{de1972lambda}. In this formalism variable identifiers consist
of natural numbers, where each number $n$ refers to the variable bound by the
binder $n$ positions above the current scope in the syntax tree. Some
examples of this naming scheme are shown in Figure~\ref{debruijn}.
\begin{figure}[h]
\centering
\begin{tabular}{l|l}
\multicolumn{1}{c}{String syntax} & \multicolumn{1}{c}{De Bruijn syntax} \\
\midrule
\verb|λx.x| & \verb|λ 0| \\
\verb|λx.λy.x| & \verb|λλ 1| \\
\verb|λx.λy.λz.x z (y z)| & \verb|λλλ 2 0 (1 0)| \\
\end{tabular}
\caption{Examples of λ terms using the standard naming scheme on the left and
using De Bruijn indices on the right.}
\label{debruijn}
\end{figure}
The immediately apparent advantage of using De Bruijn indices is that
α-equivalence\footnote{The problem of whether two λ terms represent the same
function.} of λ terms becomes trivially decidable by way of purely syntactic
equality. Other advantages include easier formalization.
\subsection{Implementation}
To implement De Bruijn indices in Agda, we express what it means for a variable
to be present in a context. Context is a collection of assumptions we are
equipped with in a given situation. We shall assume that a context is a list of
assumptions, as this is how contexts will be defined in the next subsection. We
will express list membership as a new data type,