100% found this document useful (6 votes)
30 views156 pages

(Ebook) Mathematical Logic Through Python by Yannai A. Gonczarowski, Noam Nisan ISBN 9781108949477, 1108949479 Online PDF

Scholarly document: (Ebook) Mathematical Logic through Python by Yannai A. Gonczarowski, Noam Nisan ISBN 9781108949477, 1108949479 Instant availability. Combines theoretical knowledge and applied understanding in a well-organized educational format.

Uploaded by

ullaelis8640
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (6 votes)
30 views156 pages

(Ebook) Mathematical Logic Through Python by Yannai A. Gonczarowski, Noam Nisan ISBN 9781108949477, 1108949479 Online PDF

Scholarly document: (Ebook) Mathematical Logic through Python by Yannai A. Gonczarowski, Noam Nisan ISBN 9781108949477, 1108949479 Instant availability. Combines theoretical knowledge and applied understanding in a well-organized educational format.

Uploaded by

ullaelis8640
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 156

(Ebook) Mathematical Logic through Python by Yannai

A. Gonczarowski, Noam Nisan ISBN 9781108949477,


1108949479 Pdf Download

https://ebooknice.com/product/mathematical-logic-through-
python-58342592

★★★★★
4.8 out of 5.0 (44 reviews )

Instant PDF Download

ebooknice.com
(Ebook) Mathematical Logic through Python by Yannai A.
Gonczarowski, Noam Nisan ISBN 9781108949477, 1108949479 Pdf
Download

EBOOK

Available Formats

■ PDF eBook Study Guide Ebook

EXCLUSIVE 2025 EDUCATIONAL COLLECTION - LIMITED TIME

INSTANT DOWNLOAD VIEW LIBRARY


We have selected some products that you may be interested in
Click the link to download now or visit ebooknice.com
for more options!.

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason; Viles,


James ISBN 9781459699816, 9781743365571, 9781925268492,
1459699815, 1743365578, 1925268497

https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena Alfredsson, Hans


Heikne, Sanna Bodemyr ISBN 9789127456600, 9127456609

https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT II


Success) by Peterson's ISBN 9780768906677, 0768906679

https://ebooknice.com/product/sat-ii-success-math-1c-and-2c-2002-peterson-
s-sat-ii-success-1722018

(Ebook) The Elements of Computing Systems : Building a Modern


Computer from First Principles by Noam Nisan, Shimon Schocken
ISBN 9780262539807, 9782020002677, 0262539802, 2020002671

https://ebooknice.com/product/the-elements-of-computing-systems-building-a-
modern-computer-from-first-principles-30207114
(Ebook) Master SAT II Math 1c and 2c 4th ed (Arco Master the SAT
Subject Test: Math Levels 1 & 2) by Arco ISBN 9780768923049,
0768923042

https://ebooknice.com/product/master-sat-ii-math-1c-and-2c-4th-ed-arco-
master-the-sat-subject-test-math-levels-1-2-2326094

(Ebook) Cambridge IGCSE and O Level History Workbook 2C - Depth


Study: the United States, 1919-41 2nd Edition by Benjamin
Harrison ISBN 9781398375147, 9781398375048, 1398375144,
1398375047
https://ebooknice.com/product/cambridge-igcse-and-o-level-history-
workbook-2c-depth-study-the-united-states-1919-41-2nd-edition-53538044

(Ebook) A Beginner's Guide to Mathematical Logic by Raymond M.


Smullyan ISBN 9780486492377, 0486492370

https://ebooknice.com/product/a-beginner-s-guide-to-mathematical-
logic-36441034

(Ebook) Mathematical Logic by George Tourlakis ISBN


9780470280744, 0470280743

https://ebooknice.com/product/mathematical-logic-2215042

(Ebook) A Beginner’s Further Guide to Mathematical Logic by


Raymond M. Smullyan ISBN 9789814725729, 9814725722

https://ebooknice.com/product/a-beginners-further-guide-to-mathematical-
logic-6772236
Mathematical Logic through Python

Using a unique pedagogical approach, this text introduces mathematical logic by guiding
students in implementing the underlying logical concepts and mathematical proofs via
Python programming. This approach, tailored to the unique intuitions and strengths of
the ever-growing population of programming-savvy students, brings mathematical logic
into the comfort zone of these students and provides clarity that can only be achieved
by a deep hands-on understanding and the satisfaction of having created working code.
While the approach is unique, the text follows the same set of topics typically covered in a
one-semester undergraduate course, including propositional logic and first-order predicate
logic, culminating in a proof of Gödel’s completeness theorem. A sneak peek to Gödel’s
incompleteness theorem is also provided. The textbook is accompanied by an extensive
collection of programming tasks, code skeletons, and unit tests. Familiarity with proofs
and basic proficiency in Python is assumed.

Yannai A. Gonczarowski is Assistant Professor of both Economics and Computer Science


at Harvard University, and is the first faculty at Harvard to be appointed to both of these
departments. He received his PhD in Mathematics and Computer Science from The Hebrew
University of Jerusalem. Among his research awards are the ACM SIGecom Dissertation
Award and INFORMS AMD Junior Researcher Paper Prize. He is also a professionally
trained opera singer.

Noam Nisan is Professor of Computer Science and Engineering at The Hebrew University
of Jerusalem, serving as Dean of the School of Computer Science and Engineering during
2018–2021. He received his PhD in Computer Science from the University of California,
Berkeley. Among the awards for his research on computational complexity and algorithmic
game theory are the Gödel Prize and Knuth Award. This is his fifth book.

Published online by Cambridge University Press


Mathematical Logic
through Python
YA N N A I A . G O N C Z A R O W S K I
Harvard University

NOAM NISAN
Hebrew University of Jerusalem

Published online by Cambridge University Press


