tinyprove 0.1.1__tar.gz → 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tinyprove
3
- Version: 0.1.1
3
+ Version: 0.1.3
4
4
  Summary: Tiny CoC-based theorem prover with inductive types
5
5
  Project-URL: Homepage, https://github.com/pb1729/tinyprove
6
6
  Project-URL: Repository, https://github.com/pb1729/tinyprove
@@ -63,7 +63,12 @@ The last thing you might be curious about is: "What does `Type0` mean?" It is ne
63
63
 
64
64
  ### Entering Symbols
65
65
 
66
- You can write `Π` using the hex code `3a0`. You can write `λ` using the hex code `3bb`. These are worth memorizing, copy-pasting those symbols around all the time is *not* fun. Writing unicode characters depends a bit on your computer, but `Ctl-Shift-U` followed by typing the hex code and pressing `Enter` is pretty common. Seriously, it's only two codes, go ahead and memorize them.
66
+ Tinyprove syntax uses four greek letters as special symbols. Here are their unicode codes:
67
+ * `Π` has code `3a0`
68
+ * `λ` has code `3bb`
69
+ * `δ` has code `3b4`
70
+ * `ι` has code `3b9`
71
+ These are worth memorizing, copy-pasting those symbols around all the time is no fun. Writing unicode characters depends a bit on your computer, but `Ctl-Shift-U` followed by typing the hex code and pressing `Enter` is pretty common. Seriously, it's only four codes, go ahead and memorize them.
67
72
 
68
73
  ### Applications
69
74
 
@@ -165,13 +170,16 @@ which is exactly what we expected.
165
170
 
166
171
  ### Making Definitions
167
172
 
168
- You can make your own definitions and add them to `DEFNS`. This is done by making a `ConstDefinition` and then feeding it to `DEFNS.add()`:
173
+ You can make your own definitions and add them to `DEFNS`. This is done with the `extend_definitions` function. This function will *update* the definitions object passed as its first argument to add (in order) each definition in the list of definitions passed as its second argument. Here's how we'd define addition with this system:
169
174
 
170
175
  ```python
171
176
  # define addition
172
- DEFNS.add(ConstDefinition("add",
173
- parse("λ a: Nat -> λ b: Nat -> (Nat.ind.0 (λ _: Nat -> Nat) b (λ n: Nat -> λ r: Nat -> (Nat.S r)) a)"),
174
- DEFNS))
177
+ extend_definitions(DEFNS, [
178
+ """
179
+ δ add =
180
+ λ a: Nat -> λ b: Nat -> (Nat.ind.0 (λ _: Nat -> Nat) b (λ n: Nat -> λ r: Nat -> (Nat.S r)) a)
181
+ """
182
+ ])
175
183
  ```
176
184
 
177
185
  I'll explain what `Nat.ind.0` means later, but we can check what the type of the `add` function is by running:
@@ -188,11 +196,13 @@ which prints
188
196
 
189
197
  I.e. `add` takes two `Nat`s and produces a `Nat`, as expected.
190
198
 
191
- Because definitions can depend on other definitions, we need to pass `DEFNS` when creating a new definition. For example, `add` depended on having an existing `Nat` definition. So to make a ConstDefinition, we need to pass a unique name for the definition, a defined value, and our `Definitions` object.
199
+ The symbol `δ` (for "define") is used like `let` or `const` in javascript to tell the language that we're making defining a constant. Then the constant name follows. Optionally, we can put the expected type of the constant next using `:` to denote type annotation. If we do this, tinyprove will typecheck the constant to ensure it has the type we specified. Finally, we put `=` followed by the actual value of the constant. We could have defined addition using either `δ add = ...` or `δ add: (Π a: Nat => Π b: Nat => Nat) = ...`.
200
+
201
+ Note that extend_definitions has parsing built in, and so definitions are given as strings of tinyprove code. Because definitions are added in order, it's possible for definitions to refer to previous definitions in the passed list.
192
202
 
193
203
  ### Inductive Types
194
204
 
195
- One of the standard ways to create new types in tinyprove is to define an inductive type. `False`, `And`, `Or`, `Nat`, and even `Eq` (equality) are all in fact defined as inductive types! You define an inductive type by defining its paramters, indices, and constructors. The `Nat` type does not have any parameters or indices, so it makes a nice starting example. Nat has two constructors, `Nat.Z` and `Nat.S`. Let's see their types:
205
+ One thing we need to be able to do most of modern mathematics is to define inductive types. `False`, `And`, `Or`, `Nat`, and even `Eq` (equality) are all in fact defined as inductive types! You define an inductive type by defining its paramters, indices, and constructors. The `Nat` type does not have any parameters or indices, so it makes a nice starting example. Nat has two constructors, `Nat.Z` and `Nat.S`. Let's see their types:
196
206
 
