annotate src/Subset.v @ 185:303e9d866597

ccTerm_correct
author Adam Chlipala <adamc@hcoop.net>
date Sun, 16 Nov 2008 19:42:32 -0500
parents 939add5a7db9
children cbf2f74a5130
rev   line source
adamc@70 1 (* Copyright (c) 2008, Adam Chlipala
adamc@70 2 *
adamc@70 3 * This work is licensed under a
adamc@70 4 * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0
adamc@70 5 * Unported License.
adamc@70 6 * The license text is available at:
adamc@70 7 * http://creativecommons.org/licenses/by-nc-nd/3.0/
adamc@70 8 *)
adamc@70 9
adamc@70 10 (* begin hide *)
adamc@70 11 Require Import List.
adamc@70 12
adamc@70 13 Require Import Tactics.
adamc@70 14
adamc@70 15 Set Implicit Arguments.
adamc@70 16 (* end hide *)
adamc@70 17
adamc@70 18
adamc@74 19 (** %\part{Programming with Dependent Types}
adamc@74 20
adamc@74 21 \chapter{Subset Types and Variations}% *)
adamc@70 22
adamc@70 23 (** So far, we have seen many examples of what we might call "classical program verification." We write programs, write their specifications, and then prove that the programs satisfy their specifications. The programs that we have written in Coq have been normal functional programs that we could just as well have written in Haskell or ML. In this chapter, we start investigating uses of %\textit{%#<i>#dependent types#</i>#%}% to integrate programming, specification, and proving into a single phase. *)
adamc@70 24
adamc@70 25
adamc@70 26 (** * Introducing Subset Types *)
adamc@70 27
adamc@70 28 (** Let us consider several ways of implementing the natural number predecessor function. We start by displaying the definition from the standard library: *)
adamc@70 29
adamc@70 30 Print pred.
adamc@70 31 (** [[
adamc@70 32
adamc@70 33 pred = fun n : nat => match n with
adamc@70 34 | 0 => 0
adamc@70 35 | S u => u
adamc@70 36 end
adamc@70 37 : nat -> nat
adamc@70 38 ]] *)
adamc@70 39
adamc@70 40 (** We can use a new command, [Extraction], to produce an OCaml version of this function. *)
adamc@70 41
adamc@70 42 Extraction pred.
adamc@70 43
adamc@70 44 (** %\begin{verbatim}
adamc@70 45 (** val pred : nat -> nat **)
adamc@70 46
adamc@70 47 let pred = function
adamc@70 48 | O -> O
adamc@70 49 | S u -> u
adamc@70 50 \end{verbatim}%
adamc@70 51
adamc@70 52 #<pre>
adamc@70 53 (** val pred : nat -> nat **)
adamc@70 54
adamc@70 55 let pred = function
adamc@70 56 | O -> O
adamc@70 57 | S u -> u
adamc@70 58 </pre># *)
adamc@70 59
adamc@70 60 (** Returning 0 as the predecessor of 0 can come across as somewhat of a hack. In some situations, we might like to be sure that we never try to take the predecessor of 0. We can enforce this by giving [pred] a stronger, dependent type. *)
adamc@70 61
adamc@70 62 Lemma zgtz : 0 > 0 -> False.
adamc@70 63 crush.
adamc@70 64 Qed.
adamc@70 65
adamc@70 66 Definition pred_strong1 (n : nat) : n > 0 -> nat :=
adamc@70 67 match n return (n > 0 -> nat) with
adamc@70 68 | O => fun pf : 0 > 0 => match zgtz pf with end
adamc@70 69 | S n' => fun _ => n'
adamc@70 70 end.
adamc@70 71
adamc@70 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].
adamc@70 73
adamc@70 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. *)
adamc@70 75
adamc@70 76 (** [[
adamc@70 77 Definition pred_strong1' (n : nat) (pf : n > 0) : nat :=
adamc@70 78 match n with
adamc@70 79 | O => match zgtz pf with end
adamc@70 80 | S n' => n'
adamc@70 81 end.
adamc@70 82
adamc@70 83 [[
adamc@70 84 Error: In environment
adamc@70 85 n : nat
adamc@70 86 pf : n > 0
adamc@70 87 The term "pf" has type "n > 0" while it is expected to have type
adamc@70 88 "0 > 0"
adamc@70 89 ]]
adamc@70 90
adamc@70 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.
adamc@70 92
adamc@70 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.
adamc@70 94
adamc@70 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.
adamc@70 96
adamc@70 97 Let us now take a look at the OCaml code Coq generates for [pred_strong1]. *)
adamc@70 98
adamc@70 99 Extraction pred_strong1.
adamc@70 100
adamc@70 101 (** %\begin{verbatim}
adamc@70 102 (** val pred_strong1 : nat -> nat **)
adamc@70 103
adamc@70 104 let pred_strong1 = function
adamc@70 105 | O -> assert false (* absurd case *)
adamc@70 106 | S n' -> n'
adamc@70 107 \end{verbatim}%
adamc@70 108
adamc@70 109 #<pre>
adamc@70 110 (** val pred_strong1 : nat -> nat **)
adamc@70 111
adamc@70 112 let pred_strong1 = function
adamc@70 113 | O -> assert false (* absurd case *)
adamc@70 114 | S n' -> n'
adamc@70 115 </pre># *)
adamc@70 116
adamc@70 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.
adamc@70 118
adamc@70 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]. *)
adamc@70 120
adamc@70 121 Print sig.
adamc@70 122 (** [[
adamc@70 123
adamc@70 124 Inductive sig (A : Type) (P : A -> Prop) : Type :=
adamc@70 125 exist : forall x : A, P x -> sig P
adamc@70 126 For sig: Argument A is implicit
adamc@70 127 For exist: Argument A is implicit
adamc@70 128 ]]
adamc@70 129
adamc@70 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.
adamc@70 131
adamc@70 132 We rewrite [pred_strong1], using some syntactic sugar for subset types. *)
adamc@70 133
adamc@70 134 Locate "{ _ : _ | _ }".
adamc@70 135 (** [[
adamc@70 136
adamc@70 137 Notation Scope
adamc@70 138 "{ x : A | P }" := sig (fun x : A => P)
adamc@70 139 : type_scope
adamc@70 140 (default interpretation)
adamc@70 141 ]] *)
adamc@70 142
adamc@70 143 Definition pred_strong2 (s : {n : nat | n > 0}) : nat :=
adamc@70 144 match s with
adamc@70 145 | exist O pf => match zgtz pf with end
adamc@70 146 | exist (S n') _ => n'
adamc@70 147 end.
adamc@70 148
adamc@70 149 Extraction pred_strong2.
adamc@70 150
adamc@70 151 (** %\begin{verbatim}
adamc@70 152 (** val pred_strong2 : nat -> nat **)
adamc@70 153
adamc@70 154 let pred_strong2 = function
adamc@70 155 | O -> assert false (* absurd case *)
adamc@70 156 | S n' -> n'
adamc@70 157 \end{verbatim}%
adamc@70 158
adamc@70 159 #<pre>
adamc@70 160 (** val pred_strong2 : nat -> nat **)
adamc@70 161
adamc@70 162 let pred_strong2 = function
adamc@70 163 | O -> assert false (* absurd case *)
adamc@70 164 | S n' -> n'
adamc@70 165 </pre>#
adamc@70 166
adamc@70 167 We arrive at the same OCaml code as was extracted from [pred_strong1], which may seem surprising at first. The reason is that a value of [sig] is a pair of two pieces, a value and a proof about it. Extraction erases the proof, which reduces the constructor [exist] of [sig] to taking just a single argument. An optimization eliminates uses of datatypes with single constructors taking single arguments, and we arrive back where we started.
adamc@70 168
adamc@70 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. *)
adamc@70 170
adamc@70 171 Definition pred_strong3 (s : {n : nat | n > 0}) : {m : nat | proj1_sig s = S m} :=
adamc@70 172 match s return {m : nat | proj1_sig s = S m} with
adamc@70 173 | exist 0 pf => match zgtz pf with end
adamc@70 174 | exist (S n') _ => exist _ n' (refl_equal _)
adamc@70 175 end.
adamc@70 176
adamc@70 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.
adamc@70 178
adamc@70 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. *)
adamc@70 180
adamc@70 181 Extraction pred_strong3.
adamc@70 182
adamc@70 183 (** %\begin{verbatim}
adamc@70 184 (** val pred_strong3 : nat -> nat **)
adamc@70 185
adamc@70 186 let pred_strong3 = function
adamc@70 187 | O -> assert false (* absurd case *)
adamc@70 188 | S n' -> n'
adamc@70 189 \end{verbatim}%
adamc@70 190
adamc@70 191 #<pre>
adamc@70 192 (** val pred_strong3 : nat -> nat **)
adamc@70 193
adamc@70 194 let pred_strong3 = function
adamc@70 195 | O -> assert false (* absurd case *)
adamc@70 196 | S n' -> n'
adamc@70 197 </pre>#
adamc@70 198
adamc@70 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. *)
adamc@70 200
adamc@70 201 Definition pred_strong4 (n : nat) : n > 0 -> {m : nat | n = S m}.
adamc@70 202 refine (fun n =>
adamc@70 203 match n return (n > 0 -> {m : nat | n = S m}) with
adamc@70 204 | O => fun _ => False_rec _ _
adamc@70 205 | S n' => fun _ => exist _ n' _
adamc@70 206 end).
adamc@77 207 (* begin thide *)
adamc@70 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:
adamc@70 209
adamc@70 210 [[
adamc@70 211
adamc@70 212 2 subgoals
adamc@70 213
adamc@70 214 n : nat
adamc@70 215 _ : 0 > 0
adamc@70 216 ============================
adamc@70 217 False
adamc@70 218 ]]
adamc@70 219
adamc@70 220 [[
adamc@70 221
adamc@70 222 subgoal 2 is:
adamc@70 223 S n' = S n'
adamc@70 224 ]]
adamc@70 225
adamc@70 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. *)
adamc@70 227
adamc@70 228 Undo.
adamc@70 229 refine (fun n =>
adamc@70 230 match n return (n > 0 -> {m : nat | n = S m}) with
adamc@70 231 | O => fun _ => False_rec _ _
adamc@70 232 | S n' => fun _ => exist _ n' _
adamc@70 233 end); crush.
adamc@77 234 (* end thide *)
adamc@70 235 Defined.
adamc@70 236
adamc@76 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. *)
adamc@70 238
adamc@70 239 Print pred_strong4.
adamc@70 240 (** [[
adamc@70 241
adamc@70 242 pred_strong4 =
adamc@70 243 fun n : nat =>
adamc@70 244 match n as n0 return (n0 > 0 -> {m : nat | n0 = S m}) with
adamc@70 245 | 0 =>
adamc@70 246 fun _ : 0 > 0 =>
adamc@70 247 False_rec {m : nat | 0 = S m}
adamc@70 248 (Bool.diff_false_true
adamc@70 249 (Bool.absurd_eq_true false
adamc@70 250 (Bool.diff_false_true
adamc@70 251 (Bool.absurd_eq_true false (pred_strong4_subproof n _)))))
adamc@70 252 | S n' =>
adamc@70 253 fun _ : S n' > 0 =>
adamc@70 254 exist (fun m : nat => S n' = S m) n' (refl_equal (S n'))
adamc@70 255 end
adamc@70 256 : forall n : nat, n > 0 -> {m : nat | n = S m}
adamc@70 257 ]]
adamc@70 258
adamc@70 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.
adamc@70 260
adamc@70 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. *)
adamc@70 262
adamc@70 263 Notation "!" := (False_rec _ _).
adamc@70 264 Notation "[ e ]" := (exist _ e _).
adamc@70 265
adamc@70 266 Definition pred_strong5 (n : nat) : n > 0 -> {m : nat | n = S m}.
adamc@70 267 refine (fun n =>
adamc@70 268 match n return (n > 0 -> {m : nat | n = S m}) with
adamc@70 269 | O => fun _ => !
adamc@70 270 | S n' => fun _ => [n']
adamc@70 271 end); crush.
adamc@70 272 Defined.
adamc@71 273
adamc@71 274
adamc@71 275 (** * Decidable Proposition Types *)
adamc@71 276
adamc@71 277 (** There is another type in the standard library which captures the idea of program values that indicate which of two propositions is true. *)
adamc@71 278
adamc@71 279 Print sumbool.
adamc@71 280 (** [[
adamc@71 281
adamc@71 282 Inductive sumbool (A : Prop) (B : Prop) : Set :=
adamc@71 283 left : A -> {A} + {B} | right : B -> {A} + {B}
adamc@71 284 For left: Argument A is implicit
adamc@71 285 For right: Argument B is implicit
adamc@71 286 ]] *)
adamc@71 287
adamc@71 288 (** We can define some notations to make working with [sumbool] more convenient. *)
adamc@71 289
adamc@71 290 Notation "'Yes'" := (left _ _).
adamc@71 291 Notation "'No'" := (right _ _).
adamc@71 292 Notation "'Reduce' x" := (if x then Yes else No) (at level 50).
adamc@71 293
adamc@71 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.
adamc@71 295
adamc@71 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. *)
adamc@71 297
adamc@71 298 Definition eq_nat_dec (n m : nat) : {n = m} + {n <> m}.
adamc@71 299 refine (fix f (n m : nat) {struct n} : {n = m} + {n <> m} :=
adamc@71 300 match n, m return {n = m} + {n <> m} with
adamc@71 301 | O, O => Yes
adamc@71 302 | S n', S m' => Reduce (f n' m')
adamc@71 303 | _, _ => No
adamc@71 304 end); congruence.
adamc@71 305 Defined.
adamc@71 306
adamc@71 307 (** Our definition extracts to reasonable OCaml code. *)
adamc@71 308
adamc@71 309 Extraction eq_nat_dec.
adamc@71 310
adamc@71 311 (** %\begin{verbatim}
adamc@71 312 (** val eq_nat_dec : nat -> nat -> sumbool **)
adamc@71 313
adamc@71 314 let rec eq_nat_dec n m =
adamc@71 315 match n with
adamc@71 316 | O -> (match m with
adamc@71 317 | O -> Left
adamc@71 318 | S n0 -> Right)
adamc@71 319 | S n' -> (match m with
adamc@71 320 | O -> Right
adamc@71 321 | S m' -> eq_nat_dec n' m')
adamc@71 322 \end{verbatim}%
adamc@71 323
adamc@71 324 #<pre>
adamc@71 325 (** val eq_nat_dec : nat -> nat -> sumbool **)
adamc@71 326
adamc@71 327 let rec eq_nat_dec n m =
adamc@71 328 match n with
adamc@71 329 | O -> (match m with
adamc@71 330 | O -> Left
adamc@71 331 | S n0 -> Right)
adamc@71 332 | S n' -> (match m with
adamc@71 333 | O -> Right
adamc@71 334 | S m' -> eq_nat_dec n' m')
adamc@71 335 </pre>#
adamc@71 336
adamc@71 337 Proving this kind of decidable equality result is so common that Coq comes with a tactic for automating it. *)
adamc@71 338
adamc@71 339 Definition eq_nat_dec' (n m : nat) : {n = m} + {n <> m}.
adamc@71 340 decide equality.
adamc@71 341 Defined.
adamc@71 342
adamc@71 343 (** Curious readers can verify that the [decide equality] version extracts to the same OCaml code as our more manual version does. That OCaml code had one undesirable property, which is that it uses %\texttt{%#<tt>#Left#</tt>#%}% and %\texttt{%#<tt>#Right#</tt>#%}% constructors instead of the boolean values built into OCaml. We can fix this, by using Coq's facility for mapping Coq inductive types to OCaml variant types. *)
adamc@71 344
adamc@71 345 Extract Inductive sumbool => "bool" ["true" "false"].
adamc@71 346 Extraction eq_nat_dec'.
adamc@71 347
adamc@71 348 (** %\begin{verbatim}
adamc@71 349 (** val eq_nat_dec' : nat -> nat -> bool **)
adamc@71 350
adamc@71 351 let rec eq_nat_dec' n m0 =
adamc@71 352 match n with
adamc@71 353 | O -> (match m0 with
adamc@71 354 | O -> true
adamc@71 355 | S n0 -> false)
adamc@71 356 | S n0 -> (match m0 with
adamc@71 357 | O -> false
adamc@71 358 | S n1 -> eq_nat_dec' n0 n1)
adamc@71 359 \end{verbatim}%
adamc@71 360
adamc@71 361 #<pre>
adamc@71 362 (** val eq_nat_dec' : nat -> nat -> bool **)
adamc@71 363
adamc@71 364 let rec eq_nat_dec' n m0 =
adamc@71 365 match n with
adamc@71 366 | O -> (match m0 with
adamc@71 367 | O -> true
adamc@71 368 | S n0 -> false)
adamc@71 369 | S n0 -> (match m0 with
adamc@71 370 | O -> false
adamc@71 371 | S n1 -> eq_nat_dec' n0 n1)
adamc@71 372 </pre># *)
adamc@72 373
adamc@72 374 (** %\smallskip%
adamc@72 375
adamc@72 376 We can build "smart" versions of the usual boolean operators and put them to good use in certified programming. For instance, here is a [sumbool] version of boolean "or." *)
adamc@72 377
adamc@77 378 (* begin thide *)
adamc@72 379 Notation "x || y" := (if x then Yes else Reduce y) (at level 50).
adamc@72 380
adamc@72 381 (** Let us use it for building a function that decides list membership. We need to assume the existence of an equality decision procedure for the type of list elements. *)
adamc@72 382
adamc@72 383 Section In_dec.
adamc@72 384 Variable A : Set.
adamc@72 385 Variable A_eq_dec : forall x y : A, {x = y} + {x <> y}.
adamc@72 386
adamc@72 387 (** The final function is easy to write using the techniques we have developed so far. *)
adamc@72 388
adamc@72 389 Definition In_dec : forall (x : A) (ls : list A), {In x ls} + { ~In x ls}.
adamc@72 390 refine (fix f (x : A) (ls : list A) {struct ls}
adamc@72 391 : {In x ls} + { ~In x ls} :=
adamc@72 392 match ls return {In x ls} + { ~In x ls} with
adamc@72 393 | nil => No
adamc@72 394 | x' :: ls' => A_eq_dec x x' || f x ls'
adamc@72 395 end); crush.
adamc@72 396 Qed.
adamc@72 397 End In_dec.
adamc@72 398
adamc@72 399 (** [In_dec] has a reasonable extraction to OCaml. *)
adamc@72 400
adamc@72 401 Extraction In_dec.
adamc@77 402 (* end thide *)
adamc@72 403
adamc@72 404 (** %\begin{verbatim}
adamc@72 405 (** val in_dec : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 list -> bool **)
adamc@72 406
adamc@72 407 let rec in_dec a_eq_dec x = function
adamc@72 408 | Nil -> false
adamc@72 409 | Cons (x', ls') ->
adamc@72 410 (match a_eq_dec x x' with
adamc@72 411 | true -> true
adamc@72 412 | false -> in_dec a_eq_dec x ls')
adamc@72 413 \end{verbatim}%
adamc@72 414
adamc@72 415 #<pre>
adamc@72 416 (** val in_dec : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 list -> bool **)
adamc@72 417
adamc@72 418 let rec in_dec a_eq_dec x = function
adamc@72 419 | Nil -> false
adamc@72 420 | Cons (x', ls') ->
adamc@72 421 (match a_eq_dec x x' with
adamc@72 422 | true -> true
adamc@72 423 | false -> in_dec a_eq_dec x ls')
adamc@72 424 </pre># *)
adamc@72 425
adamc@72 426
adamc@72 427 (** * Partial Subset Types *)
adamc@72 428
adamc@73 429 (** Our final implementation of dependent predecessor used a very specific argument type to ensure that execution could always complete normally. Sometimes we want to allow execution to fail, and we want a more principled way of signaling that than returning a default value, as [pred] does for [0]. One approach is to define this type family [maybe], which is a version of [sig] that allows obligation-free failure. *)
adamc@73 430
adamc@89 431 Inductive maybe (A : Set) (P : A -> Prop) : Set :=
adamc@72 432 | Unknown : maybe P
adamc@72 433 | Found : forall x : A, P x -> maybe P.
adamc@72 434
adamc@73 435 (** We can define some new notations, analogous to those we defined for subset types. *)
adamc@73 436
adamc@72 437 Notation "{{ x | P }}" := (maybe (fun x => P)).
adamc@72 438 Notation "??" := (Unknown _).
adamc@72 439 Notation "[[ x ]]" := (Found _ x _).
adamc@72 440
adamc@73 441 (** Now our next version of [pred] is trivial to write. *)
adamc@73 442
adamc@73 443 Definition pred_strong6 (n : nat) : {{m | n = S m}}.
adamc@73 444 refine (fun n =>
adamc@73 445 match n return {{m | n = S m}} with
adamc@73 446 | O => ??
adamc@73 447 | S n' => [[n']]
adamc@73 448 end); trivial.
adamc@73 449 Defined.
adamc@73 450
adamc@73 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]. *)
adamc@73 452
adamc@73 453 Print sumor.
adamc@73 454 (** [[
adamc@73 455
adamc@73 456 Inductive sumor (A : Type) (B : Prop) : Type :=
adamc@73 457 inleft : A -> A + {B} | inright : B -> A + {B}
adamc@73 458 For inleft: Argument A is implicit
adamc@73 459 For inright: Argument B is implicit
adamc@73 460 ]] *)
adamc@73 461
adamc@73 462 (** We add notations for easy use of the [sumor] constructors. The second notation is specialized to [sumor]s whose [A] parameters are instantiated with regular subset types, since this is how we will use [sumor] below. *)
adamc@73 463
adamc@73 464 Notation "!!" := (inright _ _).
adamc@73 465 Notation "[[[ x ]]]" := (inleft _ [x]).
adamc@73 466
adamc@73 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. *)
adamc@73 468
adamc@73 469 Definition pred_strong7 (n : nat) : {m : nat | n = S m} + {n = 0}.
adamc@73 470 refine (fun n =>
adamc@73 471 match n return {m : nat | n = S m} + {n = 0} with
adamc@73 472 | O => !!
adamc@73 473 | S n' => [[[n']]]
adamc@73 474 end); trivial.
adamc@73 475 Defined.
adamc@73 476
adamc@73 477
adamc@73 478 (** * Monadic Notations *)
adamc@73 479
adamc@73 480 (** We can treat [maybe] like a monad, in the same way that the Haskell [Maybe] type is interpreted as a failure monad. Our [maybe] has the wrong type to be a literal monad, but a "bind"-like notation will still be helpful. *)
adamc@73 481
adamc@72 482 Notation "x <- e1 ; e2" := (match e1 with
adamc@72 483 | Unknown => ??
adamc@72 484 | Found x _ => e2
adamc@72 485 end)
adamc@72 486 (right associativity, at level 60).
adamc@72 487
adamc@73 488 (** The meaning of [x <- e1; e2] is: First run [e1]. If it fails to find an answer, then announce failure for our derived computation, too. If [e1] %\textit{%#<i>#does#</i>#%}% find an answer, pass that answer on to [e2] to find the final result. The variable [x] can be considered bound in [e2].
adamc@73 489
adamc@73 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. *)
adamc@73 491
adamc@73 492 Definition doublePred (n1 n2 : nat) : {{p | n1 = S (fst p) /\ n2 = S (snd p)}}.
adamc@73 493 refine (fun n1 n2 =>
adamc@73 494 m1 <- pred_strong6 n1;
adamc@73 495 m2 <- pred_strong6 n2;
adamc@73 496 [[(m1, m2)]]); tauto.
adamc@73 497 Defined.
adamc@73 498
adamc@73 499 (** We can build a [sumor] version of the "bind" notation and use it to write a similarly straightforward version of this function. *)
adamc@73 500
adamc@73 501 (** printing <-- $\longleftarrow$ *)
adamc@73 502
adamc@73 503 Notation "x <-- e1 ; e2" := (match e1 with
adamc@73 504 | inright _ => !!
adamc@73 505 | inleft (exist x _) => e2
adamc@73 506 end)
adamc@73 507 (right associativity, at level 60).
adamc@73 508
adamc@73 509 (** printing * $\times$ *)
adamc@73 510
adamc@73 511 Definition doublePred' (n1 n2 : nat) : {p : nat * nat | n1 = S (fst p) /\ n2 = S (snd p)}
adamc@73 512 + {n1 = 0 \/ n2 = 0}.
adamc@73 513 refine (fun n1 n2 =>
adamc@73 514 m1 <-- pred_strong7 n1;
adamc@73 515 m2 <-- pred_strong7 n2;
adamc@73 516 [[[(m1, m2)]]]); tauto.
adamc@73 517 Defined.
adamc@72 518
adamc@72 519
adamc@72 520 (** * A Type-Checking Example *)
adamc@72 521
adamc@75 522 (** We can apply these specification types to build a certified type-checker for a simple expression language. *)
adamc@75 523
adamc@72 524 Inductive exp : Set :=
adamc@72 525 | Nat : nat -> exp
adamc@72 526 | Plus : exp -> exp -> exp
adamc@72 527 | Bool : bool -> exp
adamc@72 528 | And : exp -> exp -> exp.
adamc@72 529
adamc@75 530 (** We define a simple language of types and its typing rules, in the style introduced in Chapter 4. *)
adamc@75 531
adamc@72 532 Inductive type : Set := TNat | TBool.
adamc@72 533
adamc@72 534 Inductive hasType : exp -> type -> Prop :=
adamc@72 535 | HtNat : forall n,
adamc@72 536 hasType (Nat n) TNat
adamc@72 537 | HtPlus : forall e1 e2,
adamc@72 538 hasType e1 TNat
adamc@72 539 -> hasType e2 TNat
adamc@72 540 -> hasType (Plus e1 e2) TNat
adamc@72 541 | HtBool : forall b,
adamc@72 542 hasType (Bool b) TBool
adamc@72 543 | HtAnd : forall e1 e2,
adamc@72 544 hasType e1 TBool
adamc@72 545 -> hasType e2 TBool
adamc@72 546 -> hasType (And e1 e2) TBool.
adamc@72 547
adamc@75 548 (** It will be helpful to have a function for comparing two types. We build one using [decide equality]. *)
adamc@75 549
adamc@77 550 (* begin thide *)
adamc@75 551 Definition eq_type_dec : forall t1 t2 : type, {t1 = t2} + {t1 <> t2}.
adamc@72 552 decide equality.
adamc@72 553 Defined.
adamc@72 554
adamc@75 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. *)
adamc@75 556
adamc@73 557 Notation "e1 ;; e2" := (if e1 then e2 else ??)
adamc@73 558 (right associativity, at level 60).
adamc@73 559
adamc@75 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. *)
adamc@77 561 (* end thide *)
adamc@75 562
adamc@72 563 Definition typeCheck (e : exp) : {{t | hasType e t}}.
adamc@77 564 (* begin thide *)
adamc@72 565 Hint Constructors hasType.
adamc@72 566
adamc@72 567 refine (fix F (e : exp) : {{t | hasType e t}} :=
adamc@72 568 match e return {{t | hasType e t}} with
adamc@72 569 | Nat _ => [[TNat]]
adamc@72 570 | Plus e1 e2 =>
adamc@72 571 t1 <- F e1;
adamc@72 572 t2 <- F e2;
adamc@72 573 eq_type_dec t1 TNat;;
adamc@72 574 eq_type_dec t2 TNat;;
adamc@72 575 [[TNat]]
adamc@72 576 | Bool _ => [[TBool]]
adamc@72 577 | And e1 e2 =>
adamc@72 578 t1 <- F e1;
adamc@72 579 t2 <- F e2;
adamc@72 580 eq_type_dec t1 TBool;;
adamc@72 581 eq_type_dec t2 TBool;;
adamc@72 582 [[TBool]]
adamc@72 583 end); crush.
adamc@77 584 (* end thide *)
adamc@72 585 Defined.
adamc@72 586
adamc@75 587 (** Despite manipulating proofs, our type checker is easy to run. *)
adamc@75 588
adamc@72 589 Eval simpl in typeCheck (Nat 0).
adamc@75 590 (** [[
adamc@75 591
adamc@75 592 = [[TNat]]
adamc@75 593 : {{t | hasType (Nat 0) t}}
adamc@75 594 ]] *)
adamc@75 595
adamc@72 596 Eval simpl in typeCheck (Plus (Nat 1) (Nat 2)).
adamc@75 597 (** [[
adamc@75 598
adamc@75 599 = [[TNat]]
adamc@75 600 : {{t | hasType (Plus (Nat 1) (Nat 2)) t}}
adamc@75 601 ]] *)
adamc@75 602
adamc@72 603 Eval simpl in typeCheck (Plus (Nat 1) (Bool false)).
adamc@75 604 (** [[
adamc@75 605
adamc@75 606 = ??
adamc@75 607 : {{t | hasType (Plus (Nat 1) (Bool false)) t}}
adamc@75 608 ]] *)
adamc@75 609
adamc@75 610 (** The type-checker also extracts to some reasonable OCaml code. *)
adamc@75 611
adamc@75 612 Extraction typeCheck.
adamc@75 613
adamc@75 614 (** %\begin{verbatim}
adamc@75 615 (** val typeCheck : exp -> type0 maybe **)
adamc@75 616
adamc@75 617 let rec typeCheck = function
adamc@75 618 | Nat n -> Found TNat
adamc@75 619 | Plus (e1, e2) ->
adamc@75 620 (match typeCheck e1 with
adamc@75 621 | Unknown -> Unknown
adamc@75 622 | Found t1 ->
adamc@75 623 (match typeCheck e2 with
adamc@75 624 | Unknown -> Unknown
adamc@75 625 | Found t2 ->
adamc@75 626 (match eq_type_dec t1 TNat with
adamc@75 627 | true ->
adamc@75 628 (match eq_type_dec t2 TNat with
adamc@75 629 | true -> Found TNat
adamc@75 630 | false -> Unknown)
adamc@75 631 | false -> Unknown)))
adamc@75 632 | Bool b -> Found TBool
adamc@75 633 | And (e1, e2) ->
adamc@75 634 (match typeCheck e1 with
adamc@75 635 | Unknown -> Unknown
adamc@75 636 | Found t1 ->
adamc@75 637 (match typeCheck e2 with
adamc@75 638 | Unknown -> Unknown
adamc@75 639 | Found t2 ->
adamc@75 640 (match eq_type_dec t1 TBool with
adamc@75 641 | true ->
adamc@75 642 (match eq_type_dec t2 TBool with
adamc@75 643 | true -> Found TBool
adamc@75 644 | false -> Unknown)
adamc@75 645 | false -> Unknown)))
adamc@75 646 \end{verbatim}%
adamc@75 647
adamc@75 648 #<pre>
adamc@75 649 (** val typeCheck : exp -> type0 maybe **)
adamc@75 650
adamc@75 651 let rec typeCheck = function
adamc@75 652 | Nat n -> Found TNat
adamc@75 653 | Plus (e1, e2) ->
adamc@75 654 (match typeCheck e1 with
adamc@75 655 | Unknown -> Unknown
adamc@75 656 | Found t1 ->
adamc@75 657 (match typeCheck e2 with
adamc@75 658 | Unknown -> Unknown
adamc@75 659 | Found t2 ->
adamc@75 660 (match eq_type_dec t1 TNat with
adamc@75 661 | true ->
adamc@75 662 (match eq_type_dec t2 TNat with
adamc@75 663 | true -> Found TNat
adamc@75 664 | false -> Unknown)
adamc@75 665 | false -> Unknown)))
adamc@75 666 | Bool b -> Found TBool
adamc@75 667 | And (e1, e2) ->
adamc@75 668 (match typeCheck e1 with
adamc@75 669 | Unknown -> Unknown
adamc@75 670 | Found t1 ->
adamc@75 671 (match typeCheck e2 with
adamc@75 672 | Unknown -> Unknown
adamc@75 673 | Found t2 ->
adamc@75 674 (match eq_type_dec t1 TBool with
adamc@75 675 | true ->
adamc@75 676 (match eq_type_dec t2 TBool with
adamc@75 677 | true -> Found TBool
adamc@75 678 | false -> Unknown)
adamc@75 679 | false -> Unknown)))
adamc@75 680 </pre># *)
adamc@75 681
adamc@75 682 (** %\smallskip%
adamc@75 683
adamc@75 684 We can adapt this implementation to use [sumor], so that we know our type-checker only fails on ill-typed inputs. First, we define an analogue to the "assertion" notation. *)
adamc@73 685
adamc@77 686 (* begin thide *)
adamc@73 687 Notation "e1 ;;; e2" := (if e1 then e2 else !!)
adamc@73 688 (right associativity, at level 60).
adamc@73 689
adamc@75 690 (** Next, we prove a helpful lemma, which states that a given expression can have at most one type. *)
adamc@75 691
adamc@75 692 Lemma hasType_det : forall e t1,
adamc@73 693 hasType e t1
adamc@73 694 -> forall t2,
adamc@73 695 hasType e t2
adamc@73 696 -> t1 = t2.
adamc@73 697 induction 1; inversion 1; crush.
adamc@73 698 Qed.
adamc@73 699
adamc@75 700 (** Now we can define the type-checker. Its type expresses that it only fails on untypable expressions. *)
adamc@75 701
adamc@77 702 (* end thide *)
adamc@73 703 Definition typeCheck' (e : exp) : {t : type | hasType e t} + {forall t, ~hasType e t}.
adamc@77 704 (* begin thide *)
adamc@73 705 Hint Constructors hasType.
adamc@75 706 (** We register all of the typing rules as hints. *)
adamc@75 707
adamc@73 708 Hint Resolve hasType_det.
adamc@75 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. *)
adamc@73 710
adamc@75 711 (** Finally, the implementation of [typeCheck] can be transcribed literally, simply switching notations as needed. *)
adamc@73 712 refine (fix F (e : exp) : {t : type | hasType e t} + {forall t, ~hasType e t} :=
adamc@73 713 match e return {t : type | hasType e t} + {forall t, ~hasType e t} with
adamc@73 714 | Nat _ => [[[TNat]]]
adamc@73 715 | Plus e1 e2 =>
adamc@73 716 t1 <-- F e1;
adamc@73 717 t2 <-- F e2;
adamc@73 718 eq_type_dec t1 TNat;;;
adamc@73 719 eq_type_dec t2 TNat;;;
adamc@73 720 [[[TNat]]]
adamc@73 721 | Bool _ => [[[TBool]]]
adamc@73 722 | And e1 e2 =>
adamc@73 723 t1 <-- F e1;
adamc@73 724 t2 <-- F e2;
adamc@73 725 eq_type_dec t1 TBool;;;
adamc@73 726 eq_type_dec t2 TBool;;;
adamc@73 727 [[[TBool]]]
adamc@73 728 end); clear F; crush' tt hasType; eauto.
adamc@75 729
adamc@75 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. *)
adamc@77 731 (* end thide *)
adamc@73 732 Defined.
adamc@73 733
adamc@75 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.
adamc@75 735
adamc@75 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. *)
adamc@75 737
adamc@73 738 Eval simpl in typeCheck' (Nat 0).
adamc@75 739 (** [[
adamc@75 740
adamc@75 741 = [[[TNat]]]
adamc@75 742 : {t : type | hasType (Nat 0) t} +
adamc@75 743 {(forall t : type, ~ hasType (Nat 0) t)}
adamc@75 744 ]] *)
adamc@75 745
adamc@73 746 Eval simpl in typeCheck' (Plus (Nat 1) (Nat 2)).
adamc@75 747 (** [[
adamc@75 748
adamc@75 749 = [[[TNat]]]
adamc@75 750 : {t : type | hasType (Plus (Nat 1) (Nat 2)) t} +
adamc@75 751 {(forall t : type, ~ hasType (Plus (Nat 1) (Nat 2)) t)}
adamc@75 752 ]] *)
adamc@75 753
adamc@73 754 Eval simpl in typeCheck' (Plus (Nat 1) (Bool false)).
adamc@75 755 (** [[
adamc@75 756
adamc@75 757 = !!
adamc@75 758 : {t : type | hasType (Plus (Nat 1) (Bool false)) t} +
adamc@75 759 {(forall t : type, ~ hasType (Plus (Nat 1) (Bool false)) t)}
adamc@75 760 ]] *)
adamc@82 761
adamc@82 762
adamc@82 763 (** * Exercises *)
adamc@82 764
adamc@82 765 (** All of the notations defined in this chapter, plus some extras, are available for import from the module [MoreSpecif] of the book source.
adamc@82 766
adamc@82 767 %\begin{enumerate}%#<ol>#
adamc@82 768 %\item%#<li># Write a function of type [forall n m : nat, {n <= m} + {n > m}]. That is, this function decides whether one natural is less than another, and its dependent type guarantees that its results are accurate.#</li>#
adamc@82 769
adamc@82 770 %\item%#<li># %\begin{enumerate}%#<ol>#
adamc@82 771 %\item%#<li># Define [var], a type of propositional variables, as a synonym for [nat].#</li>#
adamc@82 772 %\item%#<li># Define an inductive type [prop] of propositional logic formulas, consisting of variables, negation, and binary conjunction and disjunction.#</li>#
adamc@82 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>#
adamc@82 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>#
adamc@82 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>#
adamc@82 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>#
adamc@82 777 #</ol>#%\end{enumerate}% #</li>#
adamc@82 778
adamc@82 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:
adamc@82 780 %\begin{center}\url{http://en.wikipedia.org/wiki/DPLL_algorithm}\end{center}%
adamc@82 781 #<blockquote><a href="http://en.wikipedia.org/wiki/DPLL_algorithm">http://en.wikipedia.org/wiki/DPLL_algorithm</a></blockquote>#
adamc@82 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>#
adamc@82 783
adamc@82 784 #</ol>#%\end{enumerate}% *)