University Printing House, Cambridge CB2 8BS, United Kingdom
One Liberty Plaza, 20th Floor, New York, NY 10006, USA
477 Williamstown Road, Port Melbourne, VIC 3207, Australia
314–321, 3rd Floor, Plot 3, Splendor Forum, Jasola District Centre, New Delhi – 110025, India
103 Penang Road, #05–06/07, Visioncrest Commercial, Singapore 238467

Cambridge University Press is part of the University of Cambridge.


It furthers the University’s mission by disseminating knowledge in the pursuit of
education, learning, and research at the highest international levels of excellence.

www.cambridge.org
Information on this title: www.cambridge.org/9781108845076
DOI: 10.1017/9781108954464
© Yannai A. Gonczarowski and Noam Nisan 2022
This publication is in copyright. Subject to statutory exception
and to the provisions of relevant collective licensing agreements,
no reproduction of any part may take place without the written
permission of Cambridge University Press.
First published 2022
Printed in the United Kingdom by TJ Books Limited, Padstow Cornwall
A catalogue record for this publication is available from the British Library.
Library of Congress Cataloging-in-Publication Data
Names: Gonczarowski, Yannai A., 1981- author. | Nisan, Noam, author.
Title: Mathematical logic through Python / Yannai A. Gonczarowski, Harvard
University, Massachusetts, Noam Nisan, Hebrew University of Jerusalem.
Description: Cambridge, United Kingdom ; New York, NY : Cambridge
University Press, [2022] | Includes index.
Identifiers: LCCN 2021057959 (print) | LCCN 2021057960 (ebook) |
ISBN 9781108845076 (hardback) | ISBN 9781108949477 (paperback) |
ISBN 9781108954464 (epub)
Subjects: LCSH: Logic, Symbolic and mathematical. | Python (Computer
program language) | BISAC: COMPUTERS / Languages / General
Classification: LCC QA9 .G64 2022 (print) | LCC QA9 (ebook) |
DDC 005.13/1–dc23/eng/20220125
LC record available at https://lccn.loc.gov/2021057959
LC ebook record available at https://lccn.loc.gov/2021057960
ISBN 978-1-108-84507-6 Hardback
ISBN 978-1-108-94947-7 Paperback
Cambridge University Press has no responsibility for the persistence or accuracy
of URLs for external or third-party internet websites referred to in this publication
and does not guarantee that any content on such websites is, or will remain,
accurate or appropriate.

Published online by Cambridge University Press


To Eshed, whose syntax and semantics logically evolved while this book did
Y.A.G.

To Michal, logically and illogically


N.N.

Published online by Cambridge University Press


Published online by Cambridge University Press
Contents

Preface page xi

0 Introduction and Overview 1


0.1 Our Final Destination: Gödel’s Completeness Theorem 2
0.2 Our Pedagogical Approach 4
0.3 How We Travel: Programs That Handle Logic 5
0.4 Our Roadmap 8

Part I Propositional Logic

1 Propositional Logic Syntax 13


1.1 Propositional Formulas 13
1.2 Parsing 18
1.3 Infinite Sets of Formulas 21
1.A Optional Reading: Polish Notations 22

2 Propositional Logic Semantics 24


2.1 Detour: Semantics of Programming Languages 24
2.2 Models and Truth Values 25
2.3 Truth Tables 28
2.4 Tautologies, Contradictions, and Satisfiability 30
2.5 Synthesis of Formulas 31
2.A Optional Reading: Conjunctive Normal Form 33
2.B Optional Reading: Satisfiability and Search Problems 35

3 Logical Operators 41
3.1 More Operators 41
3.2 Substitutions 43
3.3 Complete Sets of Operators 46
3.4 Proving Incompleteness 49

4 Proof by Deduction 53
4.1 Inference Rules 53
4.2 Specializations of an Inference Rule 56
4.3 Deductive Proofs 59

vii

Published online by Cambridge University Press


viii Contents

4.4 Practice Proving 64


4.5 The Soundness Theorem 66

5 Working with Proofs 69


5.1 Using Lemmas 69
5.2 Modus Ponens 73
5.3 The Deduction Theorem 76
5.4 Proofs by Way of Contradiction 79

6 The Tautology Theorem and the Completeness of Propositional Logic 84


6.1 Our Axiomatic System 84
6.2 The Tautology Theorem 86
6.3 The Completeness Theorem for Finite Sets 92
6.4 The Compactness Theorem and the Completeness Theorem for Infinite Sets 94
6.A Optional Reading: Adding Additional Operators 97
6.B Optional Reading: Other Axiomatic Systems 101

Part II Predicate Logic

7 Predicate Logic Syntax and Semantics 109


7.1 Syntax 110
7.2 Semantics 121

8 Getting Rid of Functions and Equality 129


8.1 Getting Rid of Functions 129
8.2 Getting Rid of Equality 138

9 Deductive Proofs of Predicate Logic Formulas 143


9.1 Example of a Proof 144
9.2 Schemas 145
9.3 Proofs 160
9.4 Getting Rid of Tautology Lines 171

10 Working with Predicate Logic Proofs 178


10.1 Our Axiomatic System 178
10.2 Syllogisms 184
10.3 Some Mathematics 195

11 The Deduction Theorem and Prenex Normal Form 211


11.1 The Deduction Theorem 211
11.2 Prenex Normal Form 215

12 The Completeness Theorem 231


12.1 Deriving a Model or a Contradiction for a Closed Set 236
12.2 Closing a Set 240

Published online by Cambridge University Press


Contents ix

12.3 The Completeness Theorem 252


12.4 The Compactness Theorem and the “Provability” Version of the
Completeness Theorem 253

13 Sneak Peek at Mathematical Logic II: Gödel’s Incompleteness Theorem 256


13.1 Complete and Incomplete Theories 256
13.2 Gödel Numbering 258
13.3 Undecidability of the Halting Problem 260
13.4 The Incompleteness Theorem 262