197
207
  ```python
198
208
  print(DEFNS["Nat.Z"].str([]))
@@ -208,38 +218,31 @@ Nat
208
218
 
209
219
  So `Nat.Z` is already a natural number. In fact, it's the smallest natural number, zero. `Nat.S` is the successor function, it accepts a natural number `n` and produces the natural number `n + 1`. Every natural number except zero can be written as the successor of some other natural number. So the actual representation of the number 3 is `(Nat.S (Nat.S (Nat.S Nat.Z)))`.
210
220
 
211
- One thing that's interesting here is that the type `Nat` is *recursive*. Some of its constructors (i.e. `Nat.S`) need arguments that are themselves of type `Nat`. This kind of recursion is very powerful, but it means we can't just define our constructors using `Term`s. After all, the `Nat` type is not yet defined, so there's no way for us to specify that a constructor should take an argument of type `Nat`.
212
-
213
- Tinyprove's solution to this is to define an **intermediate representation** (IR) to represent the *syntax* of tinyprove expressions. While we can think of `Term`s more or less as actual values, `IrNode`s (the datatype of our intermediate representation) just encode the *representations* of those values. An `IrNode` can be converted to an actual `Term` by calling its `.to_term([])` method. You can get the `IrNode` for an expression by using the `parse_ir()` function. Indeed, the `parse` function itself actually works by first using `parse_ir` to obtain the IR for the expression, and then calling `.to_term([])` on the result.
221
+ One thing that's interesting here is that the type `Nat` is *recursive*. Some of its constructors (i.e. `Nat.S`) need arguments that are themselves of type `Nat`. This kind of recursion is very powerful, but it makes writing down inductive types slightly complicated. Inductive types can't simply be written as `Term`s in the existing language, so we can't define them as constants using the `δ ...` syntax described above. Instead, we have a special `ι` syntax for creating new inductive types.
214
222
 
215
- You can also build up the intermediate representation yourself from scratch. This is the intended clean way for you to generate tinyprove code programatically. (You could generate strings and then parse them, but it's easier to just work with the IR directly.) The basic IR datatypes are:
216
- * IrSort(level)
217
- * IrConst(name)
218
- * IrVar(name)
219
- * IrPi(param_name, input\_type, output\_type)
220
- * IrLam(param_name, input\_type, body)
221
- * IrApp(fn, arg)
223
+ An inductive type definition is written: `ι TypeName (param_1: Param1Type, param_2: Param2Type...) [index_1: Index1Type, index_2: Index2Type...] : Sort` where `Sort` is `Type0` or `Type1`, etc. After that, you write all the constructors. Each constructor is written as `| constructor_name (arg_1: Arg1Type, arg_2: Arg2Type...) => TypeName[index_1_val, index_2_val...]`. Any constructor arguments whose type is the type being defined are written with indices after the type name in brackets.
222
224
 
223
- These are the basic params we need to make arbitrary `Term`s, but to define inductive types we need a couple more:
224
- * IrInductiveSelfRef(indices)
225
- * IrConstructorDefinition(constructor_name, args, result\_indices)
225
+ So, for example, the constructor `Nat.S` has the following tinyprove syntax:
226
226
 
227
- So, for example, the constructor `Nat.S` is defined as follows:
228
-
229
- ```python
230
- IrConstructorDefinition("S", [("n", IrInductiveSelfRef([]))], [])
227
+ ```
228
+ ι Nat () [] : Type0
229
+ | Z () => Nat[]
230
+ | S (n: Nat[]) => Nat[]
231
231
  ```
232
232
 
233
- The `args` of a constructor are a list of `(name: str, type: IrNode)` tuples, where we specify the names and types of the args. Here, the use of `IrInductiveSelfRef([])` as the type of `n` indicates that `n` is a `Nat`, i.e. an instance of the type we're defining. Here's the full definition of `Nat`:
233
+ It would be added to `DEFNS` using `extend_definitions`, the same as a regular definition:
234
234
 
235
235
  ```python
236
- DEFNS.add(InductiveDef("Nat", IrSort(0), [], [],
237
- [
238
- IrConstructorDefinition("Z", [], []),
239
- IrConstructorDefinition("S", [("n", IrInductiveSelfRef([]))], []),
240
- ], DEFNS))
236
+ extend_definitions(DEFNS, [
237
+ """
238
+ ι Nat () [] : Type0
239
+ | Z () => Nat[]
240
+ | S (n: Nat[]) => Nat[]
241
+ """
242
+ ])
241
243
  ```
242
244
 
245
+
243
246
  #### induction
244
247
 
245
248
  Let's review our definition of addition. I've expanded the code a little bit and added comments so it's easier to read.
@@ -247,22 +250,23 @@ Let's review our definition of addition. I've expanded the code a little bit and
247
250
  Here's the intuitive explanation of how it works: If we want to define addition, one very simple way of doing it is to say that `0 + b = b` and `(n + 1) + b = (n + b) + 1`. Since we already have a function `Nat.S` for adding 1, we can use these rules to make a function that allows us to add any two numbers:
248
251
 
