Mercurial > cpdt > repo
comparison src/InductiveTypes.v @ 400:d27c0be2c3d4
Typesetting pass over InductiveTypes
author | Adam Chlipala <adam@chlipala.net> |
---|---|
date | Fri, 08 Jun 2012 12:51:56 -0400 |
parents | 05efde66559d |
children | 539ed97750bb |
comparison
equal
deleted
inserted
replaced
399:5986e9fd40b5 | 400:d27c0be2c3d4 |
---|---|
27 | 27 |
28 (** * Proof Terms *) | 28 (** * Proof Terms *) |
29 | 29 |
30 (** Mainstream presentations of mathematics treat proofs as objects that exist outside of the universe of mathematical objects. However, for a variety of reasoning, it is convenient to encode proofs, traditional mathematical objects, and programs within a single formal language. Validity checks on mathematical objects are useful in any setting, to catch typoes and other uninteresting errors. The benefits of static typing for programs are widely recognized, and Coq brings those benefits to both mathematical objects and programs via a uniform mechanism. In fact, from this point on, we will not bother to distinguish between programs and mathematical objects. Many mathematical formalisms are most easily encoded in terms of programs. | 30 (** Mainstream presentations of mathematics treat proofs as objects that exist outside of the universe of mathematical objects. However, for a variety of reasoning, it is convenient to encode proofs, traditional mathematical objects, and programs within a single formal language. Validity checks on mathematical objects are useful in any setting, to catch typoes and other uninteresting errors. The benefits of static typing for programs are widely recognized, and Coq brings those benefits to both mathematical objects and programs via a uniform mechanism. In fact, from this point on, we will not bother to distinguish between programs and mathematical objects. Many mathematical formalisms are most easily encoded in terms of programs. |
31 | 31 |
32 Proofs are fundamentally different from programs, because any two proofs of a theorem are considered equivalent, from a formal standpoint if not from an engineering standpoint. However, we can use the same type-checking technology to check proofs as we use to validate our programs. This is the %\index{Curry-Howard correspondence}%_Curry-Howard correspondence_ %\cite{Curry,Howard}%, an approach for relating proofs and programs. We represent mathematical theorems as types, such that a theorem's proofs are exactly those programs that type-check at the corresponding type. | 32 Proofs are fundamentally different from programs, because any two proofs of a theorem are considered equivalent, from a formal standpoint if not from an engineering standpoint. However, we can use the same type-checking technology to check proofs as we use to validate our programs. This is the%\index{Curry-Howard correspondence}% _Curry-Howard correspondence_ %\cite{Curry,Howard}%, an approach for relating proofs and programs. We represent mathematical theorems as types, such that a theorem's proofs are exactly those programs that type-check at the corresponding type. |
33 | 33 |
34 The last chapter's example already snuck in an instance of Curry-Howard. We used the token [->] to stand for both function types and logical implications. One reasonable conclusion upon seeing this might be that some fancy overloading of notations is at work. In fact, functions and implications are precisely identical according to Curry-Howard! That is, they are just two ways of describing the same computational phenomenon. | 34 The last chapter's example already snuck in an instance of Curry-Howard. We used the token [->] to stand for both function types and logical implications. One reasonable conclusion upon seeing this might be that some fancy overloading of notations is at work. In fact, functions and implications are precisely identical according to Curry-Howard! That is, they are just two ways of describing the same computational phenomenon. |
35 | 35 |
36 A short demonstration should explain how this can be. The identity function over the natural numbers is certainly not a controversial program. *) | 36 A short demonstration should explain how this can be. The identity function over the natural numbers is certainly not a controversial program. *) |
37 | 37 |
72 One of the first types we introduce will be [bool], with constructors [true] and [false]. Newcomers to Coq often wonder about the distinction between [True] and [true] and the distinction between [False] and [false]. One glib answer is that [True] and [False] are types, but [true] and [false] are not. A more useful answer is that Coq's metatheory guarantees that any term of type [bool] _evaluates_ to either [true] or [false]. This means that we have an _algorithm_ for answering any question phrased as an expression of type [bool]. Conversely, most propositions do not evaluate to [True] or [False]; the language of inductively defined propositions is much richer than that. We ought to be glad that we have no algorithm for deciding mathematical truth, since otherwise it would be clear that we could not formalize undecidable properties, like most any properties of general-purpose programs. *) | 72 One of the first types we introduce will be [bool], with constructors [true] and [false]. Newcomers to Coq often wonder about the distinction between [True] and [true] and the distinction between [False] and [false]. One glib answer is that [True] and [False] are types, but [true] and [false] are not. A more useful answer is that Coq's metatheory guarantees that any term of type [bool] _evaluates_ to either [true] or [false]. This means that we have an _algorithm_ for answering any question phrased as an expression of type [bool]. Conversely, most propositions do not evaluate to [True] or [False]; the language of inductively defined propositions is much richer than that. We ought to be glad that we have no algorithm for deciding mathematical truth, since otherwise it would be clear that we could not formalize undecidable properties, like most any properties of general-purpose programs. *) |
73 | 73 |
74 | 74 |
75 (** * Enumerations *) | 75 (** * Enumerations *) |
76 | 76 |
77 (** Coq inductive types generalize the %\index{algebraic datatypes}%algebraic datatypes found in %\index{Haskell}%Haskell and %\index{ML}%ML. Confusingly enough, inductive types also generalize %\index{generalized algebraic datatypes}%generalized algebraic datatypes (GADTs), by adding the possibility for type dependency. Even so, it is worth backing up from the examples of the last chapter and going over basic, algebraic datatype uses of inductive datatypes, because the chance to prove things about the values of these types adds new wrinkles beyond usual practice in Haskell and ML. | 77 (** Coq inductive types generalize the %\index{algebraic datatypes}%algebraic datatypes found in %\index{Haskell}%Haskell and %\index{ML}%ML. Confusingly enough, inductive types also generalize %\index{generalized algebraic datatypes}%generalized algebraic datatypes (GADT's), by adding the possibility for type dependency. Even so, it is worth backing up from the examples of the last chapter and going over basic, algebraic datatype uses of inductive datatypes, because the chance to prove things about the values of these types adds new wrinkles beyond usual practice in Haskell and ML. |
78 | 78 |
79 The singleton type [unit] is an inductive type:%\index{Gallina terms!unit}\index{Gallina terms!tt}% *) | 79 The singleton type [unit] is an inductive type:%\index{Gallina terms!unit}\index{Gallina terms!tt}% *) |
80 | 80 |
81 Inductive unit : Set := | 81 Inductive unit : Set := |
82 | tt. | 82 | tt. |
125 | 125 |
126 (** Every [Inductive] command defining a type [T] also defines an induction principle named [T_ind]. Recall from the last section that our type, operations over it, and principles for reasoning about it all live in the same language and are described by the same type system. The key to telling what is a program and what is a proof lies in the distinction between the type %\index{Gallina terms!Prop}%[Prop], which appears in our induction principle; and the type %\index{Gallina terms!Set}%[Set], which we have seen a few times already. | 126 (** Every [Inductive] command defining a type [T] also defines an induction principle named [T_ind]. Recall from the last section that our type, operations over it, and principles for reasoning about it all live in the same language and are described by the same type system. The key to telling what is a program and what is a proof lies in the distinction between the type %\index{Gallina terms!Prop}%[Prop], which appears in our induction principle; and the type %\index{Gallina terms!Set}%[Set], which we have seen a few times already. |
127 | 127 |
128 The convention goes like this: [Set] is the type of normal types used in programming, and the values of such types are programs. [Prop] is the type of logical propositions, and the values of such types are proofs. Thus, an induction principle has a type that shows us that it is a function for building proofs. | 128 The convention goes like this: [Set] is the type of normal types used in programming, and the values of such types are programs. [Prop] is the type of logical propositions, and the values of such types are proofs. Thus, an induction principle has a type that shows us that it is a function for building proofs. |
129 | 129 |
130 Specifically, [unit_ind] quantifies over a predicate [P] over [unit] values. If we can present a proof that [P] holds of [tt], then we are rewarded with a proof that [P] holds for any value [u] of type [unit]. In our last proof, the predicate was [(][fun u : unit => u = tt)]. | 130 Specifically, [unit_ind] quantifies over a predicate [P] over [unit] values. If we can present a proof that [P] holds of [tt], then we are rewarded with a proof that [P] holds for any value [u] of type [unit]. In our last proof, the predicate was [(fun u : unit => u = tt)]. |
131 | 131 |
132 The definition of [unit] places the type in [Set]. By replacing [Set] with [Prop], [unit] with [True], and [tt] with [I], we arrive at precisely the definition of [True] that the Coq standard library employs! The program type [unit] is the Curry-Howard equivalent of the proposition [True]. We might make the tongue-in-cheek claim that, while philosophers have expended much ink on the nature of truth, we have now determined that truth is the [unit] type of functional programming. | 132 The definition of [unit] places the type in [Set]. By replacing [Set] with [Prop], [unit] with [True], and [tt] with [I], we arrive at precisely the definition of [True] that the Coq standard library employs! The program type [unit] is the Curry-Howard equivalent of the proposition [True]. We might make the tongue-in-cheek claim that, while philosophers have expended much ink on the nature of truth, we have now determined that truth is the [unit] type of functional programming. |
133 | 133 |
134 %\medskip% | 134 %\medskip% |
135 | 135 |
148 (** Because [Empty_set] has no elements, the fact of having an element of this type implies anything. We use [destruct 1] instead of [destruct x] in the proof because unused quantified variables are relegated to being referred to by number. (There is a good reason for this, related to the unity of quantifiers and implication. At least within Coq's logical foundation of %\index{constructive logic}%constructive logic, which we elaborate on more in the next chapter, an implication is just a quantification over a proof, where the quantified variable is never used. It generally makes more sense to refer to implication hypotheses by number than by name, and Coq treats our quantifier over an unused variable as an implication in determining the proper behavior.) | 148 (** Because [Empty_set] has no elements, the fact of having an element of this type implies anything. We use [destruct 1] instead of [destruct x] in the proof because unused quantified variables are relegated to being referred to by number. (There is a good reason for this, related to the unity of quantifiers and implication. At least within Coq's logical foundation of %\index{constructive logic}%constructive logic, which we elaborate on more in the next chapter, an implication is just a quantification over a proof, where the quantified variable is never used. It generally makes more sense to refer to implication hypotheses by number than by name, and Coq treats our quantifier over an unused variable as an implication in determining the proper behavior.) |
149 | 149 |
150 We can see the induction principle that made this proof so easy: *) | 150 We can see the induction principle that made this proof so easy: *) |
151 | 151 |
152 Check Empty_set_ind. | 152 Check Empty_set_ind. |
153 (** [Empty_set_ind : forall (][P : Empty_set -> Prop) (e : Empty_set), P e] *) | 153 (** [Empty_set_ind : forall (P : Empty_set -> Prop) (e : Empty_set), P e] *) |
154 | 154 |
155 (** In other words, any predicate over values from the empty set holds vacuously of every such element. In the last proof, we chose the predicate [(][fun _ : Empty_set => 2 + 2 = 5)]. | 155 (** In other words, any predicate over values from the empty set holds vacuously of every such element. In the last proof, we chose the predicate [(fun _ : Empty_set => 2 + 2 = 5)]. |
156 | 156 |
157 We can also apply this get-out-of-jail-free card programmatically. Here is a lazy way of converting values of [Empty_set] to values of [unit]: *) | 157 We can also apply this get-out-of-jail-free card programmatically. Here is a lazy way of converting values of [Empty_set] to values of [unit]: *) |
158 | 158 |
159 Definition e2u (e : Empty_set) : unit := match e with end. | 159 Definition e2u (e : Empty_set) : unit := match e with end. |
160 | 160 |
205 | 205 |
206 reflexivity. | 206 reflexivity. |
207 | 207 |
208 (** Likewise for the second subgoal, so we can restart the proof and give a very compact justification.%\index{Vernacular commands!Restart}% *) | 208 (** Likewise for the second subgoal, so we can restart the proof and give a very compact justification.%\index{Vernacular commands!Restart}% *) |
209 | 209 |
210 (* begin hide *) | |
211 Restart. | 210 Restart. |
212 (* end hide *) | |
213 (** %\noindent \coqdockw{Restart}%#<tt>Restart</tt>#. *) | |
214 | 211 |
215 destruct b; reflexivity. | 212 destruct b; reflexivity. |
216 Qed. | 213 Qed. |
217 (* end thide *) | 214 (* end thide *) |
218 | 215 |
242 | 239 |
243 Inductive nat : Set := | 240 Inductive nat : Set := |
244 | O : nat | 241 | O : nat |
245 | S : nat -> nat. | 242 | S : nat -> nat. |
246 | 243 |
247 (** [O] is zero, and [S] is the successor function, so that [0] is syntactic sugar for [O], [1] for [S O], [2] for [S (][S O)], and so on. | 244 (** [O] is zero, and [S] is the successor function, so that [0] is syntactic sugar for [O], [1] for [S O], [2] for [S (S O)], and so on. |
248 | 245 |
249 Pattern matching works as we demonstrated in the last chapter:%\index{Gallina terms!pred}% *) | 246 Pattern matching works as we demonstrated in the last chapter:%\index{Gallina terms!pred}% *) |
250 | 247 |
251 Definition isZero (n : nat) : bool := | 248 Definition isZero (n : nat) : bool := |
252 match n with | 249 match n with |
306 | 303 |
307 We can start out by using computation to simplify the goal as far as we can.%\index{tactics!simpl}% *) | 304 We can start out by using computation to simplify the goal as far as we can.%\index{tactics!simpl}% *) |
308 | 305 |
309 simpl. | 306 simpl. |
310 | 307 |
311 (** Now the conclusion is [S (][plus n O) = S n]. Using our inductive hypothesis: *) | 308 (** Now the conclusion is [S (plus n O) = S n]. Using our inductive hypothesis: *) |
312 | 309 |
313 rewrite IHn. | 310 rewrite IHn. |
314 | 311 |
315 (** ...we get a trivial conclusion [S n = S n]. *) | 312 (** ...we get a trivial conclusion [S n = S n]. *) |
316 | 313 |
317 reflexivity. | 314 reflexivity. |
318 | 315 |
319 (** Not much really went on in this proof, so the [crush] tactic from the [CpdtTactics] module can prove this theorem automatically. *) | 316 (** Not much really went on in this proof, so the [crush] tactic from the [CpdtTactics] module can prove this theorem automatically. *) |
320 | 317 |
321 (* begin hide *) | |
322 Restart. | 318 Restart. |
323 (* end hide *) | |
324 (** %\noindent \coqdockw{Restart}%#<tt>Restart</tt>#. *) | |
325 | 319 |
326 induction n; crush. | 320 induction n; crush. |
327 Qed. | 321 Qed. |
328 (* end thide *) | 322 (* end thide *) |
329 | 323 |
334 nat_ind : forall P : nat -> Prop, | 328 nat_ind : forall P : nat -> Prop, |
335 P O -> (forall n : nat, P n -> P (S n)) -> forall n : nat, P n | 329 P O -> (forall n : nat, P n -> P (S n)) -> forall n : nat, P n |
336 | 330 |
337 ]] | 331 ]] |
338 | 332 |
339 Each of the two cases of our last proof came from the type of one of the arguments to [nat_ind]. We chose [P] to be [(][fun n : nat => plus n O = n)]. The first proof case corresponded to [P O] and the second case to [(][forall n : nat, P n -> P (][S n))]. The free variable [n] and inductive hypothesis [IHn] came from the argument types given here. | 333 Each of the two cases of our last proof came from the type of one of the arguments to [nat_ind]. We chose [P] to be [(fun n : nat => plus n O = n)]. The first proof case corresponded to [P O] and the second case to [(forall n : nat, P n -> P (S n))]. The free variable [n] and inductive hypothesis [IHn] came from the argument types given here. |
340 | 334 |
341 Since [nat] has a constructor that takes an argument, we may sometimes need to know that that constructor is injective.%\index{tactics!injection}\index{tactics!trivial}% *) | 335 Since [nat] has a constructor that takes an argument, we may sometimes need to know that that constructor is injective.%\index{tactics!injection}\index{tactics!trivial}% *) |
342 | 336 |
343 Theorem S_inj : forall n m : nat, S n = S m -> n = m. | 337 Theorem S_inj : forall n m : nat, S n = S m -> n = m. |
344 (* begin thide *) | 338 (* begin thide *) |
345 injection 1; trivial. | 339 injection 1; trivial. |
346 Qed. | 340 Qed. |
347 (* end thide *) | 341 (* end thide *) |
348 | 342 |
349 (** [injection] refers to a premise by number, adding new equalities between the corresponding arguments of equated terms that are formed with the same constructor. We end up needing to prove [n = m -> n = m], so it is unsurprising that a tactic named [trivial] is able to finish the proof. | 343 (** The [injection] tactic refers to a premise by number, adding new equalities between the corresponding arguments of equated terms that are formed with the same constructor. We end up needing to prove [n = m -> n = m], so it is unsurprising that a tactic named [trivial] is able to finish the proof. |
350 | 344 |
351 There is also a very useful tactic called %\index{tactics!congruence}%[congruence] that can prove this theorem immediately. [congruence] generalizes [discriminate] and [injection], and it also adds reasoning about the general properties of equality, such as that a function returns equal results on equal arguments. That is, [congruence] is a %\index{theory of equality and uninterpreted functions}%_complete decision procedure for the theory of equality and uninterpreted functions_, plus some smarts about inductive types. | 345 There is also a very useful tactic called %\index{tactics!congruence}%[congruence] that can prove this theorem immediately. [congruence] generalizes [discriminate] and [injection], and it also adds reasoning about the general properties of equality, such as that a function returns equal results on equal arguments. That is, [congruence] is a%\index{theory of equality and uninterpreted functions}% _complete decision procedure for the theory of equality and uninterpreted functions_, plus some smarts about inductive types. |
352 | 346 |
353 %\medskip% | 347 %\medskip% |
354 | 348 |
355 We can define a type of lists of natural numbers. *) | 349 We can define a type of lists of natural numbers. *) |
356 | 350 |
417 (* end thide *) | 411 (* end thide *) |
418 | 412 |
419 Theorem nsize_nsplice : forall tr1 tr2 : nat_btree, nsize (nsplice tr1 tr2) | 413 Theorem nsize_nsplice : forall tr1 tr2 : nat_btree, nsize (nsplice tr1 tr2) |
420 = plus (nsize tr2) (nsize tr1). | 414 = plus (nsize tr2) (nsize tr1). |
421 (* begin thide *) | 415 (* begin thide *) |
422 (* begin hide *) | |
423 Hint Rewrite n_plus_O plus_assoc. | 416 Hint Rewrite n_plus_O plus_assoc. |
424 (* end hide *) | |
425 (** [Hint] %\coqdockw{%#<tt>#Rewrite#</tt>#%}% [n_plus_O plus_assoc.] *) | |
426 | 417 |
427 induction tr1; crush. | 418 induction tr1; crush. |
428 Qed. | 419 Qed. |
429 (* end thide *) | 420 (* end thide *) |
430 | 421 |
716 | 707 |
717 %\medskip% | 708 %\medskip% |
718 | 709 |
719 Up to this point, we have seen how to encode in Coq more and more of what is possible with algebraic datatypes in %\index{Haskell}%Haskell and %\index{ML}%ML. This may have given the inaccurate impression that inductive types are a strict extension of algebraic datatypes. In fact, Coq must rule out some types allowed by Haskell and ML, for reasons of soundness. Reflexive types provide our first good example of such a case. | 710 Up to this point, we have seen how to encode in Coq more and more of what is possible with algebraic datatypes in %\index{Haskell}%Haskell and %\index{ML}%ML. This may have given the inaccurate impression that inductive types are a strict extension of algebraic datatypes. In fact, Coq must rule out some types allowed by Haskell and ML, for reasons of soundness. Reflexive types provide our first good example of such a case. |
720 | 711 |
721 Given our last example of an inductive type, many readers are probably eager to try encoding the syntax of %\index{lambda calculus}%lambda calculus. Indeed, the function-based representation technique that we just used, called %\index{higher-order abstract syntax}\index{HOAS|see{higher-order abstract syntax}}%_higher-order abstract syntax (HOAS)_ %\cite{HOAS}%, is the representation of choice for lambda calculi in %\index{Twelf}%Twelf and in many applications implemented in Haskell and ML. Let us try to import that choice to Coq: *) | 712 Given our last example of an inductive type, many readers are probably eager to try encoding the syntax of %\index{lambda calculus}%lambda calculus. Indeed, the function-based representation technique that we just used, called%\index{higher-order abstract syntax}\index{HOAS|see{higher-order abstract syntax}}% _higher-order abstract syntax_ (HOAS)%~\cite{HOAS}%, is the representation of choice for lambda calculi in %\index{Twelf}%Twelf and in many applications implemented in Haskell and ML. Let us try to import that choice to Coq: *) |
713 (* begin hide *) | |
714 Inductive term : Set := App | Abs. | |
715 Reset term. | |
716 (* end hide *) | |
722 (** [[ | 717 (** [[ |
723 Inductive term : Set := | 718 Inductive term : Set := |
724 | App : term -> term -> term | 719 | App : term -> term -> term |
725 | Abs : (term -> term) -> term. | 720 | Abs : (term -> term) -> term. |
726 ]] | 721 ]] |
727 | 722 |
728 << | 723 << |
729 Error: Non strictly positive occurrence of "term" in "(term -> term) -> term" | 724 Error: Non strictly positive occurrence of "term" in "(term -> term) -> term" |
730 >> | 725 >> |
731 | 726 |
732 We have run afoul of the %\index{strict positivity requirement}\index{positivity requirement}%_strict positivity requirement_ for inductive definitions, which says that the type being defined may not occur to the left of an arrow in the type of a constructor argument. It is important that the type of a constructor is viewed in terms of a series of arguments and a result, since obviously we need recursive occurrences to the lefts of the outermost arrows if we are to have recursive occurrences at all. Our candidate definition above violates the positivity requirement because it involves an argument of type [term -> term], where the type [term] that we are defining appears to the left of an arrow. The candidate type of [App] is fine, however, since every occurrence of [term] is either a constructor argument or the final result type. | 727 We have run afoul of the%\index{strict positivity requirement}\index{positivity requirement}% _strict positivity requirement_ for inductive definitions, which says that the type being defined may not occur to the left of an arrow in the type of a constructor argument. It is important that the type of a constructor is viewed in terms of a series of arguments and a result, since obviously we need recursive occurrences to the lefts of the outermost arrows if we are to have recursive occurrences at all. Our candidate definition above violates the positivity requirement because it involves an argument of type [term -> term], where the type [term] that we are defining appears to the left of an arrow. The candidate type of [App] is fine, however, since every occurrence of [term] is either a constructor argument or the final result type. |
733 | 728 |
734 Why must Coq enforce this restriction? Imagine that our last definition had been accepted, allowing us to write this function: | 729 Why must Coq enforce this restriction? Imagine that our last definition had been accepted, allowing us to write this function: |
735 | 730 |
736 [[ | 731 [[ |
737 Definition uhoh (t : term) : term := | 732 Definition uhoh (t : term) : term := |
771 unit_rect | 766 unit_rect |
772 : forall P : unit -> Type, P tt -> forall u : unit, P u | 767 : forall P : unit -> Type, P tt -> forall u : unit, P u |
773 | 768 |
774 ]] | 769 ]] |
775 | 770 |
776 [unit_rect] gives [P] type [unit -> Type] instead of [unit -> Prop]. [Type] is another universe, like [Set] and [Prop]. In fact, it is a common supertype of both. Later on, we will discuss exactly what the significances of the different universes are. For now, it is just important that we can use [Type] as a sort of meta-universe that may turn out to be either [Set] or [Prop]. We can see the symmetry inherent in the subtyping relationship by printing the definition of another principle that was generated for [unit] automatically: *) | 771 The principle [unit_rect] gives [P] type [unit -> Type] instead of [unit -> Prop]. [Type] is another universe, like [Set] and [Prop]. In fact, it is a common supertype of both. Later on, we will discuss exactly what the significances of the different universes are. For now, it is just important that we can use [Type] as a sort of meta-universe that may turn out to be either [Set] or [Prop]. We can see the symmetry inherent in the subtyping relationship by printing the definition of another principle that was generated for [unit] automatically: *) |
777 | 772 |
778 (* begin hide *) | 773 (* begin hide *) |
779 Print unit_rec. | 774 Print unit_rec. |
780 (* end hide *) | 775 (* end hide *) |
781 (** %\noindent%[Print] [unit_rec.] *) | 776 (** %\noindent%[Print] [unit_rec.] *) |
810 end | 805 end |
811 : forall P : unit -> Type, P tt -> forall u : unit, P u | 806 : forall P : unit -> Type, P tt -> forall u : unit, P u |
812 | 807 |
813 ]] | 808 ]] |
814 | 809 |
815 The only new wrinkle here is the annotations on the [match] expression. This is a %\index{dependent pattern matching}%_dependently typed_ pattern match, because the _type_ of the expression depends on the _value_ being matched on. Of course, for this example, the dependency is degenerate; the value being matched on has type [unit], so it may only take on a single known value, [tt]. We will meet more involved examples later, especially in Part II of the book. | 810 The only new wrinkle here is the annotations on the [match] expression. This is a%\index{dependent pattern matching}% _dependently typed_ pattern match, because the _type_ of the expression depends on the _value_ being matched on. Of course, for this example, the dependency is degenerate; the value being matched on has type [unit], so it may only take on a single known value, [tt]. We will meet more involved examples later, especially in Part II of the book. |
816 | 811 |
817 %\index{type inference}%Type inference for dependent pattern matching is undecidable, which can be proved by reduction from %\index{higher-order unification}%higher-order unification%~\cite{HOU}%. Thus, we often find ourselves needing to annotate our programs in a way that explains dependencies to the type checker. In the example of [unit_rect], we have an %\index{Gallina terms!as}%[as] clause, which binds a name for the discriminee; and a %\index{Gallina terms!return}%[return] clause, which gives a way to compute the [match] result type as a function of the discriminee. | 812 %\index{type inference}%Type inference for dependent pattern matching is undecidable, which can be proved by reduction from %\index{higher-order unification}%higher-order unification%~\cite{HOU}%. Thus, we often find ourselves needing to annotate our programs in a way that explains dependencies to the type checker. In the example of [unit_rect], we have an %\index{Gallina terms!as}%[as] clause, which binds a name for the discriminee; and a %\index{Gallina terms!return}%[return] clause, which gives a way to compute the [match] result type as a function of the discriminee. |
818 | 813 |
819 To prove that [unit_rect] is nothing special, we can reimplement it manually. *) | 814 To prove that [unit_rect] is nothing special, we can reimplement it manually. *) |
820 | 815 |
823 | tt => f | 818 | tt => f |
824 end. | 819 end. |
825 | 820 |
826 (** We rely on Coq's heuristics for inferring [match] annotations, which are not consulted in the pretty-printing of terms. | 821 (** We rely on Coq's heuristics for inferring [match] annotations, which are not consulted in the pretty-printing of terms. |
827 | 822 |
828 We can check the implementation of %\coqdocdefinition{%#<tt>#nat_rect#</tt>#%}% as well: *) | 823 We can check the implementation [nat_rect] as well: *) |
829 | 824 |
830 (* begin hide *) | |
831 Print nat_rect. | 825 Print nat_rect. |
832 (* end hide *) | 826 |
833 (** %\noindent%[Print] %\coqdocdefinition{%#<tt>#nat_rect#</tt>#%}%[.] *) | |
834 | |
835 (** %\hspace{-.05in}\coqdocdefinition{%#<tt>#nat_rect#</tt>#%}% [=] *) | |
836 (** %\vspace{-.05in}% [[ | 827 (** %\vspace{-.05in}% [[ |
828 nat_rect = | |
837 fun (P : nat -> Type) (f : P O) (f0 : forall n : nat, P n -> P (S n)) => | 829 fun (P : nat -> Type) (f : P O) (f0 : forall n : nat, P n -> P (S n)) => |
838 fix F (n : nat) : P n := | 830 fix F (n : nat) : P n := |
839 match n as n0 return (P n0) with | 831 match n as n0 return (P n0) with |
840 | O => f | 832 | O => f |
841 | S n0 => f0 n0 (F n0) | 833 | S n0 => f0 n0 (F n0) |
842 end | 834 end |
843 : forall P : nat -> Type, | 835 : forall P : nat -> Type, |
844 P O -> (forall n : nat, P n -> P (S n)) -> forall n : nat, P n | 836 P O -> (forall n : nat, P n -> P (S n)) -> forall n : nat, P n |
845 ]] | 837 ]] |
846 | 838 |
847 Now we have an actual recursive definition. %\index{Gallina terms!fix}%[fix] expressions are an anonymous form of [Fixpoint], just as [fun] expressions stand for anonymous non-recursive functions. Beyond that, the syntax of [fix] mirrors that of [Fixpoint]. We can understand the definition of %\coqdocdefinition{%#<tt>#nat_rect#</tt>#%}% better by reimplementing [nat_ind] using sections. *) | 839 Now we have an actual recursive definition. Expressions starting with %\index{Gallina terms!fix}%[fix] are anonymous forms of [Fixpoint], just as [fun] expressions stand for anonymous non-recursive functions. Beyond that, the syntax of [fix] mirrors that of [Fixpoint]. We can understand the definition of [nat_rect] better by reimplementing [nat_ind] using sections. *) |
848 | 840 |
849 Section nat_ind'. | 841 Section nat_ind'. |
850 (** First, we have the property of natural numbers that we aim to prove. *) | 842 (** First, we have the property of natural numbers that we aim to prove. *) |
851 | 843 |
852 Variable P : nat -> Prop. | 844 Variable P : nat -> Prop. |
866 | O => O_case | 858 | O => O_case |
867 | S n' => S_case (nat_ind' n') | 859 | S n' => S_case (nat_ind' n') |
868 end. | 860 end. |
869 End nat_ind'. | 861 End nat_ind'. |
870 | 862 |
871 (** Closing the section adds the [Variable]s and [Hypothesis]es as new [fun]-bound arguments to [nat_ind'], and, modulo the use of [Prop] instead of [Type], we end up with the exact same definition that was generated automatically for %\coqdocdefinition{%#<tt>#nat_rect#</tt>#%}%. | 863 (** Closing the section adds the [Variable]s and [Hypothesis]es as new [fun]-bound arguments to [nat_ind'], and, modulo the use of [Prop] instead of [Type], we end up with the exact same definition that was generated automatically for [nat_rect]. |
872 | 864 |
873 %\medskip% | 865 %\medskip% |
874 | 866 |
875 We can also examine the definition of [even_list_mut], which we generated with [Scheme] for a mutually recursive type. *) | 867 We can also examine the definition of [even_list_mut], which we generated with [Scheme] for a mutually recursive type. *) |
876 | 868 |
877 (* begin hide *) | |
878 Print even_list_mut. | 869 Print even_list_mut. |
879 (* end hide *) | |
880 (** %\noindent%[Print] %\coqdocdefinition{%#<tt>#even_list_mut#</tt>#%}%[.] *) | |
881 (** [[ | 870 (** [[ |
882 even_list_mut = | 871 even_list_mut = |
883 fun (P : even_list -> Prop) (P0 : odd_list -> Prop) | 872 fun (P : even_list -> Prop) (P0 : odd_list -> Prop) |
884 (f : P ENil) (f0 : forall (n : nat) (o : odd_list), P0 o -> P (ECons n o)) | 873 (f : P ENil) (f0 : forall (n : nat) (o : odd_list), P0 o -> P (ECons n o)) |
885 (f1 : forall (n : nat) (e : even_list), P e -> P0 (OCons n e)) => | 874 (f1 : forall (n : nat) (e : even_list), P e -> P0 (OCons n e)) => |
986 end. | 975 end. |
987 End All. | 976 End All. |
988 | 977 |
989 (** It will be useful to review the definitions of [True] and [/\], since we will want to write manual proofs of them below. *) | 978 (** It will be useful to review the definitions of [True] and [/\], since we will want to write manual proofs of them below. *) |
990 | 979 |
991 (* begin hide *) | |
992 Print True. | 980 Print True. |
993 (* end hide *) | |
994 (** %\noindent%[Print] %\coqdocinductive{%#<tt>#True#</tt>#%}%[.] *) | |
995 (** [[ | 981 (** [[ |
996 Inductive True : Prop := I : True | 982 Inductive True : Prop := I : True |
997 ]] | 983 ]] |
998 | 984 |
999 That is, [True] is a proposition with exactly one proof, [I], which we may always supply trivially. | 985 That is, [True] is a proposition with exactly one proof, [I], which we may always supply trivially. |
1000 | 986 |
1001 Finding the definition of [/\] takes a little more work. Coq supports user registration of arbitrary parsing rules, and it is such a rule that is letting us write [/\] instead of an application of some inductive type family. We can find the underlying inductive type with the %\index{Vernacular commands!Locate}\coqdockw{%#<tt>#Locate#</tt>#%}% command, whose argument may be a parsing token.%\index{Gallina terms!and}% *) | 987 Finding the definition of [/\] takes a little more work. Coq supports user registration of arbitrary parsing rules, and it is such a rule that is letting us write [/\] instead of an application of some inductive type family. We can find the underlying inductive type with the %\index{Vernacular commands!Locate}%[Locate] command, whose argument may be a parsing token.%\index{Gallina terms!and}% *) |
1002 | 988 |
1003 (* begin hide *) | |
1004 Locate "/\". | 989 Locate "/\". |
1005 (* end hide *) | |
1006 (** %\noindent \coqdockw{Locate}%#<tt>Locate</tt># ["/\".] *) | |
1007 (** [[ | 990 (** [[ |
1008 "A /\ B" := and A B : type_scope (default interpretation) | 991 "A /\ B" := and A B : type_scope (default interpretation) |
1009 ]] | 992 ]] |
1010 *) | 993 *) |
1011 | 994 |
1012 (* begin hide *) | |
1013 Print and. | 995 Print and. |
1014 (* end hide *) | |
1015 (** %\noindent%[Print] %\coqdocinductive{%#<tt>#and#</tt>#%}%[.] *) | |
1016 (** [[ | 996 (** [[ |
1017 Inductive and (A : Prop) (B : Prop) : Prop := conj : A -> B -> A /\ B | 997 Inductive and (A : Prop) (B : Prop) : Prop := conj : A -> B -> A /\ B |
1018 ]] | 998 ]] |
1019 %\vspace{-.1in}% | 999 %\vspace{-.1in}% |
1020 << | 1000 << |
1021 For conj: Arguments A, B are implicit | 1001 For conj: Arguments A, B are implicit |
1022 >> | 1002 >> |
1023 | 1003 |
1024 In addition to the definition of %\coqdocinductive{%#<tt>#and#</tt>#%}% itself, we get information on %\index{implicit arguments}%implicit arguments (and some other information that we omit here). The implicit argument information tells us that we build a proof of a conjunction by calling the constructor [conj] on proofs of the conjuncts, with no need to include the types of those proofs as explicit arguments. | 1004 In addition to the definition of [and] itself, we get information on %\index{implicit arguments}%implicit arguments (and some other information that we omit here). The implicit argument information tells us that we build a proof of a conjunction by calling the constructor [conj] on proofs of the conjuncts, with no need to include the types of those proofs as explicit arguments. |
1025 | 1005 |
1026 %\medskip% | 1006 %\medskip% |
1027 | 1007 |
1028 Now we create a section for our induction principle, following the same basic plan as in the last section of this chapter. *) | 1008 Now we create a section for our induction principle, following the same basic plan as in the last section of this chapter. *) |
1029 | 1009 |
1122 (** Now we begin the proof of the theorem, adding the lemma [plus_S] as a hint. *) | 1102 (** Now we begin the proof of the theorem, adding the lemma [plus_S] as a hint. *) |
1123 | 1103 |
1124 Theorem ntsize_ntsplice : forall tr1 tr2 : nat_tree, ntsize (ntsplice tr1 tr2) | 1104 Theorem ntsize_ntsplice : forall tr1 tr2 : nat_tree, ntsize (ntsplice tr1 tr2) |
1125 = plus (ntsize tr2) (ntsize tr1). | 1105 = plus (ntsize tr2) (ntsize tr1). |
1126 (* begin thide *) | 1106 (* begin thide *) |
1127 (* begin hide *) | |
1128 Hint Rewrite plus_S. | 1107 Hint Rewrite plus_S. |
1129 (* end hide *) | |
1130 (** [Hint] %\coqdockw{%#<tt>#Rewrite#</tt>#%}% [plus_S.] *) | |
1131 | 1108 |
1132 (** We know that the standard induction principle is insufficient for the task, so we need to provide a %\index{tactics!using}%[using] clause for the [induction] tactic to specify our alternate principle. *) | 1109 (** We know that the standard induction principle is insufficient for the task, so we need to provide a %\index{tactics!using}%[using] clause for the [induction] tactic to specify our alternate principle. *) |
1133 | 1110 |
1134 induction tr1 using nat_tree_ind'; crush. | 1111 induction tr1 using nat_tree_ind'; crush. |
1135 | 1112 |
1154 | 1131 |
1155 destruct ls; crush. | 1132 destruct ls; crush. |
1156 | 1133 |
1157 (** We can go further in automating the proof by exploiting the hint mechanism.%\index{Vernacular commands!Hint Extern}% *) | 1134 (** We can go further in automating the proof by exploiting the hint mechanism.%\index{Vernacular commands!Hint Extern}% *) |
1158 | 1135 |
1159 (* begin hide *) | |
1160 Restart. | 1136 Restart. |
1161 (* end hide *) | |
1162 (** %\hspace{-.075in}\coqdockw{%#<tt>#Restart#</tt>#%}%[.] *) | |
1163 | 1137 |
1164 Hint Extern 1 (ntsize (match ?LS with Nil => _ | Cons _ _ => _ end) = _) => | 1138 Hint Extern 1 (ntsize (match ?LS with Nil => _ | Cons _ _ => _ end) = _) => |
1165 destruct LS; crush. | 1139 destruct LS; crush. |
1166 induction tr1 using nat_tree_ind'; crush. | 1140 induction tr1 using nat_tree_ind'; crush. |
1167 Qed. | 1141 Qed. |
1200 | 1174 |
1201 This is the point in the proof where we apply some creativity. We define a function whose utility will become clear soon. *) | 1175 This is the point in the proof where we apply some creativity. We define a function whose utility will become clear soon. *) |
1202 | 1176 |
1203 Definition toProp (b : bool) := if b then True else False. | 1177 Definition toProp (b : bool) := if b then True else False. |
1204 | 1178 |
1205 (** It is worth recalling the difference between the lowercase and uppercase versions of truth and falsehood: [True] and [False] are logical propositions, while [true] and [false] are boolean values that we can case-analyze. We have defined [toProp] such that our conclusion of [False] is computationally equivalent to [toProp false]. Thus, the %\index{tactics!change}\coqdockw{%#<tt>#change#</tt>#%}% tactic will let us change the conclusion to [toProp false]. The general form %\coqdockw{%#<tt>#change#</tt>#%}% [e] replaces the conclusion with [e], whenever Coq's built-in computation rules suffice to establish the equivalence of [e] with the original conclusion. *) | 1179 (** It is worth recalling the difference between the lowercase and uppercase versions of truth and falsehood: [True] and [False] are logical propositions, while [true] and [false] are boolean values that we can case-analyze. We have defined [toProp] such that our conclusion of [False] is computationally equivalent to [toProp false]. Thus, the %\index{tactics!change}%[change] tactic will let us change the conclusion to [toProp false]. The general form [change e] replaces the conclusion with [e], whenever Coq's built-in computation rules suffice to establish the equivalence of [e] with the original conclusion. *) |
1206 | 1180 |
1207 (* begin hide *) | |
1208 change (toProp false). | 1181 change (toProp false). |
1209 (* end hide *) | |
1210 (** %\hspace{-.075in}\coqdockw{%#<tt>#change#</tt>#%}% [(][toProp false).] *) | |
1211 (** [[ | 1182 (** [[ |
1212 H : true = false | 1183 H : true = false |
1213 ============================ | 1184 ============================ |
1214 toProp false | 1185 toProp false |
1215 | 1186 |
1247 We can perform a similar manual proof of injectivity of the constructor [S]. I leave a walk-through of the details to curious readers who want to run the proof script interactively. *) | 1218 We can perform a similar manual proof of injectivity of the constructor [S]. I leave a walk-through of the details to curious readers who want to run the proof script interactively. *) |
1248 | 1219 |
1249 Theorem S_inj' : forall n m : nat, S n = S m -> n = m. | 1220 Theorem S_inj' : forall n m : nat, S n = S m -> n = m. |
1250 (* begin thide *) | 1221 (* begin thide *) |
1251 intros n m H. | 1222 intros n m H. |
1252 (* begin hide *) | |
1253 change (pred (S n) = pred (S m)). | 1223 change (pred (S n) = pred (S m)). |
1254 (* end hide *) | |
1255 (** %\hspace{-.075in}\coqdockw{%#<tt>#change#</tt>#%}% [(][pred (][S n) = pred (][S m)).] *) | |
1256 | |
1257 rewrite H. | 1224 rewrite H. |
1258 reflexivity. | 1225 reflexivity. |
1259 Qed. | 1226 Qed. |
1260 (* end thide *) | 1227 (* end thide *) |
1261 | 1228 |
1262 (** The key piece of creativity in this theorem comes in the use of the natural number predecessor function [pred]. Embodied in the implementation of %\coqdockw{%#<tt>#injectivity#</tt>#%}% is a generic recipe for writing such type-specific functions. | 1229 (** The key piece of creativity in this theorem comes in the use of the natural number predecessor function [pred]. Embodied in the implementation of [injection] is a generic recipe for writing such type-specific functions. |
1263 | 1230 |
1264 The examples in this section illustrate an important aspect of the design philosophy behind Coq. We could certainly design a Gallina replacement that built in rules for constructor discrimination and injectivity, but a simpler alternative is to include a few carefully chosen rules that enable the desired reasoning patterns and many others. A key benefit of this philosophy is that the complexity of proof checking is minimized, which bolsters our confidence that proved theorems are really true. *) | 1231 The examples in this section illustrate an important aspect of the design philosophy behind Coq. We could certainly design a Gallina replacement that built in rules for constructor discrimination and injectivity, but a simpler alternative is to include a few carefully chosen rules that enable the desired reasoning patterns and many others. A key benefit of this philosophy is that the complexity of proof checking is minimized, which bolsters our confidence that proved theorems are really true. *) |