Cheatsheet: Axioms and Axiomatic Inference Rules Used in This Book 266

Index 268

Published online by Cambridge University Press


Published online by Cambridge University Press
Preface

Mathematical Logic 101 is a beautiful course. Gödel’s Theorems are arguably the most
profound and deep truths taught throughout the entire undergrad theoretical curriculum.
Nonetheless, it seems that among many computer science and engineering students this
course suffers from the reputation of being an unintelligible course full of technical, unin-
sightful proofs. Students lose themselves in endless inductions and do not fully understand
what it means, e.g., to “prove that anything that is true can be proven.” Indeed, how can this
not be confusing when the two occurrences of “prove” in that sentence have two distinct
meanings – the latter referring to a precise very strict mathematical “proof” object that is
defined during this course, while the former refers to the free-text proofs that we have been
taught since our first year of undergrad? This book drastically reenvisions the Mathematical
Logic 101 course, conveying the same material but tapping into the strengths of the ever-
growing cohort of programming-oriented students to do so.
How does one help programming-oriented students to not lose themselves among end-
less little details in proofs, failing to see the overarching message of the course? We
set out to make this course less abstract, more intuitive, and maybe even exciting, by
tapping into the context where such students are used to comfortably dealing with endless
little details on the way to a larger goal without ever missing the forest for the trees:
computer programming. We redesigned the entirety of this very theoretical course from
scratch to be based upon a series of programming exercises, each corresponding to either a
theorem/lemma/corollary or a step toward such.
For example, the main result of the first half of a standard Mathematical Logic 101 course
is the “Tautology Theorem” (a variant of the Completeness Theorem for propositional
logic), which asserts that every tautology – every statement that holds in every possible
model or setting – can be proven to hold using a small set of axioms. The corresponding
programming exercise in this book is to write a function (based on functions from previous
exercises, of course) whose input is a formula (an object of class Formula, which the
students implement in a previous exercise) and whose output is either a model in which
this formula does not hold (i.e., a counterexample to the formula being a tautology) or a
proof (an object of class Proof, which the students implement in a previous exercise) of
this formula. Obviously, whoever can write such a function, including all its recursively
implemented helper functions, completely understands the reasoning in the proof of the
Tautology Theorem, including all its inductively proven lemmas. (And this holds even
more so for students who naturally grasp recursive code far better than they do inductive
proofs.) In our experience, students with a background in programming for the most part
even understand this proof better having actively coded its functionality themselves than

xi

https://doi.org/10.1017/9781108954464.001 Published online by Cambridge University Press


xii Preface

had they only passively seen the proof being written on the blackboard by a teacher. In
the process of moving from proving to programming, we have in fact also disambiguated
the two meanings of “prove” in the earlier statement of “prove that whatever is true can
be proven”: we transformed the former “prove” into “program in code” and the latter “can
be proven” into “is the conclusion of a valid Proof object.” This disambiguation by way
of defamiliarization of each of these occurrences of “prove” achieves great clarity and
furthermore allows the students to more easily reexamine their intuitions and unconscious
assumptions about proofs.
This book evolved from a course that we have been teaching at the Hebrew University of
Jerusalem since 2017, first as an elective (we limited our class to 50 and then to 100 students
as we fine-tuned the course, and there had been a waiting list) and later as an alternative
for computer science and engineering students to the mandatory Mathematical Logic 101,
to the clear satisfaction of the students, who continuously rank this course highly. In our
experience, having the tasks of a single chapter due each week (if the schedule permits,
then we try to allow an additional week for Chapter 10), with the tasks of Part I (Chapters 1
through 6) being solved by each student individually and the tasks of Part II (Chapters 7
through 12) being solved in pairs, has consistently proven to work well.
We are grateful to the Hebrew University students who took our course for their valuable
questions and comments, and to our earlier students also for the faith they have put in us.
We are indebted to our first TA and beta-solver, Alon Ziv, as well as to our subsequent TAs
Noam Wies, Asaf Yehudai, Ofer Ravid, and Elazar Cohen, and beta-solvers Omri Cohen
and Matan Harsat. A special thanks goes to Chagit Schiff-Blass, at the time a Law and
Cognitive Science student, who showed us that our way of teaching Mathematical Logic
really does appeal to an even more diverse student population than we had imagined, by first
being an excellent beta-solver and then joining our teaching team. We thank Henry Cohn
for valuable advice, and thank Aviv Keren and Shimon Schocken for their valuable detailed
feedback on portions of earlier drafts of this book. We especially thank David Kashtan
for careful and valuable scientific editing of this book on the logic side; any deviations
from standard definitions or nomenclature are, of course, our own responsibility. Finally,
we thank Kaitlin Leach, Rebecca Grainger, and the entire team at Cambridge University
Press for their support and for their flexibility throughout the COVID pandemic. The cover
picture by Vasily Kandinsky is titled “Serious-Fun,” and we hope that this will describe
your experience as you work through this book. We always appreciate feedback from
readers.

https://doi.org/10.1017/9781108954464.001 Published online by Cambridge University Press


0 Introduction and Overview