249
252
  ```python
250
- DEFNS.add(ConstDefinition("add",
251
- parse("""
252
- λ a: Nat -> λ b: Nat ->
253
- (Nat.ind.0
254
- (λ _: Nat -> Nat) # motive: our return type is simply Nat
255
- # case where a = 0:
256
- b
257
- # case where a = n + 1:
258
- (λ n: Nat -> λ r: Nat -> (Nat.S r)) # in this line, r is the recursive result, (n + b)
259
- a # match on a
260
- )
261
- """),
262
- DEFNS))
263
- ```
264
-
265
- We have to use recursion though. In the case where `a = n + 1`, we now have to add `n + b`. Thus, the case functions are applied recursively all the way until we reach zero. Then `b` is returned without a recursive call. It's a nice fact about inductive types that recursion on such a type *always terminates*. Maybe it's not obvious that this could be true, but it arises from the fact that instances of the type have to be built up in order. We start out with `Nat.Z`, and can only reach any higher number by applying `Nat.S` repeatedly. In the C programming language, you're allowed to make a struct with a pointer in it that points to itself. But this is not allowed in a proof language. Anything you feed to a constructor must *already fully exist*, and it can't be modified after the fact either. And because things must have been built by a finite process, we must be able to disassemble them by a finite process too.
253
+ extend_definitions(DEFNS, [
254
+ """
255
+ δ add =
256
+ λ a: Nat -> λ b: Nat ->
257
+ (Nat.ind.0
258
+ (λ _: Nat -> Nat) # motive: our return type is simply Nat
259
+ # case where a = 0:
260
+ b
261
+ # case where a = n + 1:
262
+ (λ n: Nat -> λ r: Nat -> (Nat.S r)) # in this line, r is the recursive result, (n + b)
263
+ a # match on a
264
+ )
265
+ """
266
+ ])
267
+ ```
268
+
269
+ We have to use recursion here. In the case where `a = n + 1`, we now have to add `n + b`. Thus, the case functions are applied recursively all the way until we reach zero. Then `b` is returned without a recursive call. It's a nice fact about inductive types that recursion on such a type *always terminates*. Maybe it's not obvious that this could be true, but it arises from the fact that instances of the type have to be built up in order. We start out with `Nat.Z`, and can only reach any higher number by applying `Nat.S` repeatedly. In the C programming language, you're allowed to make a struct with a pointer in it that points to itself. But this is not allowed in a proof language. Anything you feed to a constructor must *already fully exist*, and it can't be modified after the fact either. And because things must have been built by a finite process, we must be able to disassemble them by a finite process too.
266
270
 
267
271
  What `Nat.ind.0` does is to provide a formal way of making a recursive function for the type `Nat`. It first asks for a motive, a function that gives us the type we want this whole recursion process to return. Then we need to provide cases to handle the constructors one by one. First we handle the `Nat.Z` constructor, then the `Nat.S` one. If a constructor accepts a recursive argument (i.e. one of its args is an inductive self-ref) then that case function gets passed a bonus argument: the result of recursively calling our `Nat.ind.0` expression on that argument.
268
272
 
@@ -328,16 +332,14 @@ To summarize the difference between parameters and indices in a few words:
328
332
 
329
333
  Indices are one of the more difficult-to-understand parts of inductive types. Equality will be our example for this section. Here is how `Eq` is defined:
330
334
 
331
- ```python
332
- DEFNS.add(InductiveDef("Eq", IrSort(0), [("A", IrSort(0)), ("x", IrVar("A"))], [("y", IrVar("A"))],
333
- [
334
- IrConstructorDefinition("refl", [], [IrVar("x")]),
335
- ], DEFNS))
335
+ ```
336
+ ι Eq (A: Type0, x: A) [y: A] : Type0
337
+ | refl () => Eq[x]
336
338
  ```
337
339
 
338
- Here we have a list of the type parameters `A: Type0` and `x: A` as the third argument to `InductiveDef`. The fourth argument is a list of indices, and says that we have one index `y: A`. `Eq` has only one constructor, `Eq.refl`. This constructor takes no arguments (`[]` in the constructor definition), but remember that we still have to tell it the type parameters, so a call to `Eq.refl` would look something like `(Eq.refl Nat Nat.Z)`, which produces a proof of type `(Eq Nat Nat.Z Nat.Z)`, aka "0 = 0".
340
+ Here we have type parameters `A: Type0` and `x: A`, and we have one index `y: A`. `Eq` has only one constructor, `Eq.refl`. This constructor takes no arguments (`()` in the constructor definition), but remember that we still have to tell it the type parameters, so a call to `Eq.refl` would look something like `(Eq.refl Nat Nat.Z)`, which produces a proof of type `(Eq Nat Nat.Z Nat.Z)`, aka "0 = 0".
339
341
 
340
- Each constructor has to tell us the indices that it produces. The `[IrVar("x")]` says that the `Eq.refl` constructor produces `x` as the index of the resulting equaltiy type. Just like all the other inductive types, `Eq.ind.0` is a thing, and it lets us use proofs of equalities to construct various other things. Here's an example of how we'd use it:
342
+ Each constructor has to tell us the indices that it produces. The `=> Eq[x]` says that the `Eq.refl` constructor produces `x` as the index of the resulting equaltiy type. Just like all the other inductive types, `Eq.ind.0` is a thing, and it lets us use proofs of equalities to construct various other things. Here's an example of how we'd use it:
341
343
 
