comparison src/Subset.v @ 212:3227be370687

Ported Subset
author Adam Chlipala <adamc@hcoop.net>
date Mon, 09 Nov 2009 15:43:56 -0500
parents cbf2f74a5130
children c4b1c0de7af9
comparison
equal deleted inserted replaced
211:d06726f49bc6 212:3227be370687
26 (** * Introducing Subset Types *) 26 (** * Introducing Subset Types *)
27 27
28 (** Let us consider several ways of implementing the natural number predecessor function. We start by displaying the definition from the standard library: *) 28 (** Let us consider several ways of implementing the natural number predecessor function. We start by displaying the definition from the standard library: *)
29 29
30 Print pred. 30 Print pred.
31 (** [[ 31 (** %\vspace{-.15in}% [[
32
33 pred = fun n : nat => match n with 32 pred = fun n : nat => match n with
34 | 0 => 0 33 | 0 => 0
35 | S u => u 34 | S u => u
36 end 35 end
37 : nat -> nat 36 : nat -> nat
38 ]] *) 37
39 38 ]]
40 (** We can use a new command, [Extraction], to produce an OCaml version of this function. *) 39
40 We can use a new command, [Extraction], to produce an OCaml version of this function. *)
41 41
42 Extraction pred. 42 Extraction pred.
43 43
44 (** %\begin{verbatim} 44 (** %\begin{verbatim}
45 (** val pred : nat -> nat **) 45 (** val pred : nat -> nat **)
62 Lemma zgtz : 0 > 0 -> False. 62 Lemma zgtz : 0 > 0 -> False.
63 crush. 63 crush.
64 Qed. 64 Qed.
65 65
66 Definition pred_strong1 (n : nat) : n > 0 -> nat := 66 Definition pred_strong1 (n : nat) : n > 0 -> nat :=
67 match n return (n > 0 -> nat) with 67 match n with
68 | O => fun pf : 0 > 0 => match zgtz pf with end 68 | O => fun pf : 0 > 0 => match zgtz pf with end
69 | S n' => fun _ => n' 69 | S n' => fun _ => n'
70 end. 70 end.
71 71
72 (** We expand the type of [pred] to include a %\textit{%#<i>#proof#</i>#%}% that its argument [n] is greater than 0. When [n] is 0, we use the proof to derive a contradiction, which we can use to build a value of any type via a vacuous pattern match. When [n] is a successor, we have no need for the proof and just return the answer. The proof argument can be said to have a %\textit{%#<i>#dependent#</i>#%}% type, because its type depends on the %\textit{%#<i>#value#</i>#%}% of the argument [n]. 72 (** We expand the type of [pred] to include a %\textit{%#<i>#proof#</i>#%}% that its argument [n] is greater than 0. When [n] is 0, we use the proof to derive a contradiction, which we can use to build a value of any type via a vacuous pattern match. When [n] is a successor, we have no need for the proof and just return the answer. The proof argument can be said to have a %\textit{%#<i>#dependent#</i>#%}% type, because its type depends on the %\textit{%#<i>#value#</i>#%}% of the argument [n].
73 73
74 There are two aspects of the definition of [pred_strong1] that may be surprising. First, we took advantage of [Definition]'s syntactic sugar for defining function arguments in the case of [n], but we bound the proofs later with explicit [fun] expressions. Second, there is the [return] clause for the [match], which we saw briefly in Chapter 2. Let us see what happens if we write this function in the way that at first seems most natural. *) 74 One aspects in particular of the definition of [pred_strong1] that may be surprising. We took advantage of [Definition]'s syntactic sugar for defining function arguments in the case of [n], but we bound the proofs later with explicit [fun] expressions. Let us see what happens if we write this function in the way that at first seems most natural.
75 75
76 (** [[ 76 [[
77 Definition pred_strong1' (n : nat) (pf : n > 0) : nat := 77 Definition pred_strong1' (n : nat) (pf : n > 0) : nat :=
78 match n with 78 match n with
79 | O => match zgtz pf with end 79 | O => match zgtz pf with end
80 | S n' => n' 80 | S n' => n'
81 end. 81 end.
82 82
83 [[
84 Error: In environment 83 Error: In environment
85 n : nat 84 n : nat
86 pf : n > 0 85 pf : n > 0
87 The term "pf" has type "n > 0" while it is expected to have type 86 The term "pf" has type "n > 0" while it is expected to have type
88 "0 > 0" 87 "0 > 0"
88
89 ]] 89 ]]
90 90
91 The term [zgtz pf] fails to type-check. Somehow the type checker has failed to take into account information that follows from which [match] branch that term appears in. The problem is that, by default, [match] does not let us use such implied information. To get refined typing, we must always add special [match] annotations. 91 The term [zgtz pf] fails to type-check. Somehow the type checker has failed to take into account information that follows from which [match] branch that term appears in. The problem is that, by default, [match] does not let us use such implied information. To get refined typing, we must always rely on [match] annotations, either written explicitly or inferred.
92 92
93 In this case, we must use a [return] annotation to declare the relationship between the %\textit{%#<i>#value#</i>#%}% of the [match] discriminee and the %\textit{%#<i>#type#</i>#%}% of the result. There is no annotation that lets us declare a relationship between the discriminee and the type of a variable that is already in scope; hence, we delay the binding of [pf], so that we can use the [return] annotation to express the needed relationship. 93 In this case, we must use a [return] annotation to declare the relationship between the %\textit{%#<i>#value#</i>#%}% of the [match] discriminee and the %\textit{%#<i>#type#</i>#%}% of the result. There is no annotation that lets us declare a relationship between the discriminee and the type of a variable that is already in scope; hence, we delay the binding of [pf], so that we can use the [return] annotation to express the needed relationship.
94 94
95 Why does Coq not infer this relationship for us? Certainly, it is not hard to imagine heuristics that would handle this particular case and many others. In general, however, the inference problem is undecidable. The known undecidable problem of %\textit{%#<i>#higher-order unification#</i>#%}% reduces to the [match] type inference problem. Over time, Coq is enhanced with more and more heuristics to get around this problem, but there must always exist [match]es whose types Coq cannot infer without annotations. 95 We are lucky that Coq's heuristics infer the [return] clause (specifically, [return n > 0 -> nat]) for us in this case. In general, however, the inference problem is undecidable. The known undecidable problem of %\textit{%#<i>#higher-order unification#</i>#%}% reduces to the [match] type inference problem. Over time, Coq is enhanced with more and more heuristics to get around this problem, but there must always exist [match]es whose types Coq cannot infer without annotations.
96 96
97 Let us now take a look at the OCaml code Coq generates for [pred_strong1]. *) 97 Let us now take a look at the OCaml code Coq generates for [pred_strong1]. *)
98 98
99 Extraction pred_strong1. 99 Extraction pred_strong1.
100 100
117 (** The proof argument has disappeared! We get exactly the OCaml code we would have written manually. This is our first demonstration of the main technically interesting feature of Coq program extraction: program components of type [Prop] are erased systematically. 117 (** The proof argument has disappeared! We get exactly the OCaml code we would have written manually. This is our first demonstration of the main technically interesting feature of Coq program extraction: program components of type [Prop] are erased systematically.
118 118
119 We can reimplement our dependently-typed [pred] based on %\textit{%#<i>#subset types#</i>#%}%, defined in the standard library with the type family [sig]. *) 119 We can reimplement our dependently-typed [pred] based on %\textit{%#<i>#subset types#</i>#%}%, defined in the standard library with the type family [sig]. *)
120 120
121 Print sig. 121 Print sig.
122 (** [[ 122 (** %\vspace{-.15in}% [[
123
124 Inductive sig (A : Type) (P : A -> Prop) : Type := 123 Inductive sig (A : Type) (P : A -> Prop) : Type :=
125 exist : forall x : A, P x -> sig P 124 exist : forall x : A, P x -> sig P
126 For sig: Argument A is implicit 125 For sig: Argument A is implicit
127 For exist: Argument A is implicit 126 For exist: Argument A is implicit
127
128 ]] 128 ]]
129 129
130 [sig] is a Curry-Howard twin of [ex], except that [sig] is in [Type], while [ex] is in [Prop]. That means that [sig] values can survive extraction, while [ex] proofs will always be erased. The actual details of extraction of [sig]s are more subtle, as we will see shortly. 130 [sig] is a Curry-Howard twin of [ex], except that [sig] is in [Type], while [ex] is in [Prop]. That means that [sig] values can survive extraction, while [ex] proofs will always be erased. The actual details of extraction of [sig]s are more subtle, as we will see shortly.
131 131
132 We rewrite [pred_strong1], using some syntactic sugar for subset types. *) 132 We rewrite [pred_strong1], using some syntactic sugar for subset types. *)
133 133
134 Locate "{ _ : _ | _ }". 134 Locate "{ _ : _ | _ }".
135 (** [[ 135 (** %\vspace{-.15in}% [[
136
137 Notation Scope 136 Notation Scope
138 "{ x : A | P }" := sig (fun x : A => P) 137 "{ x : A | P }" := sig (fun x : A => P)
139 : type_scope 138 : type_scope
140 (default interpretation) 139 (default interpretation)
141 ]] *) 140 ]] *)
169 We can continue on in the process of refining [pred]'s type. Let us change its result type to capture that the output is really the predecessor of the input. *) 168 We can continue on in the process of refining [pred]'s type. Let us change its result type to capture that the output is really the predecessor of the input. *)
170 169
171 Definition pred_strong3 (s : {n : nat | n > 0}) : {m : nat | proj1_sig s = S m} := 170 Definition pred_strong3 (s : {n : nat | n > 0}) : {m : nat | proj1_sig s = S m} :=
172 match s return {m : nat | proj1_sig s = S m} with 171 match s return {m : nat | proj1_sig s = S m} with
173 | exist 0 pf => match zgtz pf with end 172 | exist 0 pf => match zgtz pf with end
174 | exist (S n') _ => exist _ n' (refl_equal _) 173 | exist (S n') pf => exist _ n' (refl_equal _)
175 end. 174 end.
176 175
177 (** The function [proj1_sig] extracts the base value from a subset type. Besides the use of that function, the only other new thing is the use of the [exist] constructor to build a new [sig] value, and the details of how to do that follow from the output of our earlier [Print] command. 176 (** The function [proj1_sig] extracts the base value from a subset type. Besides the use of that function, the only other new thing is the use of the [exist] constructor to build a new [sig] value, and the details of how to do that follow from the output of our earlier [Print] command. It also turns out that we need to include an explicit [return] clause here, since Coq's heuristics are not smart enough to propagate the result type that we wrote earlier.
178 177
179 By now, the reader is probably ready to believe that the new [pred_strong] leads to the same OCaml code as we have seen several times so far, and Coq does not disappoint. *) 178 By now, the reader is probably ready to believe that the new [pred_strong] leads to the same OCaml code as we have seen several times so far, and Coq does not disappoint. *)
180 179
181 Extraction pred_strong3. 180 Extraction pred_strong3.
182 181
198 197
199 We have managed to reach a type that is, in a formal sense, the most expressive possible for [pred]. Any other implementation of the same type must have the same input-output behavior. However, there is still room for improvement in making this kind of code easier to write. Here is a version that takes advantage of tactic-based theorem proving. We switch back to passing a separate proof argument instead of using a subset type for the function's input, because this leads to cleaner code. *) 198 We have managed to reach a type that is, in a formal sense, the most expressive possible for [pred]. Any other implementation of the same type must have the same input-output behavior. However, there is still room for improvement in making this kind of code easier to write. Here is a version that takes advantage of tactic-based theorem proving. We switch back to passing a separate proof argument instead of using a subset type for the function's input, because this leads to cleaner code. *)
200 199
201 Definition pred_strong4 (n : nat) : n > 0 -> {m : nat | n = S m}. 200 Definition pred_strong4 (n : nat) : n > 0 -> {m : nat | n = S m}.
202 refine (fun n => 201 refine (fun n =>
203 match n return (n > 0 -> {m : nat | n = S m}) with 202 match n with
204 | O => fun _ => False_rec _ _ 203 | O => fun _ => False_rec _ _
205 | S n' => fun _ => exist _ n' _ 204 | S n' => fun _ => exist _ n' _
206 end). 205 end).
206
207 (* begin thide *) 207 (* begin thide *)
208 (** We build [pred_strong4] using tactic-based proving, beginning with a [Definition] command that ends in a period before a definition is given. Such a command enters the interactive proving mode, with the type given for the new identifier as our proof goal. We do most of the work with the [refine] tactic, to which we pass a partial "proof" of the type we are trying to prove. There may be some pieces left to fill in, indicated by underscores. Any underscore that Coq cannot reconstruct with type inference is added as a proof subgoal. In this case, we have two subgoals: 208 (** We build [pred_strong4] using tactic-based proving, beginning with a [Definition] command that ends in a period before a definition is given. Such a command enters the interactive proving mode, with the type given for the new identifier as our proof goal. We do most of the work with the [refine] tactic, to which we pass a partial "proof" of the type we are trying to prove. There may be some pieces left to fill in, indicated by underscores. Any underscore that Coq cannot reconstruct with type inference is added as a proof subgoal. In this case, we have two subgoals:
209 209
210 [[ 210 [[
211
212 2 subgoals 211 2 subgoals
213 212
214 n : nat 213 n : nat
215 _ : 0 > 0 214 _ : 0 > 0
216 ============================ 215 ============================
217 False 216 False
218 ]]
219
220 [[
221 217
222 subgoal 2 is: 218 subgoal 2 is:
223 S n' = S n' 219 S n' = S n'
220
224 ]] 221 ]]
225 222
226 We can see that the first subgoal comes from the second underscore passed to [False_rec], and the second subgoal comes from the second underscore passed to [exist]. In the first case, we see that, though we bound the proof variable with an underscore, it is still available in our proof context. It is hard to refer to underscore-named variables in manual proofs, but automation makes short work of them. Both subgoals are easy to discharge that way, so let us back up and ask to prove all subgoals automatically. *) 223 We can see that the first subgoal comes from the second underscore passed to [False_rec], and the second subgoal comes from the second underscore passed to [exist]. In the first case, we see that, though we bound the proof variable with an underscore, it is still available in our proof context. It is hard to refer to underscore-named variables in manual proofs, but automation makes short work of them. Both subgoals are easy to discharge that way, so let us back up and ask to prove all subgoals automatically. *)
227 224
228 Undo. 225 Undo.
229 refine (fun n => 226 refine (fun n =>
230 match n return (n > 0 -> {m : nat | n = S m}) with 227 match n with
231 | O => fun _ => False_rec _ _ 228 | O => fun _ => False_rec _ _
232 | S n' => fun _ => exist _ n' _ 229 | S n' => fun _ => exist _ n' _
233 end); crush. 230 end); crush.
234 (* end thide *) 231 (* end thide *)
235 Defined. 232 Defined.
236 233
237 (** We end the "proof" with [Defined] instead of [Qed], so that the definition we constructed remains visible. This contrasts to the case of ending a proof with [Qed], where the details of the proof are hidden afterward. Let us see what our proof script constructed. *) 234 (** We end the "proof" with [Defined] instead of [Qed], so that the definition we constructed remains visible. This contrasts to the case of ending a proof with [Qed], where the details of the proof are hidden afterward. Let us see what our proof script constructed. *)
238 235
239 Print pred_strong4. 236 Print pred_strong4.
240 (** [[ 237 (** %\vspace{-.15in}% [[
241
242 pred_strong4 = 238 pred_strong4 =
243 fun n : nat => 239 fun n : nat =>
244 match n as n0 return (n0 > 0 -> {m : nat | n0 = S m}) with 240 match n as n0 return (n0 > 0 -> {m : nat | n0 = S m}) with
245 | 0 => 241 | 0 =>
246 fun _ : 0 > 0 => 242 fun _ : 0 > 0 =>
252 | S n' => 248 | S n' =>
253 fun _ : S n' > 0 => 249 fun _ : S n' > 0 =>
254 exist (fun m : nat => S n' = S m) n' (refl_equal (S n')) 250 exist (fun m : nat => S n' = S m) n' (refl_equal (S n'))
255 end 251 end
256 : forall n : nat, n > 0 -> {m : nat | n = S m} 252 : forall n : nat, n > 0 -> {m : nat | n = S m}
253
257 ]] 254 ]]
258 255
259 We see the code we entered, with some proofs filled in. The first proof obligation, the second argument to [False_rec], is filled in with a nasty-looking proof term that we can be glad we did not enter by hand. The second proof obligation is a simple reflexivity proof. 256 We see the code we entered, with some proofs filled in. The first proof obligation, the second argument to [False_rec], is filled in with a nasty-looking proof term that we can be glad we did not enter by hand. The second proof obligation is a simple reflexivity proof.
260 257
261 We are almost done with the ideal implementation of dependent predecessor. We can use Coq's syntax extension facility to arrive at code with almost no complexity beyond a Haskell or ML program with a complete specification in a comment. *) 258 We are almost done with the ideal implementation of dependent predecessor. We can use Coq's syntax extension facility to arrive at code with almost no complexity beyond a Haskell or ML program with a complete specification in a comment. *)
263 Notation "!" := (False_rec _ _). 260 Notation "!" := (False_rec _ _).
264 Notation "[ e ]" := (exist _ e _). 261 Notation "[ e ]" := (exist _ e _).
265 262
266 Definition pred_strong5 (n : nat) : n > 0 -> {m : nat | n = S m}. 263 Definition pred_strong5 (n : nat) : n > 0 -> {m : nat | n = S m}.
267 refine (fun n => 264 refine (fun n =>
268 match n return (n > 0 -> {m : nat | n = S m}) with 265 match n with
269 | O => fun _ => ! 266 | O => fun _ => !
270 | S n' => fun _ => [n'] 267 | S n' => fun _ => [n']
271 end); crush. 268 end); crush.
272 Defined. 269 Defined.
273 270
271 (** One other alternative is worth demonstrating. Recent Coq versions include a facility called [Program] that streamlines this style of definition. Here is a complete implementation using [Program]. *)
272
273 Obligation Tactic := crush.
274
275 Program Definition pred_strong6 (n : nat) (_ : n > 0) : {m : nat | n = S m} :=
276 match n with
277 | O => _
278 | S n' => n'
279 end.
280
281 (** Printing the resulting definition of [pred_strong6] yields a term very similar to what we built with [refine]. [Program] can save time in writing programs that use subset types. Nonetheless, [refine] is often just as effective, and [refine] gives you more control over the form the final term takes, which can be useful when you want to prove additional theorems about your definition. [Program] will sometimes insert type casts that can complicate theorem-proving. *)
282
274 283
275 (** * Decidable Proposition Types *) 284 (** * Decidable Proposition Types *)
276 285
277 (** There is another type in the standard library which captures the idea of program values that indicate which of two propositions is true. *) 286 (** There is another type in the standard library which captures the idea of program values that indicate which of two propositions is true. *)
278 287
279 Print sumbool. 288 Print sumbool.
280 (** [[ 289 (** %\vspace{-.15in}% [[
281
282 Inductive sumbool (A : Prop) (B : Prop) : Set := 290 Inductive sumbool (A : Prop) (B : Prop) : Set :=
283 left : A -> {A} + {B} | right : B -> {A} + {B} 291 left : A -> {A} + {B} | right : B -> {A} + {B}
284 For left: Argument A is implicit 292 For left: Argument A is implicit
285 For right: Argument B is implicit 293 For right: Argument B is implicit
286 ]] *) 294
287 295 ]]
288 (** We can define some notations to make working with [sumbool] more convenient. *) 296
297 We can define some notations to make working with [sumbool] more convenient. *)
289 298
290 Notation "'Yes'" := (left _ _). 299 Notation "'Yes'" := (left _ _).
291 Notation "'No'" := (right _ _). 300 Notation "'No'" := (right _ _).
292 Notation "'Reduce' x" := (if x then Yes else No) (at level 50). 301 Notation "'Reduce' x" := (if x then Yes else No) (at level 50).
293 302
294 (** The [Reduce] notation is notable because it demonstrates how [if] is overloaded in Coq. The [if] form actually works when the test expression has any two-constructor inductive type. Moreover, in the [then] and [else] branches, the appropriate constructor arguments are bound. This is important when working with [sumbool]s, when we want to have the proof stored in the test expression available when proving the proof obligations generated in the appropriate branch. 303 (** The [Reduce] notation is notable because it demonstrates how [if] is overloaded in Coq. The [if] form actually works when the test expression has any two-constructor inductive type. Moreover, in the [then] and [else] branches, the appropriate constructor arguments are bound. This is important when working with [sumbool]s, when we want to have the proof stored in the test expression available when proving the proof obligations generated in the appropriate branch.
295 304
296 Now we can write [eq_nat_dec], which compares two natural numbers, returning either a proof of their equality or a proof of their inequality. *) 305 Now we can write [eq_nat_dec], which compares two natural numbers, returning either a proof of their equality or a proof of their inequality. *)
297 306
298 Definition eq_nat_dec (n m : nat) : {n = m} + {n <> m}. 307 Definition eq_nat_dec (n m : nat) : {n = m} + {n <> m}.
299 refine (fix f (n m : nat) {struct n} : {n = m} + {n <> m} := 308 refine (fix f (n m : nat) : {n = m} + {n <> m} :=
300 match n, m return {n = m} + {n <> m} with 309 match n, m with
301 | O, O => Yes 310 | O, O => Yes
302 | S n', S m' => Reduce (f n' m') 311 | S n', S m' => Reduce (f n' m')
303 | _, _ => No 312 | _, _ => No
304 end); congruence. 313 end); congruence.
305 Defined. 314 Defined.
384 Variable A : Set. 393 Variable A : Set.
385 Variable A_eq_dec : forall x y : A, {x = y} + {x <> y}. 394 Variable A_eq_dec : forall x y : A, {x = y} + {x <> y}.
386 395
387 (** The final function is easy to write using the techniques we have developed so far. *) 396 (** The final function is easy to write using the techniques we have developed so far. *)
388 397
389 Definition In_dec : forall (x : A) (ls : list A), {In x ls} + { ~In x ls}. 398 Definition In_dec : forall (x : A) (ls : list A), {In x ls} + {~ In x ls}.
390 refine (fix f (x : A) (ls : list A) {struct ls} 399 refine (fix f (x : A) (ls : list A) : {In x ls} + {~ In x ls} :=
391 : {In x ls} + { ~In x ls} := 400 match ls with
392 match ls return {In x ls} + { ~In x ls} with
393 | nil => No 401 | nil => No
394 | x' :: ls' => A_eq_dec x x' || f x ls' 402 | x' :: ls' => A_eq_dec x x' || f x ls'
395 end); crush. 403 end); crush.
396 Qed. 404 Qed.
397 End In_dec. 405 End In_dec.
438 Notation "??" := (Unknown _). 446 Notation "??" := (Unknown _).
439 Notation "[[ x ]]" := (Found _ x _). 447 Notation "[[ x ]]" := (Found _ x _).
440 448
441 (** Now our next version of [pred] is trivial to write. *) 449 (** Now our next version of [pred] is trivial to write. *)
442 450
443 Definition pred_strong6 (n : nat) : {{m | n = S m}}. 451 Definition pred_strong7 (n : nat) : {{m | n = S m}}.
444 refine (fun n => 452 refine (fun n =>
445 match n return {{m | n = S m}} with 453 match n with
446 | O => ?? 454 | O => ??
447 | S n' => [[n']] 455 | S n' => [[n']]
448 end); trivial. 456 end); trivial.
449 Defined. 457 Defined.
450 458
451 (** Because we used [maybe], one valid implementation of the type we gave [pred_strong6] would return [??] in every case. We can strengthen the type to rule out such vacuous implementations, and the type family [sumor] from the standard library provides the easiest starting point. For type [A] and proposition [B], [A + {B}] desugars to [sumor A B], whose values are either values of [A] or proofs of [B]. *) 459 (** Because we used [maybe], one valid implementation of the type we gave [pred_strong7] would return [??] in every case. We can strengthen the type to rule out such vacuous implementations, and the type family [sumor] from the standard library provides the easiest starting point. For type [A] and proposition [B], [A + {B}] desugars to [sumor A B], whose values are either values of [A] or proofs of [B]. *)
452 460
453 Print sumor. 461 Print sumor.
454 (** [[ 462 (** %\vspace{-.15in}% [[
455
456 Inductive sumor (A : Type) (B : Prop) : Type := 463 Inductive sumor (A : Type) (B : Prop) : Type :=
457 inleft : A -> A + {B} | inright : B -> A + {B} 464 inleft : A -> A + {B} | inright : B -> A + {B}
458 For inleft: Argument A is implicit 465 For inleft: Argument A is implicit
459 For inright: Argument B is implicit 466 For inright: Argument B is implicit
460 ]] *) 467 ]] *)
464 Notation "!!" := (inright _ _). 471 Notation "!!" := (inright _ _).
465 Notation "[[[ x ]]]" := (inleft _ [x]). 472 Notation "[[[ x ]]]" := (inleft _ [x]).
466 473
467 (** Now we are ready to give the final version of possibly-failing predecessor. The [sumor]-based type that we use is maximally expressive; any implementation of the type has the same input-output behavior. *) 474 (** Now we are ready to give the final version of possibly-failing predecessor. The [sumor]-based type that we use is maximally expressive; any implementation of the type has the same input-output behavior. *)
468 475
469 Definition pred_strong7 (n : nat) : {m : nat | n = S m} + {n = 0}. 476 Definition pred_strong8 (n : nat) : {m : nat | n = S m} + {n = 0}.
470 refine (fun n => 477 refine (fun n =>
471 match n return {m : nat | n = S m} + {n = 0} with 478 match n with
472 | O => !! 479 | O => !!
473 | S n' => [[[n']]] 480 | S n' => [[[n']]]
474 end); trivial. 481 end); trivial.
475 Defined. 482 Defined.
476 483
489 496
490 This notation is very helpful for composing richly-typed procedures. For instance, here is a very simple implementation of a function to take the predecessors of two naturals at once. *) 497 This notation is very helpful for composing richly-typed procedures. For instance, here is a very simple implementation of a function to take the predecessors of two naturals at once. *)
491 498
492 Definition doublePred (n1 n2 : nat) : {{p | n1 = S (fst p) /\ n2 = S (snd p)}}. 499 Definition doublePred (n1 n2 : nat) : {{p | n1 = S (fst p) /\ n2 = S (snd p)}}.
493 refine (fun n1 n2 => 500 refine (fun n1 n2 =>
494 m1 <- pred_strong6 n1; 501 m1 <- pred_strong7 n1;
495 m2 <- pred_strong6 n2; 502 m2 <- pred_strong7 n2;
496 [[(m1, m2)]]); tauto. 503 [[(m1, m2)]]); tauto.
497 Defined. 504 Defined.
498 505
499 (** We can build a [sumor] version of the "bind" notation and use it to write a similarly straightforward version of this function. *) 506 (** We can build a [sumor] version of the "bind" notation and use it to write a similarly straightforward version of this function. *)
500 507
506 end) 513 end)
507 (right associativity, at level 60). 514 (right associativity, at level 60).
508 515
509 (** printing * $\times$ *) 516 (** printing * $\times$ *)
510 517
511 Definition doublePred' (n1 n2 : nat) : {p : nat * nat | n1 = S (fst p) /\ n2 = S (snd p)} 518 Definition doublePred' (n1 n2 : nat)
519 : {p : nat * nat | n1 = S (fst p) /\ n2 = S (snd p)}
512 + {n1 = 0 \/ n2 = 0}. 520 + {n1 = 0 \/ n2 = 0}.
513 refine (fun n1 n2 => 521 refine (fun n1 n2 =>
514 m1 <-- pred_strong7 n1; 522 m1 <-- pred_strong8 n1;
515 m2 <-- pred_strong7 n2; 523 m2 <-- pred_strong8 n2;
516 [[[(m1, m2)]]]); tauto. 524 [[[(m1, m2)]]]); tauto.
517 Defined. 525 Defined.
518 526
519 527
520 (** * A Type-Checking Example *) 528 (** * A Type-Checking Example *)
550 (* begin thide *) 558 (* begin thide *)
551 Definition eq_type_dec : forall t1 t2 : type, {t1 = t2} + {t1 <> t2}. 559 Definition eq_type_dec : forall t1 t2 : type, {t1 = t2} + {t1 <> t2}.
552 decide equality. 560 decide equality.
553 Defined. 561 Defined.
554 562
555 (** Another notation complements the monadic notation for [maybe] that we defined earlier. Sometimes we want to be to include "assertions" in our procedures. That is, we want to run a decision procedure and fail if it fails; otherwise, we want to continue, with the proof that it produced made available to us. This infix notation captures that, for a procedure that returns an arbitrary two-constructor type. *) 563 (** Another notation complements the monadic notation for [maybe] that we defined earlier. Sometimes we want to include "assertions" in our procedures. That is, we want to run a decision procedure and fail if it fails; otherwise, we want to continue, with the proof that it produced made available to us. This infix notation captures that idea, for a procedure that returns an arbitrary two-constructor type. *)
556 564
557 Notation "e1 ;; e2" := (if e1 then e2 else ??) 565 Notation "e1 ;; e2" := (if e1 then e2 else ??)
558 (right associativity, at level 60). 566 (right associativity, at level 60).
559 567
560 (** With that notation defined, we can implement a [typeCheck] function, whose code is only more complex than what we would write in ML because it needs to include some extra type annotations. Every [[[e]]] expression adds a [hasType] proof obligation, and [crush] makes short work of them when we add [hasType]'s constructors as hints. *) 568 (** With that notation defined, we can implement a [typeCheck] function, whose code is only more complex than what we would write in ML because it needs to include some extra type annotations. Every [[[e]]] expression adds a [hasType] proof obligation, and [crush] makes short work of them when we add [hasType]'s constructors as hints. *)
563 Definition typeCheck (e : exp) : {{t | hasType e t}}. 571 Definition typeCheck (e : exp) : {{t | hasType e t}}.
564 (* begin thide *) 572 (* begin thide *)
565 Hint Constructors hasType. 573 Hint Constructors hasType.
566 574
567 refine (fix F (e : exp) : {{t | hasType e t}} := 575 refine (fix F (e : exp) : {{t | hasType e t}} :=
568 match e return {{t | hasType e t}} with 576 match e with
569 | Nat _ => [[TNat]] 577 | Nat _ => [[TNat]]
570 | Plus e1 e2 => 578 | Plus e1 e2 =>
571 t1 <- F e1; 579 t1 <- F e1;
572 t2 <- F e2; 580 t2 <- F e2;
573 eq_type_dec t1 TNat;; 581 eq_type_dec t1 TNat;;
585 Defined. 593 Defined.
586 594
587 (** Despite manipulating proofs, our type checker is easy to run. *) 595 (** Despite manipulating proofs, our type checker is easy to run. *)
588 596
589 Eval simpl in typeCheck (Nat 0). 597 Eval simpl in typeCheck (Nat 0).
590 (** [[ 598 (** %\vspace{-.15in}% [[
591
592 = [[TNat]] 599 = [[TNat]]
593 : {{t | hasType (Nat 0) t}} 600 : {{t | hasType (Nat 0) t}}
594 ]] *) 601 ]] *)
595 602
596 Eval simpl in typeCheck (Plus (Nat 1) (Nat 2)). 603 Eval simpl in typeCheck (Plus (Nat 1) (Nat 2)).
597 (** [[ 604 (** %\vspace{-.15in}% [[
598
599 = [[TNat]] 605 = [[TNat]]
600 : {{t | hasType (Plus (Nat 1) (Nat 2)) t}} 606 : {{t | hasType (Plus (Nat 1) (Nat 2)) t}}
601 ]] *) 607 ]] *)
602 608
603 Eval simpl in typeCheck (Plus (Nat 1) (Bool false)). 609 Eval simpl in typeCheck (Plus (Nat 1) (Bool false)).
604 (** [[ 610 (** %\vspace{-.15in}% [[
605
606 = ?? 611 = ??
607 : {{t | hasType (Plus (Nat 1) (Bool false)) t}} 612 : {{t | hasType (Plus (Nat 1) (Bool false)) t}}
608 ]] *) 613 ]] *)
609 614
610 (** The type-checker also extracts to some reasonable OCaml code. *) 615 (** The type-checker also extracts to some reasonable OCaml code. *)
698 Qed. 703 Qed.
699 704
700 (** Now we can define the type-checker. Its type expresses that it only fails on untypable expressions. *) 705 (** Now we can define the type-checker. Its type expresses that it only fails on untypable expressions. *)
701 706
702 (* end thide *) 707 (* end thide *)
703 Definition typeCheck' (e : exp) : {t : type | hasType e t} + {forall t, ~hasType e t}. 708 Definition typeCheck' (e : exp) : {t : type | hasType e t} + {forall t, ~ hasType e t}.
704 (* begin thide *) 709 (* begin thide *)
705 Hint Constructors hasType. 710 Hint Constructors hasType.
706 (** We register all of the typing rules as hints. *) 711 (** We register all of the typing rules as hints. *)
707 712
708 Hint Resolve hasType_det. 713 Hint Resolve hasType_det.
709 (** [hasType_det] will also be useful for proving proof obligations with contradictory contexts. Since its statement includes [forall]-bound variables that do not appear in its conclusion, only [eauto] will apply this hint. *) 714 (** [hasType_det] will also be useful for proving proof obligations with contradictory contexts. Since its statement includes [forall]-bound variables that do not appear in its conclusion, only [eauto] will apply this hint. *)
710 715
711 (** Finally, the implementation of [typeCheck] can be transcribed literally, simply switching notations as needed. *) 716 (** Finally, the implementation of [typeCheck] can be transcribed literally, simply switching notations as needed. *)
712 refine (fix F (e : exp) : {t : type | hasType e t} + {forall t, ~hasType e t} := 717
713 match e return {t : type | hasType e t} + {forall t, ~hasType e t} with 718 refine (fix F (e : exp) : {t : type | hasType e t} + {forall t, ~ hasType e t} :=
719 match e with
714 | Nat _ => [[[TNat]]] 720 | Nat _ => [[[TNat]]]
715 | Plus e1 e2 => 721 | Plus e1 e2 =>
716 t1 <-- F e1; 722 t1 <-- F e1;
717 t2 <-- F e2; 723 t2 <-- F e2;
718 eq_type_dec t1 TNat;;; 724 eq_type_dec t1 TNat;;;
727 [[[TBool]]] 733 [[[TBool]]]
728 end); clear F; crush' tt hasType; eauto. 734 end); clear F; crush' tt hasType; eauto.
729 735
730 (** We clear [F], the local name for the recursive function, to avoid strange proofs that refer to recursive calls that we never make. The [crush] variant [crush'] helps us by performing automatic inversion on instances of the predicates specified in its second argument. Once we throw in [eauto] to apply [hasType_det] for us, we have discharged all the subgoals. *) 736 (** We clear [F], the local name for the recursive function, to avoid strange proofs that refer to recursive calls that we never make. The [crush] variant [crush'] helps us by performing automatic inversion on instances of the predicates specified in its second argument. Once we throw in [eauto] to apply [hasType_det] for us, we have discharged all the subgoals. *)
731 (* end thide *) 737 (* end thide *)
738
739
732 Defined. 740 Defined.
733 741
734 (** The short implementation here hides just how time-saving automation is. Every use of one of the notations adds a proof obligation, giving us 12 in total. Most of these obligations require multiple inversions and either uses of [hasType_det] or applications of [hasType] rules. 742 (** The short implementation here hides just how time-saving automation is. Every use of one of the notations adds a proof obligation, giving us 12 in total. Most of these obligations require multiple inversions and either uses of [hasType_det] or applications of [hasType] rules.
735 743
736 The results of simplifying calls to [typeCheck'] look deceptively similar to the results for [typeCheck], but now the types of the results provide more information. *) 744 The results of simplifying calls to [typeCheck'] look deceptively similar to the results for [typeCheck], but now the types of the results provide more information. *)
737 745
738 Eval simpl in typeCheck' (Nat 0). 746 Eval simpl in typeCheck' (Nat 0).
739 (** [[ 747 (** %\vspace{-.15in}% [[
740
741 = [[[TNat]]] 748 = [[[TNat]]]
742 : {t : type | hasType (Nat 0) t} + 749 : {t : type | hasType (Nat 0) t} +
743 {(forall t : type, ~ hasType (Nat 0) t)} 750 {(forall t : type, ~ hasType (Nat 0) t)}
744 ]] *) 751 ]] *)
745 752
746 Eval simpl in typeCheck' (Plus (Nat 1) (Nat 2)). 753 Eval simpl in typeCheck' (Plus (Nat 1) (Nat 2)).
747 (** [[ 754 (** %\vspace{-.15in}% [[
748
749 = [[[TNat]]] 755 = [[[TNat]]]
750 : {t : type | hasType (Plus (Nat 1) (Nat 2)) t} + 756 : {t : type | hasType (Plus (Nat 1) (Nat 2)) t} +
751 {(forall t : type, ~ hasType (Plus (Nat 1) (Nat 2)) t)} 757 {(forall t : type, ~ hasType (Plus (Nat 1) (Nat 2)) t)}
752 ]] *) 758 ]] *)
753 759
754 Eval simpl in typeCheck' (Plus (Nat 1) (Bool false)). 760 Eval simpl in typeCheck' (Plus (Nat 1) (Bool false)).
755 (** [[ 761 (** %\vspace{-.15in}% [[
756
757 = !! 762 = !!
758 : {t : type | hasType (Plus (Nat 1) (Bool false)) t} + 763 : {t : type | hasType (Plus (Nat 1) (Bool false)) t} +
759 {(forall t : type, ~ hasType (Plus (Nat 1) (Bool false)) t)} 764 {(forall t : type, ~ hasType (Plus (Nat 1) (Bool false)) t)}
760 ]] *) 765 ]] *)
761 766
770 %\item%#<li># %\begin{enumerate}%#<ol># 775 %\item%#<li># %\begin{enumerate}%#<ol>#
771 %\item%#<li># Define [var], a type of propositional variables, as a synonym for [nat].#</li># 776 %\item%#<li># Define [var], a type of propositional variables, as a synonym for [nat].#</li>#
772 %\item%#<li># Define an inductive type [prop] of propositional logic formulas, consisting of variables, negation, and binary conjunction and disjunction.#</li># 777 %\item%#<li># Define an inductive type [prop] of propositional logic formulas, consisting of variables, negation, and binary conjunction and disjunction.#</li>#
773 %\item%#<li># Define a function [propDenote] from variable truth assignments and [prop]s to [Prop], based on the usual meanings of the connectives. Represent truth assignments as functions from [var] to [bool].#</li># 778 %\item%#<li># Define a function [propDenote] from variable truth assignments and [prop]s to [Prop], based on the usual meanings of the connectives. Represent truth assignments as functions from [var] to [bool].#</li>#
774 %\item%#<li># Define a function [bool_true_dec] that checks whether a boolean is true, with a maximally expressive dependent type. That is, the function should have type [forall b, {b = true} + {b = true -> False}]. #</li># 779 %\item%#<li># Define a function [bool_true_dec] that checks whether a boolean is true, with a maximally expressive dependent type. That is, the function should have type [forall b, {b = true} + {b = true -> False}]. #</li>#
775 %\item%#<li># Define a function [decide] that determines whether a particular [prop] is true under a particular truth assignment. That is, the function should have type [forall (truth : var -> bool) (p : prop), {propDenote truth p} + { ~propDenote truth p}]. This function is probably easiest to write in the usual tactical style, instead of programming with [refine]. [bool_true_dec] may come in handy as a hint.#</li># 780 %\item%#<li># Define a function [decide] that determines whether a particular [prop] is true under a particular truth assignment. That is, the function should have type [forall (truth : var -> bool) (p : prop), {propDenote truth p} + {~ propDenote truth p}]. This function is probably easiest to write in the usual tactical style, instead of programming with [refine]. [bool_true_dec] may come in handy as a hint.#</li>#
776 %\item%#<li># Define a function [negate] that returns a simplified version of the negation of a [prop]. That is, the function should have type [forall p : prop, {p' : prop | forall truth, propDenote truth p <-> ~propDenote truth p'}]. To simplify a variable, just negate it. Simplify a negation by returning its argument. Simplify conjunctions and disjunctions using De Morgan's laws, negating the arguments recursively and switching the kind of connective. [decide] may be useful in some of the proof obligations, even if you do not use it in the computational part of [negate]'s definition. Lemmas like [decide] allow us to compensate for the lack of a general Law of the Excluded Middle in CIC.#</li># 781 %\item%#<li># Define a function [negate] that returns a simplified version of the negation of a [prop]. That is, the function should have type [forall p : prop, {p' : prop | forall truth, propDenote truth p <-> ~ propDenote truth p'}]. To simplify a variable, just negate it. Simplify a negation by returning its argument. Simplify conjunctions and disjunctions using De Morgan's laws, negating the arguments recursively and switching the kind of connective. [decide] may be useful in some of the proof obligations, even if you do not use it in the computational part of [negate]'s definition. Lemmas like [decide] allow us to compensate for the lack of a general Law of the Excluded Middle in CIC.#</li>#
777 #</ol>#%\end{enumerate}% #</li># 782 #</ol>#%\end{enumerate}% #</li>#
778 783
779 %\item%#<li># Implement the DPLL satisfiability decision procedure for boolean formulas in conjunctive normal form, with a dependent type that guarantees its correctness. An example of a reasonable type for this function would be [forall f : formula, {truth : tvals | formulaTrue truth f} + {forall truth, ~formulaTrue truth f}]. Implement at least "the basic backtracking algorithm" as defined here: 784 %\item%#<li># Implement the DPLL satisfiability decision procedure for boolean formulas in conjunctive normal form, with a dependent type that guarantees its correctness. An example of a reasonable type for this function would be [forall f : formula, {truth : tvals | formulaTrue truth f} + {forall truth, ~ formulaTrue truth f}]. Implement at least "the basic backtracking algorithm" as defined here:
780 %\begin{center}\url{http://en.wikipedia.org/wiki/DPLL_algorithm}\end{center}% 785 %\begin{center}\url{http://en.wikipedia.org/wiki/DPLL_algorithm}\end{center}%
781 #<blockquote><a href="http://en.wikipedia.org/wiki/DPLL_algorithm">http://en.wikipedia.org/wiki/DPLL_algorithm</a></blockquote># 786 #<blockquote><a href="http://en.wikipedia.org/wiki/DPLL_algorithm">http://en.wikipedia.org/wiki/DPLL_algorithm</a></blockquote>#
782 It might also be instructive to implement the unit propagation and pure literal elimination optimizations described there or some other optimizations that have been used in modern SAT solvers.#</li># 787 It might also be instructive to implement the unit propagation and pure literal elimination optimizations described there or some other optimizations that have been used in modern SAT solvers.#</li>#
783 788
784 #</ol>#%\end{enumerate}% *) 789 #</ol>#%\end{enumerate}% *)