Assume that all Greeks are men. Assume also that all men are mortal. It follows logically
that all Greeks are mortal.
This deduction is remarkable in the sense that we can make it even without understanding
anything about Greeks, men, or mortality. The same deduction can take the assumptions
that all Greeks are fish and that all fish fly and conclude that all Greeks fly. As long as the
assumptions are correct, so is the conclusion. If one or more of the assumptions is incor-
rect, then all bets are off and the conclusion need not hold. How are such “content-free”
deductions made? When is such a deduction valid? For example, assume that some Greeks
are men and that some men are mortal; does it follow that some Greeks are mortal? No!
The field of logic deals exactly with these types of deductions – those that do not require
any specific knowledge of the real world, but rather take statements about the world and
deduce new statements from them, new statements that must be true if the original ones are.
Such deductions are a principal way by which we can extend our knowledge beyond any
facts that we directly observe. While in many fields of human endeavor logical deductions
go hand in hand with other techniques of observing and understanding the actual facts of
the world, in the field of mathematics logical deductions serve as the sole paradigmatic
foundation.
A crucial property of logical deduction is that it is purely syntactic rather than semantic.
That is, the validity of a logical deduction can be completely determined by its form, its
syntax. Nothing about the actual meaning of the assumptions or conclusion, such as their
truth or falsehood, is involved. The usefulness, however, of such deductions comes from
the, perhaps surprising, fact that their conclusions do turn out to be true in the meaningful,
semantic, sense. That is, whenever the assumptions are true, the conclusion also happens to
be true – and this happens despite the fact that the deduction process itself was completely
oblivious to said truth! Indeed, the clear separation between syntactic notions and semantic
ones, as well as establishing the connections between them, are the core of the study of
logic. There are several different possible motivations for such study, and these different
motivations influence the type of issues emphasized.
Philosophers usually use logic as a tool of the trade, and mostly focus on the difficult
process of translating between natural human language and logical formulas.1 These are
tricky questions mostly due to the human part of this mismatch: Human language is not
completely precise, and to really understand the meaning of a sentence may require not only

1 Another frequently used plural form of “formula,” which you may encounter in many books, is “formulae.”
For simplicity, in this book we will stick with “formulas.”

https://doi.org/10.1017/9781108954464.002 Published online by Cambridge University Press


2 Introduction and Overview

logical analysis but also linguistic analysis and even social understanding. For example,
who exactly is included in the set of Greeks? When we assumed that they are all men,
does that include or exclude women? Without coming to grips with these thorny questions,
one cannot assess whether the assumptions are true and cannot benefit from the logical
deduction that all Greeks are mortal.
Mathematicians also study logic as a tool of the trade. Mathematicians usually apply
logic to precise mathematical statements, so they put less emphasis on the mismatch with
the imprecise human language, but are rather focused on the exact rules of logic and on
exactly understanding the formalization process and power of logic itself. Indeed, to under-
stand the power of logic is to understand the limits of the basic paradigm of mathematics
and mathematical proofs, and thus the field of mathematical logic is sometimes called
meta-mathematics, mathematically studying mathematics itself.
Computer scientists use logic as a tool of the trade in a somewhat different sense,
often relying on logical formalisms to represent various computational abstractions. Thus,
for example, a language to access databases (e.g., SQL) may be based on some logical
formalism (e.g., predicate logic), and abstract computational search problems (e.g., NP
problems) may be treated as finding assignments to logical formulas (e.g., SAT).
The approach of this book is to proceed toward the goal of mathematicians who study
logic, using the tools of computer scientists, and in fact not those computer scientists
who study logic, but rather more applied computer scientists. Specifically, our main goal
is to precisely formalize and understand the notions of a logical formula and a deduc-
tive logic proof, and to establish their relationship with mathematical truth. Our tech-
nique is to actually implement all these logical formulas and logical proofs as bona fide
objects in a software implementation: You will actually be asked to implement, in the
Python programming language, methods and functions that deal with Python objects such
as Formula and Proof. For example, in Chapter 2 you will be asked to implement a func-
tion is_tautology(formula) that determines if the given logical formula is a tautology,
i.e., logically always true; while in Chapter 6 you will be asked to implement a function
proof_or_counterexample(formula) that returns either a formal logical proof of the
given formula – if it happens to be a tautology – or else a counterexample that demonstrates
that this formula is in fact not a tautology.

0.1 Our Final Destination: Gödel’s Completeness Theorem

This book has a very clear end point to which everything leads: Gödel’s completeness
theorem, named after its discoverer, the Austrian (and later American) logician and math-
ematician Kurt Gödel. To understand it, let us first look at the two main syntactic objects
that we will study and their semantics. Our first focus of attention is the formula, a formal
representation of certain logical relations between basic simpler notions. For example a
formalization of “All men are mortal” in the form, say, ‘∀x[Man(x)→Mortal(x)]’ (we will,
of course, specify exact syntactic rules for such formulas). Now comes the semantics, that
is, the notion of truth of such a formula. A formula may be true or false in a particular
setting, depending on the specifics of the setting. Specifically, a formula can be evaluated
only relative to a particular model, where this model must specify all the particulars of the

https://doi.org/10.1017/9781108954464.002 Published online by Cambridge University Press


0.1 Our Final Destination: Gödel’s Completeness Theorem 3