342
344
  ```python
343
345
  # Functions of equals are equal
@@ -362,7 +364,7 @@ check(
362
364
  [], DEFNS)
363
365
  ```
364
366
 
365
- As an exercise, can you prove the three standard properties (reflexivity, symmetry, transitivity) of equality by making use `Eq.ind.0`? (Hint: as you may be able to guess by the looking at the name of `Eq`'s only constructor, one of these proofs is very easy.)
367
+ As an exercise, can you prove the three standard properties (reflexivity, symmetry, transitivity) of equality using `Eq.ind.0`? (Hint: as you may be able to guess by the looking at the name of `Eq`'s only constructor, one of these proofs is very easy.)
366
368
 
367
369
  ### Current listing of inductive types created by get_usual_axioms()
368
370
 
@@ -414,9 +416,7 @@ Nat.ind.0 (Π @motive: (Π @instance: Nat => Type0) => (Π @case_
414
416
 
415
417
  ### Conclusion
416
418
 
417
- You now have all the basic knowledge you need to start proving things. When writing proofs, you should be making new `ConstDefinition`s all the time, new `InductiveDef`s every once in a while, and new `AxiomDefinition`s only if you really know what you're doing.
418
-
419
- If you get stuck, ask ChatGPT or another language model. But feed it this document first so it knows what's going on.
419
+ You now have all the basic knowledge you need to start proving things. If you get stuck, ask ChatGPT or another language model. But feed it this document first so it knows what's going on.
420
420
 
421
421
  If you manage to prove `False` without adding any new `AxiomDefinition`s, that means there's something seriously wrong and you should submit an issue the includes the offending tinyprove code. Actually, if you find *any* bugs, please submit an issue. I'll also consider QoL improvements or feature requests, but keep in mind that I am very lazy.
422
422
 
@@ -53,7 +53,12 @@ The last thing you might be curious about is: "What does `Type0` mean?" It is ne
53
53
 
54
54
  ### Entering Symbols
55
55
 
56
- You can write `Π` using the hex code `3a0`. You can write `λ` using the hex code `3bb`. These are worth memorizing, copy-pasting those symbols around all the time is *not* fun. Writing unicode characters depends a bit on your computer, but `Ctl-Shift-U` followed by typing the hex code and pressing `Enter` is pretty common. Seriously, it's only two codes, go ahead and memorize them.
56
+ Tinyprove syntax uses four greek letters as special symbols. Here are their unicode codes:
57
+ * `Π` has code `3a0`
58
+ * `λ` has code `3bb`
59
+ * `δ` has code `3b4`
60
+ * `ι` has code `3b9`
61
+ These are worth memorizing, copy-pasting those symbols around all the time is no fun. Writing unicode characters depends a bit on your computer, but `Ctl-Shift-U` followed by typing the hex code and pressing `Enter` is pretty common. Seriously, it's only four codes, go ahead and memorize them.
57
62
 
58
63
  ### Applications
59
64
 
@@ -155,13 +160,16 @@ which is exactly what we expected.
155
160
 
156
161
  ### Making Definitions
157
162
 
158
- You can make your own definitions and add them to `DEFNS`. This is done by making a `ConstDefinition` and then feeding it to `DEFNS.add()`:
163
+ You can make your own definitions and add them to `DEFNS`. This is done with the `extend_definitions` function. This function will *update* the definitions object passed as its first argument to add (in order) each definition in the list of definitions passed as its second argument. Here's how we'd define addition with this system:
159
164
 
160
165
  ```python
161
166
  # define addition
162
- DEFNS.add(ConstDefinition("add",
163
- parse("λ a: Nat -> λ b: Nat -> (Nat.ind.0 (λ _: Nat -> Nat) b (λ n: Nat -> λ r: Nat -> (Nat.S r)) a)"),
164
- DEFNS))
167
+ extend_definitions(DEFNS, [
168
+ """
169
+ δ add =
170
+ λ a: Nat -> λ b: Nat -> (Nat.ind.0 (λ _: Nat -> Nat) b (λ n: Nat -> λ r: Nat -> (Nat.S r)) a)
171
+ """
172
+ ])
165
173
  ```
166
174
 
167
175
  I'll explain what `Nat.ind.0` means later, but we can check what the type of the `add` function is by running:
@@ -178,11 +186,13 @@ which prints
178
186
 
179
187
  I.e. `add` takes two `Nat`s and produces a `Nat`, as expected.
180
188
 
181
- Because definitions can depend on other definitions, we need to pass `DEFNS` when creating a new definition. For example, `add` depended on having an existing `Nat` definition. So to make a ConstDefinition, we need to pass a unique name for the definition, a defined value, and our `Definitions` object.
189
+ The symbol `δ` (for "define") is used like `let` or `const` in javascript to tell the language that we're making defining a constant. Then the constant name follows. Optionally, we can put the expected type of the constant next using `:` to denote type annotation. If we do this, tinyprove will typecheck the constant to ensure it has the type we specified. Finally, we put `=` followed by the actual value of the constant. We could have defined addition using either `δ add = ...` or `δ add: (Π a: Nat => Π b: Nat => Nat) = ...`.
190
+
191
+ Note that extend_definitions has parsing built in, and so definitions are given as strings of tinyprove code. Because definitions are added in order, it's possible for definitions to refer to previous definitions in the passed list.
182
192
 
183
193
  ### Inductive Types
184
194
 
185
- One of the standard ways to create new types in tinyprove is to define an inductive type. `False`, `And`, `Or`, `Nat`, and even `Eq` (equality) are all in fact defined as inductive types! You define an inductive type by defining its paramters, indices, and constructors. The `Nat` type does not have any parameters or indices, so it makes a nice starting example. Nat has two constructors, `Nat.Z` and `Nat.S`. Let's see their types:
195
+ One thing we need to be able to do most of modern mathematics is to define inductive types. `False`, `And`, `Or`, `Nat`, and even `Eq` (equality) are all in fact defined as inductive types! You define an inductive type by defining its paramters, indices, and constructors. The `Nat` type does not have any parameters or indices, so it makes a nice starting example. Nat has two constructors, `Nat.Z` and `Nat.S`. Let's see their types:
186
196
 
187
197
  ```python
188
198
  print(DEFNS["Nat.Z"].str([]))
@@ -198,38 +208,31 @@ Nat
198
208
 
199
209
  So `Nat.Z` is already a natural number. In fact, it's the smallest natural number, zero. `Nat.S` is the successor function, it accepts a natural number `n` and produces the natural number `n + 1`. Every natural number except zero can be written as the successor of some other natural number. So the actual representation of the number 3 is `(Nat.S (Nat.S (Nat.S Nat.Z)))`.
200
210
 
201
- One thing that's interesting here is that the type `Nat` is *recursive*. Some of its constructors (i.e. `Nat.S`) need arguments that are themselves of type `Nat`. This kind of recursion is very powerful, but it means we can't just define our constructors using `Term`s. After all, the `Nat` type is not yet defined, so there's no way for us to specify that a constructor should take an argument of type `Nat`.
202
-
203
- Tinyprove's solution to this is to define an **intermediate representation** (IR) to represent the *syntax* of tinyprove expressions. While we can think of `Term`s more or less as actual values, `IrNode`s (the datatype of our intermediate representation) just encode the *representations* of those values. An `IrNode` can be converted to an actual `Term` by calling its `.to_term([])` method. You can get the `IrNode` for an expression by using the `parse_ir()` function. Indeed, the `parse` function itself actually works by first using `parse_ir` to obtain the IR for the expression, and then calling `.to_term([])` on the result.
211
+ One thing that's interesting here is that the type `Nat` is *recursive*. Some of its constructors (i.e. `Nat.S`) need arguments that are themselves of type `Nat`. This kind of recursion is very powerful, but it makes writing down inductive types slightly complicated. Inductive types can't simply be written as `Term`s in the existing language, so we can't define them as constants using the `δ ...` syntax described above. Instead, we have a special `ι` syntax for creating new inductive types.
204
212
 
205
- You can also build up the intermediate representation yourself from scratch. This is the intended clean way for you to generate tinyprove code programatically. (You could generate strings and then parse them, but it's easier to just work with the IR directly.) The basic IR datatypes are:
206
- * IrSort(level)
207
- * IrConst(name)
208
- * IrVar(name)
209
- * IrPi(param_name, input\_type, output\_type)
210
- * IrLam(param_name, input\_type, body)
211
- * IrApp(fn, arg)
213
+ An inductive type definition is written: `ι TypeName (param_1: Param1Type, param_2: Param2Type...) [index_1: Index1Type, index_2: Index2Type...] : Sort` where `Sort` is `Type0` or `Type1`, etc. After that, you write all the constructors. Each constructor is written as `| constructor_name (arg_1: Arg1Type, arg_2: Arg2Type...) => TypeName[index_1_val, index_2_val...]`. Any constructor arguments whose type is the type being defined are written with indices after the type name in brackets.
212
214
 
213
- These are the basic params we need to make arbitrary `Term`s, but to define inductive types we need a couple more:
214
- * IrInductiveSelfRef(indices)
215
- * IrConstructorDefinition(constructor_name, args, result\_indices)
215
+ So, for example, the constructor `Nat.S` has the following tinyprove syntax:
216
216
 
217
- So, for example, the constructor `Nat.S` is defined as follows:
218
-
219
- ```python
220
- IrConstructorDefinition("S", [("n", IrInductiveSelfRef([]))], [])
217
+ ```
218
+ ι Nat () [] : Type0
219
+ | Z () => Nat[]
220
+ | S (n: Nat[]) => Nat[]
221
221
  ```
222
222
 
223
- The `args` of a constructor are a list of `(name: str, type: IrNode)` tuples, where we specify the names and types of the args. Here, the use of `IrInductiveSelfRef([])` as the type of `n` indicates that `n` is a `Nat`, i.e. an instance of the type we're defining. Here's the full definition of `Nat`:
223
+ It would be added to `DEFNS` using `extend_definitions`, the same as a regular definition:
224
224
 
225
225
  ```python
226
- DEFNS.add(InductiveDef("Nat", IrSort(0), [], [],
227
- [
228
- IrConstructorDefinition("Z", [], []),
229
- IrConstructorDefinition("S", [("n", IrInductiveSelfRef([]))], []),
230
- ], DEFNS))
226
+ extend_definitions(DEFNS, [
227
+ """
228
+ ι Nat () [] : Type0
229
+ | Z () => Nat[]
230
+ | S (n: Nat[]) => Nat[]
231
+ """
232
+ ])
231
233
  ```
232
234
 
235
+
233
236
  #### induction
234
237
 
235
238
  Let's review our definition of addition. I've expanded the code a little bit and added comments so it's easier to read.
@@ -237,22 +240,23 @@ Let's review our definition of addition. I've expanded the code a little bit and
237
240
  Here's the intuitive explanation of how it works: If we want to define addition, one very simple way of doing it is to say that `0 + b = b` and `(n + 1) + b = (n + b) + 1`. Since we already have a function `Nat.S` for adding 1, we can use these rules to make a function that allows us to add any two numbers:
238
241
 
239
242
  ```python
240
- DEFNS.add(ConstDefinition("add",
241
- parse("""
242
- λ a: Nat -> λ b: Nat ->
243
- (Nat.ind.0
244
- (λ _: Nat -> Nat) # motive: our return type is simply Nat
245
- # case where a = 0:
246
- b
247
- # case where a = n + 1:
248
- (λ n: Nat -> λ r: Nat -> (Nat.S r)) # in this line, r is the recursive result, (n + b)
249
- a # match on a
250
- )
251
- """),
252
- DEFNS))
253
- ```
254
-
255
- We have to use recursion though. In the case where `a = n + 1`, we now have to add `n + b`. Thus, the case functions are applied recursively all the way until we reach zero. Then `b` is returned without a recursive call. It's a nice fact about inductive types that recursion on such a type *always terminates*. Maybe it's not obvious that this could be true, but it arises from the fact that instances of the type have to be built up in order. We start out with `Nat.Z`, and can only reach any higher number by applying `Nat.S` repeatedly. In the C programming language, you're allowed to make a struct with a pointer in it that points to itself. But this is not allowed in a proof language. Anything you feed to a constructor must *already fully exist*, and it can't be modified after the fact either. And because things must have been built by a finite process, we must be able to disassemble them by a finite process too.
243
+ extend_definitions(DEFNS, [
244
+ """
245
+ δ add =
246
+ λ a: Nat -> λ b: Nat ->
247
+ (Nat.ind.0
248
+ (λ _: Nat -> Nat) # motive: our return type is simply Nat
249
+ # case where a = 0:
250
+ b
251
+ # case where a = n + 1:
252
+ (λ n: Nat -> λ r: Nat -> (Nat.S r)) # in this line, r is the recursive result, (n + b)
253
+ a # match on a
254
+ )
255
+ """
256
+ ])
257
+ ```
258
+
259
+ We have to use recursion here. In the case where `a = n + 1`, we now have to add `n + b`. Thus, the case functions are applied recursively all the way until we reach zero. Then `b` is returned without a recursive call. It's a nice fact about inductive types that recursion on such a type *always terminates*. Maybe it's not obvious that this could be true, but it arises from the fact that instances of the type have to be built up in order. We start out with `Nat.Z`, and can only reach any higher number by applying `Nat.S` repeatedly. In the C programming language, you're allowed to make a struct with a pointer in it that points to itself. But this is not allowed in a proof language. Anything you feed to a constructor must *already fully exist*, and it can't be modified after the fact either. And because things must have been built by a finite process, we must be able to disassemble them by a finite process too.
256
260
 
257
261
  What `Nat.ind.0` does is to provide a formal way of making a recursive function for the type `Nat`. It first asks for a motive, a function that gives us the type we want this whole recursion process to return. Then we need to provide cases to handle the constructors one by one. First we handle the `Nat.Z` constructor, then the `Nat.S` one. If a constructor accepts a recursive argument (i.e. one of its args is an inductive self-ref) then that case function gets passed a bonus argument: the result of recursively calling our `Nat.ind.0` expression on that argument.
258
262
 
@@ -318,16 +322,14 @@ To summarize the difference between parameters and indices in a few words:
318
322
 
319
323
  Indices are one of the more difficult-to-understand parts of inductive types. Equality will be our example for this section. Here is how `Eq` is defined:
320
324
 
321
- ```python
322
- DEFNS.add(InductiveDef("Eq", IrSort(0), [("A", IrSort(0)), ("x", IrVar("A"))], [("y", IrVar("A"))],
323
- [
324
- IrConstructorDefinition("refl", [], [IrVar("x")]),
325
- ], DEFNS))
325
+ ```
326
+ ι Eq (A: Type0, x: A) [y: A] : Type0
327
+ | refl () => Eq[x]
326
328
  ```
327
329
 
328
- Here we have a list of the type parameters `A: Type0` and `x: A` as the third argument to `InductiveDef`. The fourth argument is a list of indices, and says that we have one index `y: A`. `Eq` has only one constructor, `Eq.refl`. This constructor takes no arguments (`[]` in the constructor definition), but remember that we still have to tell it the type parameters, so a call to `Eq.refl` would look something like `(Eq.refl Nat Nat.Z)`, which produces a proof of type `(Eq Nat Nat.Z Nat.Z)`, aka "0 = 0".
330
+ Here we have type parameters `A: Type0` and `x: A`, and we have one index `y: A`. `Eq` has only one constructor, `Eq.refl`. This constructor takes no arguments (`()` in the constructor definition), but remember that we still have to tell it the type parameters, so a call to `Eq.refl` would look something like `(Eq.refl Nat Nat.Z)`, which produces a proof of type `(Eq Nat Nat.Z Nat.Z)`, aka "0 = 0".
329
331
 
330
- Each constructor has to tell us the indices that it produces. The `[IrVar("x")]` says that the `Eq.refl` constructor produces `x` as the index of the resulting equaltiy type. Just like all the other inductive types, `Eq.ind.0` is a thing, and it lets us use proofs of equalities to construct various other things. Here's an example of how we'd use it:
332
+ Each constructor has to tell us the indices that it produces. The `=> Eq[x]` says that the `Eq.refl` constructor produces `x` as the index of the resulting equaltiy type. Just like all the other inductive types, `Eq.ind.0` is a thing, and it lets us use proofs of equalities to construct various other things. Here's an example of how we'd use it:
331
333
 
332
334
  ```python
333
335
  # Functions of equals are equal
@@ -352,7 +354,7 @@ check(
352
354
  [], DEFNS)
353
355
  ```
354
356
 
355
- As an exercise, can you prove the three standard properties (reflexivity, symmetry, transitivity) of equality by making use `Eq.ind.0`? (Hint: as you may be able to guess by the looking at the name of `Eq`'s only constructor, one of these proofs is very easy.)
357
+ As an exercise, can you prove the three standard properties (reflexivity, symmetry, transitivity) of equality using `Eq.ind.0`? (Hint: as you may be able to guess by the looking at the name of `Eq`'s only constructor, one of these proofs is very easy.)
356
358
 
357
359
  ### Current listing of inductive types created by get_usual_axioms()
358
360
 
@@ -404,9 +406,7 @@ Nat.ind.0 (Π @motive: (Π @instance: Nat => Type0) => (Π @case_
404
406
 
405
407
  ### Conclusion
406
408
 
407
- You now have all the basic knowledge you need to start proving things. When writing proofs, you should be making new `ConstDefinition`s all the time, new `InductiveDef`s every once in a while, and new `AxiomDefinition`s only if you really know what you're doing.
408
-
409
- If you get stuck, ask ChatGPT or another language model. But feed it this document first so it knows what's going on.
409
+ You now have all the basic knowledge you need to start proving things. If you get stuck, ask ChatGPT or another language model. But feed it this document first so it knows what's going on.
410
410
 
411
411
  If you manage to prove `False` without adding any new `AxiomDefinition`s, that means there's something seriously wrong and you should submit an issue the includes the offending tinyprove code. Actually, if you find *any* bugs, please submit an issue. I'll also consider QoL improvements or feature requests, but keep in mind that I am very lazy.
412
412
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tinyprove"
7
- version = "0.1.1"
7
+ version = "0.1.3"
8
8
  description = "Tiny CoC-based theorem prover with inductive types"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -5,7 +5,7 @@ from .core import (
5
5
  infer, check,
6
6
  )
7
7
  from .ir import (
8
- IrNode, IrSort, IrConst, IrVar, IrPi, IrLam, IrApp,
8
+ IrNode, IrSort, IrConst, IrVar, IrPi, IrLam, IrApp, IrConstantDefinition
9
9
  )
10
10
  from .parser import (
11
11
  parse_ir, parse,
@@ -15,7 +15,7 @@ from .inductive import (
15
15
  InductiveDef, IrConstructorDefinition, IrInductiveSelfRef,
16
16
  )
17
17
  from .axiom_defs import (
18
- get_usual_axioms,
18
+ extend_definitions, get_usual_axioms,
19
19
  )
20
20
 
21
21
 
@@ -0,0 +1,64 @@
1
+ from typing import List
2
+
3
+ from .ir import *
4
+ from .parser import parse, parse_ir
5
+ from .core import Definitions, AxiomDefinition
6
+ from .inductive import InductiveDef, IrConstructorDefinition, IrInductiveSelfRef
7
+
8
+
9
+
10
+ def extend_definitions(defns:Definitions, src:List[str]):
11
+ """ MUTATES defns by adding all definitions from src """
12
+ for defn_str in src:
13
+ defn_ir = parse_ir(defn_str)
14
+ if hasattr(defn_ir, "to_definition"):
15
+ defns.add(defn_ir.to_definition(defns))
16
+ else:
17
+ raise RuntimeError(f"The following code does not constitute a definition:\n{defn_str}")
18
+
19
+
20
+ def get_usual_axioms(classical:bool=True) -> Definitions:
21
+ ans = Definitions()
22
+
23
+ # Constructive:
24
+ extend_definitions(ans, [
25
+ """
26
+ ι False () [] : Type0
27
+ """, """
28
+ ι Unit () [] : Type0
29
+ | in () => Unit[]
30
+ """, """
31
+ ι And (A: Type0, B: Type0) [] : Type0
32
+ | in (a: A, b: B) => And[]
33
+ """, """
34
+ ι Or (A: Type0, B: Type0) [] : Type0
35
+ | inl (a: A) => Or[]
36
+ | inr (b: B) => Or[]
37
+ """, """
38
+ ι Eq (A: Type0, x: A) [y: A] : Type0
39
+ | refl () => Eq[x]
40
+ """, """
41
+ ι Exists (A: Type0, P: (Π a: A => Type0)) [] : Type0
42
+ | in (a: A, pa: (P a)) => Exists[]
43
+ """, """
44
+ ι Nat () [] : Type0
45
+ | Z () => Nat[]
46
+ | S (n: Nat[]) => Nat[]
47
+ """
48
+ ])
49
+
50
+ # Non-constructive:
51
+ if classical:
52
+ ans.add(AxiomDefinition(
53
+ "",
54
+ {
55
+ "em": parse("Π A: Type0 => (Or A (Π a: A => False))")
56
+ },
57
+ ans))
58
+
59
+ return ans
60
+
61
+
62
+
63
+
64
+
@@ -301,10 +301,13 @@ class AxiomDefinition:
301
301
  return None
302
302
 
303
303
  class ConstDefinition:
304
- def __init__(self, name:str, value:Term, defns:Definitions):
304
+ def __init__(self, name:str, value:Term, defns:Definitions, expected_ty:(Term|None)=None):
305
305
  self.name = name
306
306
  self.value = whnf(value, defns)
307
307
  self.type = whnf(infer(self.value, [], defns), defns)
308
+ if expected_ty is not None:
309
+ if not conv(self.type, expected_ty, defns):
310
+ raise TypecheckError(f"When defining constant {self.name}, expected a type of {expected_ty.str([])} but actually got {self.type.str([])}.")
308
311
  self.used = find_used_defs(self.value)
309
312
  def get_type(self, key:List[str]) -> Term:
310
313
  match key:
@@ -76,6 +76,18 @@ class IrConstructorDefinition(IrNode):
76
76
  def to_term(self, ctx_nm):
77
77
  raise RuntimeError("Can't convert IrConstructorDefinition to Term, it is intended for creating InductiveDef's only.")
78
78
 
79
+ @dataclass(frozen=True)
80
+ class IrInductiveDefinition(IrNode):
81
+ name: str
82
+ sort: IrSort
83
+ params: List[Tuple[str, IrNode]]
84
+ indices: List[Tuple[str, IrNode]]
85
+ constructors:List[IrConstructorDefinition]
86
+ def to_term(self, ctx_nm):
87
+ raise RuntimeError("Can't convert IrInductiveDefinition to Term, it is intended for creating InductiveDef's only.")
88
+ def to_definition(self, defns: Definitions):
89
+ return InductiveDef(self.name, self.sort, self.params, self.indices, self.constructors, defns)
90
+
79
91
  def selfref_sub(node:IrNode, selfref_ir:IrNode) -> IrNode:
80
92
  match node:
81
93
  case IrLam(param, A, body):
@@ -1,4 +1,4 @@
1
- from typing import List, Dict, Tuple
1
+ from typing import List, Dict, Tuple, Optional
2
2
 
3
3
  from .core import *
4
4
 
@@ -82,3 +82,16 @@ def to_positive_int(digits:str) -> int | None:
82
82
  return val
83
83
 
84
84
 
85
+ # IR node for constant definitions:
86
+ @dataclass(frozen=True)
87
+ class IrConstantDefinition(IrNode):
88
+ name: str
89
+ value: IrNode
90
+ expected_ty: Optional[IrNode]
91
+ def to_term(self, ctx_nm):
92
+ raise RuntimeError("Can't convert IrConstantDefinition to Term, it is intended for defining constants only.")
93
+ def to_definition(self, defns: Definitions):
94
+ expected_ty = self.expected_ty.to_term([]) if self.expected_ty is not None else None
95
+ return ConstDefinition(self.name, self.value.to_term([]), defns, expected_ty)
96
+
97
+