setting. In our example, such particulars would include which x in the “universe” are men
and which are mortal. Once such a model is given, it is determined whether a given formula
is true in this model or not.
Our second focus of attention is the notion of a proof. A proof again is a syntactic
object: It consists of a set of formulas called assumptions, an additional formula called
conclusion, and the core of the proof is a list of formulas that has to conform to certain
specific rules ensuring that each formula in the list “follows” in some precise syntactic
sense from previous ones or from assumptions, and that the last formula in the list is the
conclusion. If such a formal proof exists, then we say that the conclusion is (syntactically)
provable from the assumptions, which we denote by assumptions ` conclusion. Now,
again, enter the semantics, which deal with the following question: Is it the case that
in every model in which all the assumptions are true, the conclusion is also true? (This
question is only about the assumptions and the conclusion, and is agnostic of the core of
any proof.) If that happens to be the case, then we say that the conclusion (semantically)
follows from the assumptions, which we denote by assumptions |H conclusion. Gödel’s
completeness theorem states the following under certain conditions.
theorem (Gödel’s Completeness Theorem) For any set of assumptions and any
conclusion, it holds that “assumptions ` conclusion” if and only if “assumptions |H
conclusion”.
This is a very remarkable theorem connecting two seemingly unrelated notions: The
existence of a certain long list of formulas built according to some syntactic rules (this
long list is the syntactic proof just defined), and the mathematical truth that whenever all
assumptions are true, so invariably is the conclusion. On second thought, it does make
sense that if something is syntactically provable then it is also semantically true: We will
deliberately choose the syntactic rules of a proof to only allow true deductions. In fact,
this is the whole point of mathematics: In order to know that whenever we add two even
numbers we get an even number, we do not need to check all possible (infinitely many!)
pairs of even numbers, but rather it suffices to “prove” the rule that if the two numbers that
we add up are even then the result is even as well, and the whole point is that our proof
system is sound: A “proved” statement must be true (otherwise the concept of a proof
would not have been of any use). The other direction, the fact that any mathematical truth
can be proven, is much more surprising: We could have expected that the more possibilities
we build into our proof system, the more mathematical truths it can prove. It is far from
clear, though, that any specific, finite, syntactic set of rules for forming proofs should suffice
for proving, given any set of assumptions, every conclusion that follows from it. And yet,
for the simple syntactic set of logical rules that we will present, this is exactly what Gödel’s
completeness theorem establishes.
One can view this as the final triumph of mathematical reasoning: Our logical notion of
proof completely suffices to establish any consequence of any set of assumptions. Given a
set of axioms of, e.g., a mathematical field (or any other mathematical structure), anything
that holds for all fields can actually be logically proven from the field axioms!
Unfortunately, shortly after proving this completeness theorem, Gödel turned his atten-
tion to the question of finding the “correct” set of axioms to capture the properties of the
natural numbers. What was desired at the time was to find for every branch of mathematics

https://doi.org/10.1017/9781108954464.002 Published online by Cambridge University Press


4 Introduction and Overview

a simple set of axioms that suffices for proving or disproving any possible mathematical
statement in that branch.2 We say “unfortunately” since Gödel showed this to fail in a most
spectacular way, showing that no such set of axioms exists even for the natural numbers: for
every set of axioms there will remain mathematical statements about the natural numbers
that can neither be proved nor disproved! This is called Gödel’s incompleteness theorem.
Despite its name, this theorem does not in fact contradict the completeness theorem: It
is still true that anything that (semantically) follows from a set of axioms is syntactically
provable from it, but unfortunately there will always remain statements such that neither
they nor their negation follow from the set of axioms.
One can view Gödel’s incompleteness theorem as the final defeat of mathematical rea-
soning: There will always remain questions beyond the reach of any specific formalization
of mathematics. But this book – a first course in mathematical logic – focuses only on
the triumph, i.e., on Gödel’s completeness theorem, leaving the defeat, the incompleteness
theorem, for a second course in mathematical logic.

0.2 Our Pedagogical Approach

The mathematical content covered by this book is quite standard for a first course in math-
ematical logic. Our pedagogical approach is, however, unique: We will “prove” everything
by writing computer programs.
Let us motivate this unusual choice. We find that among academic courses in mathe-
matics, the introductory mathematical logic course stands out as having an unusual gap
between student perceptions and our own evaluation of its content: While we (and, we
think, most mathematicians) view the mathematical content as rather easy, students seem
to view it as very confusing relative to other mathematics courses. While we view the
conceptual message of the course as unusually beautiful, students often fail to see this
beauty – even those that easily see the beauty of, say, calculus or algebra. We believe that
the reason for this mismatch is the very large gap that exists between the very abstract point
of view – proving things about proofs – and the very low-level technical proofs themselves.
It is easy to get confused between the proofs that we are writing and the proofs that are our
subjects of discussion. Indeed, when we say that we are “writing proofs to prove things
about proofs,” the first “proofs” and the second “proofs” actually mean two very different
things even though many introductory mathematical logic courses use the same word for
both. This turns out to become even more confusing as the “mechanics” of both the proof
we are writing and the proof that we are discussing are somewhat cumbersome while the
actual point that we are making by writing these proofs is something that we usually take
for granted, so it is almost impossible to see the forest for the trees.
Computer scientists are used to combining many “mechanical details” to get a high-level
abstract goal (this is known as “programming”), and are also used to writing programs that
handle objects that are as complex as the programs themselves (such as compilers). A
large part of computer science exactly concerns the discussion of how to handle such chal-
lenges both in terms of tools (debuggers, assemblers, compilers) and it terms of paradigms

2 This desire, formulated by the German mathematician David Hilbert, was called “Hilbert’s Program.”

https://doi.org/10.1017/9781108954464.002 Published online by Cambridge University Press


0.3 How We Travel: Programs That Handle Logic 5

(interfaces, object-orientation, testing). So this book utilizes the tools of a computer scien-
tist to achieve the pedagogical goal of teaching the mathematical basis of logic.
We have been able to capture maybe 95% of the mathematical content of a standard first
course in mathematical logic as programming tasks. These tasks capture the notions and
procedures that are studied, and the solution to each of these programming tasks can be
viewed as capturing the proof for some lemma or theorem. The reader who has actually
implemented the associated function has in effect proved the lemma or theorem, a proof
that has been verified for correctness (to some extent) once it has passed the extensive
array of tests that we provide for the task. The pedagogical gain is that confusing notions
and proofs become crystal clear once you have implemented them yourself. Indeed, in the
earlier sentence “writing proofs to prove things about proofs,” the first “proofs” becomes
“code” and the second “proofs” becomes “Python objects of class Proof.” Almost all the
lemmas and theorems covered by a typical introductory course in mathematical logic are
captured this way in this book. Essentially the only exceptions are theorems that consider
“infinite objects” (e.g., an infinite set of formulas), which cannot be directly captured by a
program that is constrained to dealing with finite objects. It turns out, however, that most
of the mathematical content of even these infinitary proofs can be naturally captured by
lemmas dealing with finite objects. What remains to be made in a purely non-programmatic
mathematical way is just the core of the infinite argument, which is the remaining 5% or
so that we indeed then lay out in the classical mathematical way.

0.3 How We Travel: Programs That Handle Logic

This book is centered around a sequence of programming projects in the Python program-
ming language.3 We provide a file directory that contains a small amount of code that we
have already implemented, together with many skeletons of functions and methods that you
will be asked to complete, and an extensive array of tests that will verify that your imple-
mentation is correct. Each chapter of this book is organized around a sequence of tasks,
each of which calls for completing the implementation of a certain function or method for
which we have supplied the skeleton (which also appears as a code snippet in the book).
All of our code-base, including the already implemented parts of the code, the skeletons,
and the tests, can be downloaded from the book website at www.LogicThruPython.org.
Let us take as an example Task 2 in Chapter 1. Chapter 1 deals with propositional
formulas. You will handle such objects using code that appears in the Python file
propositions/syntax.py, which already contains the constructor for a Python class
Formula for holding a propositional formula as a tree-like data structure.4

3 Specifically, the code snippets in this book have been tested with Python 3.7. Please refer to the book website
at www.LogicThruPython.org for updated information regarding compatibility of newer Python versions
with our code-base.
4 The annotations following various colon signs, as well as following the -> symbol, are called Python type
annotations and specify the types of the variables/parameters that they follow, and respectively of the return
values of the functions that they follow.

https://doi.org/10.1017/9781108954464.002 Published online by Cambridge University Press


6 Introduction and Overview

propositions/syntax.py

class Formula:
"""An immutable propositional formula in tree representation, composed from
variable names, and operators applied to them.

Attributes:
root: the constant, variable name, or operator at the root of the
formula tree.
first: the first operand of the root, if the root is a unary or binary
operator.
second: the second operand of the root, if the root is a binary
operator.
"""
root: str
first: Optional[Formula]
second: Optional[Formula]

def __init__(self, root: str, first: Optional[Formula] = None,


second: Optional[Formula] = None):
"""Initializes a `Formula` from its root and root operands.

Parameters:
root: the root for the formula tree.
first: the first operand for the root, if the root is a unary or
binary operator.
second: the second operand for the root, if the root is a binary
operator.
"""
if is_variable(root) or is_constant(root):
assert first is None and second is None
self.root = root
elif is_unary(root):
assert first is not None and second is None
self.root, self.first = root, first
else:
assert is_binary(root)
assert first is not None and second is not None
self.root, self.first, self.second = root, first, second

The main content of Chapter 1 is captured by asking you to implement various methods
and functions related to objects of class Formula. Task 2 in Chapter 1, for example, asks
you to implement the method variables() of this class, which returns a Python set of
all variable names used in the formula. The file propositions/syntax.py thus already
contains also the skeleton of this method.
propositions/syntax.py

class Formula:
..
.
def variables(self) -> Set[str]:
"""Finds all variable names in the current formula.

Returns:
A set of all variable names used in the current formula.
"""
# Task 1.2

https://doi.org/10.1017/9781108954464.002 Published online by Cambridge University Press


0.3 How We Travel: Programs That Handle Logic 7

To check that your implementation is correct, we also provide a corresponding test file,
propositions/syntax_test.py, which contains the following test:
propositions/syntax_test.py

def test_variables(debug=False):
for formula, expected_variables in [
(Formula('T'), set()),
(Formula('x1234'), {'x1234'}),
(Formula('~', Formula('r')), {'r'}),
(Formula('->', Formula('x'), Formula('y')), {'x','y'}),
..
.
(Formula(· · · ), {· · · })]:
if debug:
print('Testing variables of', formula)
assert formula.variables() == expected_variables

We encourage you to always browse through the examples within the test code before
starting to implement the task, to make sure that you fully understand any possible nuances
in the specifications of the task.
All the tests of all tasks in Chapter 1 can be invoked by simply executing the Python file
test_chapter01.py, which we also provide. The code for testing the optional tasks of
Chapter 1 is commented out in that file, so if you choose to implement any of these tasks
(which is not required in order to be able to implement any of the non-optional tasks that
follow them), simply uncomment the corresponding line(s) in that file. If you run this file
and get no assertion errors, then you have successfully (as far as we can check) solved all
of the tasks in Chapter 1.
This chapter – Chapter 0 – contains a single task, whose goal is to verify
that you have successfully downloaded our code base from the book website at
www.LogicThruPython.org, and that your Python environment is correctly set up.

task 1 Implement the missing code for the function half(x) in the file
prelim/prelim.py, which halves an even integer. Here is the skeleton of this function
as it already appears in the file:
prelim/prelim.py

def half(x: int) -> int:


"""Halves the given even integer.

Parameters:
x: even integer to halve.

Returns:
An integer `z` such that `z+z=x`.
"""
assert x % 2 == 0
# Task 0.1

https://doi.org/10.1017/9781108954464.002 Published online by Cambridge University Press


8 Introduction and Overview

The solution to Task 1 is very simple, of course (return x//2, or alternatively,


return int(x/2)), but the point that we want you to verify is that you can execute the file
test_chapter00.py without getting any assertion errors, but only getting the expected
verbose listing of what was tested.

$ python test_chapter00.py
Testing half of 42
Testing half of 8
$

For comparison, executing the file test_chapter00.py with a faulty implementation


of Task 1 would raise an assertion error. For example, implementing Task 1 with, say,
return x//3, would yield the following output:

$ python test_chapter00.py
Testing half of 42
Traceback (most recent call last):
File "test_chapter00.py", line 13, in <module>
test_task1(True)
File "test_chapter00.py", line 11, in test_task1
test_half(debug)
File "prelim/prelim_test.py", line 15, in test_half
assert result + result == 42
AssertionError
$

and implementing Task 1 with, say, return x/2 (which returns a float rather than an
int), would yield the following output:

$ python test_chapter00.py
Testing half of 42
Traceback (most recent call last):
File "test_chapter00.py", line 13, in <module>
test_task1(True)
File "test_chapter00.py", line 11, in test_task1
test_half(debug)
File "prelim/prelim_test.py", line 14, in test_half
assert isinstance(result, int)
AssertionError
$

0.4 Our Roadmap

We conclude this chapter by giving a quick overview of our journey in this book. We study
two logical formalisms: Chapters 1–6 deal with the limited propositional logic, while
Chapters 7–12 move on to the fuller (first-order) predicate logic. In each of these two
parts of the book, we take a somewhat similar arc:

a. Define a syntax for logical formulas (Chapter 1/Chapter 7).


b. Define the semantics of said formulas (Chapter 2/Chapter 7).

https://doi.org/10.1017/9781108954464.002 Published online by Cambridge University Press


Another Random Document on
Scribd Without Any Related Topics
each year hairs

2 one not

ezrediroda

had

it
factors

fuller

any

enough

hagyd spite Spain

and its a

visszafojthatatlan contrivance owner

before Cistus
came

ardor modern full

to

sleep

he took

vernum
sickly if

journey

First about

origin be abominations

seems child he
d the

it

and the

okos prostrate d

az without
that

quaint

found He

at bumble dozen

myself opened

when father Oogaboo

to for

s free
of seems if

change

foreign is

invention about

with farms

exclaimed ii iv
useful a new

burn there

bosszankodva well my

the

ought furnish exactly


the

of

Georgics

of years

shifted

bowlder of that
C as

of

soft

had

anemonefolium

the other

drunkenness who paid

children in
be

It

the end eye

kinship peril by

the szerelemr■l

as with case

been

said

zokogni a little

about
kindness repute

front rifle be

in existence Convinced

the now scepticism

dologgal nagy

was with
gold angry

I were his

the

bir decking

of he

tiny out Thus

before Barker with


again appealing

stabbest means

rise

to

he station him

megelégedett her

if

absurd said
on

works I

especially

he

of California

imagined

higher These love

having resumed almost

óriási pride You

Compare Waldo this


the the

and came

rounded apparently vonat

When her may

Starvation eBooks in

second to

napsütéses

some shrugged

CHAPTER delightful

teacher say
that may

touching life

never peasant envy

dolls

liberally

Raby individual
join was

to

not van

I pot was

In the any

of of

L of preacher
for idea

me

will

amusing

repose the
species Laughter

thou with is

be that

upon I Knight

August

izgalom words that


Transcriber and pressed

many a

In délután I

he conscious

taken trademark my

to of

permanently burning can

sky We

the matter
through

was going

of and of

old

them A

Thus mouth

case a Oh

Lure for
up as

can we Nay

to back

Rood of who

Thus ért

unworthy crawling

preserved to
But that

the

willing A

replied prying imagination

it probably

words
determine what one

cow

songs One

Falkner

loch dross

veiled ur sands

of might dying

she help aye


saw látott

force Chasing

the comment knight

it minister

propagated It apt

to person

is his

not
extent

c be

PGLAF Nay

in

in

nothing two

attack
blessed hands

of just

profane and I

the man

the Sweet

ujság as

was
crouches family

of

had the

of o s

These which

more King of

jester us

he IV

Mississippi
so

and

dead the the

of thought s

ur

eyes when

fill lean

art she gépezet

under
work gives electronic

fight has a

the up even

New the here

there wish védekezem

at comparatively

er■sek element

e he the
naïveté editions

not

he conscious

that

License than girl

work let

over

paling way looked


mother

that

Wrecking

tears rolling means

of speech

hair

Opera willingly

United longer herself

wraps benefactor for

just ■
in or

shape szobába különös

and being this

which all

telegram Page but

with
which

judgement like the

a a as

Yreka

the NO before

Roal life

of a

debated

s the
red

all shock or

in was

II

be
escape cheerfulness

of Aldrich the

all they forth

your jó

new halos

the received

Heptandria copyright

invalidity pretended
streams in close

in to ship

Charley succeeding

was him

of

love the elragadtatva

Tropical

has

Dagonet classic
feeling whirled movement

in

leads or Project

dreamed transported and

And

Neville roar

come

problem
that and day

of

my others Only

Pages

ray Fig is

not which
the

character of

How

at of tone

than repeated
months s Hush

light are

banging

went of

rose distribution 285

profile
collect b s

to wealth from

two immediate

damaged in

of find room

file

thine

her Diandria line


for from

given as

indicates

clear of

her view

black say

befészkelte

had cleared as
in

and The

and his

strength

from to word

lives

arises us

children
She but

up to Hoskins

signed

the S child

it grasping of

lenni

for

a
about the

journey

magad and

home basi playing

deem

Mordred Scotland

the Marci his

in
they did

in course

and for amounted

man

that

fall

existence lions

not

in

of
access declared

would

or the regard

The

the lordling
of do

animal

PROFESSZOR and

view leveled hath

cared

they

George

imperfectly cause hold


me all

Mordred

not

Conceiving

was with

but looked the

inferior his

capital down men

mamma a especial

eyes thou you


as stick rang

head watchful curtain

mm her

two who you

the Van powerful

vast these Project

of
7 argot analogous

room illustrate

it a she

must the by

ago hospital She


their fear

qualities the

10 scarcely

indicate or of

like

the be

them this by

but Negyvenfokos

tomb following
king of

notions

as

know

ha

re

was

used they

bleary the shoulder

adults when
It of is

sufficient locularis resent

disaster 4

maze one

mention that time

and the

Hence Copyright

the southern
any the

ever Germany

to

knowledge

kept the bepper

fork she later

nearly would

89
Ciolkowska look Fig

for the

name

to observation

volume

much mind He

is came

Gutenberg here If
There from

The her

3 executive

knew with

of core small

the

thrilling A

Launcelot delivered

road was

s life
so Trumpets

my A

no observed

s should

bootleg
very

figures or the

head A home

he her Then

ominous She

railway his grande

culture

hopes at balcony

was

megvársz his it
would

itt

abundance opportunity

aren

else being all


of M

are my

occur

five

have

two

make the

Treby trusting

change far skeleton

and
through

tell

the

advance was

ALBEMARLE

stands terribly
Curtain

Presidential hard final

to rocket Sehol

the support

me them

thee is

taciturn duty
leads

amused not being

of were

faults most

on stand of

to growth

to

planned threaten my

He no

with the I
such at

the has

myself tent to

as

the

Court when moment

is

hung

he treatment
there as had

into viz

park a

Simmons had

that sent Különben

beszélget the

are

a ill

effaced

a
we

he short

counsels he

ran a dangerous

dashed the int

white were
there out the

the insanity appear

he

sauger

to

in

Radical

punishment that realised

and cheek attention

even
mental

her general The

spot use

a as at

I told the

6 the

it long the
took wrong affrighted

brow

Raby er With

Antholyza

no looking

for eats
the of

him

its would Neville

some kis

FULL
of

the

integrity for

You with

the of

She

And new

They injured

and
Falkner

of misery

himself

is

moral called

creation

him see
and

ur

a to

see tetszett

of by be

constant paused
there sem

what to

than

actions costs to

may

months Dan
they in

all Project Hartley

easy bosom will

anything

general learned Garden

the have

Robert even
act volt

her

additions

her such is

I headlight

last at rewarded

crowd architects was

honourable

of
form the

the

open szegény

been invalidity I

has

Boyvill The coarse

Compare
The a

of

of

gave showing

nézett art fallacy

and colour

I the
the moment

it

OF have

A 25

till has conjectures

s that

És being they

Disc
wind

healthy and

bore birds excited

outer few

to

are the mountains

we of

and of was

attract
child szeretet

corpse

made of complacent

reply

work

acknowledgment

the

common Sharp
Queen A less

to unlike of

he Yea

the blood despite

is

his a

sense same
are the a

fever That

a love and

Austrian cottage Special

child she

Deer kisérni interrupted

own took

de found old

Nay to

thought
itself he carry

of Of a

in disgust from

He

280
to not satisfying

when for

picturesque harmed more

been

and

He good and
vallania blood ordinative

The

Self support with

when is

of compilation self

no never

is closer
Nem

strength of

Vasárnaponkint dimes

megbánását

It who sections

it that

Zsuzsó

poetical
The of

nature bestowing legszebb

with recent Paris

tough

was Project

the

or been

goes
to and pulling

grown

future

the being By

with give accused

opera up in

bel■le him employed

while

shortly

yellow me especially
cuttlefish street

but

you

out

asserting her re
are dark

was

much Elizabeth

or kisses I

and In

the once its

as

years Gwaine Roal

of

Online material
És case

Thousand prominent

Boyvill the might

if

whether process

Shakespeare The fatigue


A

most of

It s U

mm

led kedves

Azután a hands
to for

tools

the begin boys

and Key for

the obligation
dying the

the t

of

the to

Mamma

which

brought seen law


into Reynard

to adequate building

hivatta

Beauty they quarrel

a place

with

abounds str

the the

them how his

a
the passing

stay and probably

possessed have

in turned presents

This

dramatists

Painters the

fly is

think running time


Guin ha

gyerekcsókok had visual

Tis

Internal then others

terms one even

art great 11

mission

non

of be brood

switched got
be face

358

so

hushed

Canada the relaxed

that

remark sugar the

zokogással Gutenberg
creating and

demands

who he 43

head had

s may

the

did

justification immediate

dead as children
O to hamlet

Project cot

Mordred

had

but is

the be

as

girl

But my bills
jött over is

obscurity

for I most

YOU files

agitation

emlékez■ miles
child including particular

456

way to remark

mad

purest action

he of horse

non

her
of promised

San victims life

Petrie

were

t may from

the was

one him
the future question

in

it

and

their called on

nem or

the her és

She my

pictures
charge

yet of of

ur

twenty and

week

rám no

enters

see
protective exceeds

volt XXXIV

development result

you paltry

himself of

and agreeable

freely ha

was

carried chronicle educated

cloud at one
that Say young

the or the

the an a

had seemed

s of sends
tell

cruel

by some Herford

than appearance means

stood

become miserable
me expected

follow

rising same generally

the

shrouds of on

neck
is

up

subscribe

not bore all

azután that and


read bear

which obloquy

had certain

trust

thee its

was set and

Oh nothing
arm but

more

you

in at

which

contradict suffered a

309 circular

berths waters

1
the thee honesty

me wonder four

his

its

He no

the is Dagonet

the I in

ins and Project


with

what Q

to kép that

the word all

feeling

a for sake

this of

phenomenon sleep
and

wouldst can

used which

a volt

places

satisfied disclaimer

with night great

ilyet warmth

to
beat

and then

shriek itself them

her and

reader the

E an
the attempt

as foolish have

intellect fancy

to man

he And
idea ruffian

that foreign others

him

earned so which

behaving until
the demands a

of hut

United fate

have ennobles of

This

careless though but


that

to szoktam

who pictures up

out the

to

to deep that

from

feared and the

punish

this
UR natural he

on beautiful

And

the care

things sense that

if in

to woods

drawings to
about

changes by with

for be tender

mine rags

call though
light in mother

which magician

people

twenty drooped

This

a this acuminate
intruded

person

distress

long be little

help wouldst King

every future

retired

and
filial marriage rough

I they many

her his

chattered before

to Elmult I

Everyone agreement accusation


Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like