### annotate src/Subset.v @ 534:ed829eaa91b2

Builds with Coq 8.5beta2
author Adam Chlipala Wed, 05 Aug 2015 14:46:55 -0400 8921cfa2f503 af97676583f3
rev   line source
adamc@70 10 (* begin hide *)
adamc@70 17 (* end hide *)
adam@403 19 (** printing <-- $\longleftarrow$ *)
adamc@74 22 (** %\part{Programming with Dependent Types}
adamc@74 24 \chapter{Subset Types and Variations}% *)
adam@423 26 (** 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%\index{dependent types}% _dependent types_ to integrate programming, specification, and proving into a single phase. The techniques we will learn make it possible to reduce the cost of program verification dramatically. *)
adamc@70 29 (** * Introducing Subset Types *)
adamc@70 31 (** Let us consider several ways of implementing the natural number predecessor function. We start by displaying the definition from the standard library: *)
adamc@70 35 pred = fun n : nat => match n with
adamc@70 36 | 0 => 0
adamc@70 37 | S u => u
adamc@70 39 : nat -> nat
adam@335 43 We can use a new command, %\index{Vernacular commands!Extraction}\index{program extraction}\index{extraction|see{program extraction}}%[Extraction], to produce an %\index{OCaml}%OCaml version of this function. *)
adamc@70 48 (** val pred : nat -> nat **)
adamc@70 50 let pred = function
adamc@70 51 | O -> O
adamc@70 52 | S u -> u
adamc@70 56 (** val pred : nat -> nat **)
adamc@70 58 let pred = function
adamc@70 59 | O -> O
adamc@70 60 | S u -> u
adamc@70 63 (** 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 65 Lemma zgtz : 0 > 0 -> False.
adamc@70 69 Definition pred_strong1 (n : nat) : n > 0 -> nat :=
adamc@70 71 | O => fun pf : 0 > 0 => match zgtz pf with end
adamc@70 72 | S n' => fun _ => n'
adam@398 75 (** We expand the type of [pred] to include a _proof_ 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 _dependent_ type, because its type depends on the _value_ of the argument [n].
adam@398 77 Coq's [Eval] command can execute particular invocations of [pred_strong1] just as easily as it can execute more traditional functional programs. Note that Coq has decided that argument [n] of [pred_strong1] can be made _implicit_, since it can be deduced from the type of the second argument, so we need not write [n] in function calls. *)
adam@282 79 Theorem two_gt0 : 2 > 0.
adam@282 83 Eval compute in pred_strong1 two_gt0.
adam@442 89 One aspect in particular of the definition of [pred_strong1] 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.
adamc@70 92 Definition pred_strong1' (n : nat) (pf : n > 0) : nat :=
adamc@70 94 | O => match zgtz pf with end
adamc@70 95 | S n' => n'
adamc@70 102 pf : n > 0
adamc@70 103 The term "pf" has type "n > 0" while it is expected to have type
adamc@212 107 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.
adam@398 109 In this case, we must use a [return] annotation to declare the relationship between the _value_ of the [match] discriminee and the _type_ 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.
adam@471 111 We are lucky that Coq's heuristics infer the [return] clause (specifically, [return n > 0 -> nat]) for us in the definition of [pred_strong1], leading to the following elaborated code: *)
adam@335 113 Definition pred_strong1' (n : nat) : n > 0 -> nat :=
adam@335 114 match n return n > 0 -> nat with
adam@335 115 | O => fun pf : 0 > 0 => match zgtz pf with end
adam@335 116 | S n' => fun _ => n'
adam@403 119 (** By making explicit the functional relationship between value [n] and the result type of the [match], we guide Coq toward proper type checking. The clause for this example follows by simple copying of the original annotation on the definition. In general, however, the [match] annotation inference problem is undecidable. The known undecidable problem of%\index{higher-order unification}% _higher-order unification_ %\cite{HOU}% 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 121 Let us now take a look at the OCaml code Coq generates for [pred_strong1]. *)
adamc@70 126 (** val pred_strong1 : nat -> nat **)
adamc@70 128 let pred_strong1 = function
adamc@70 129 | O -> assert false (* absurd case *)
adamc@70 130 | S n' -> n'
adamc@70 134 (** val pred_strong1 : nat -> nat **)
adamc@70 136 let pred_strong1 = function
adamc@70 137 | O -> assert false (* absurd case *)
adamc@70 138 | S n' -> n'
adam@451 141 (** 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: proofs are erased systematically.
adam@403 145 We can reimplement our dependently typed [pred] based on%\index{subset types}% _subset types_, defined in the standard library with the type family %\index{Gallina terms!sig}%[sig]. *)
adam@423 147 (* begin hide *)
adam@437 148 (* begin thide *)
adam@437 149 Definition bar := ex.
adam@437 150 (* end thide *)
adam@423 151 (* end hide *)
adamc@70 155 Inductive sig (A : Type) (P : A -> Prop) : Type :=
adamc@70 156 exist : forall x : A, P x -> sig P
adam@442 159 The family [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 161 We rewrite [pred_strong1], using some syntactic sugar for subset types. *)
adamc@70 163 Locate "{ _ : _ | _ }".
adam@495 166 "{ x : A | P }" := sig (fun x : A => P)
adamc@70 170 Definition pred_strong2 (s : {n : nat | n > 0}) : nat :=
adamc@70 172 | exist O pf => match zgtz pf with end
adamc@70 173 | exist (S n') _ => n'
adam@474 176 (** To build a value of a subset type, we use the [exist] constructor, and the details of how to do that follow from the output of our earlier [Print sig] command, where we elided the extra information that parameter [A] is implicit. We need an extra [_] here and not in the definition of [pred_strong2] because _parameters_ of inductive types (like the predicate [P] for [sig]) are not mentioned in pattern matching, but _are_ mentioned in construction of terms (if they are not marked as implicit arguments). *)
adam@282 178 Eval compute in pred_strong2 (exist _ 2 two_gt0).
adamc@70 188 (** val pred_strong2 : nat -> nat **)
adamc@70 190 let pred_strong2 = function
adamc@70 191 | O -> assert false (* absurd case *)
adamc@70 192 | S n' -> n'
adamc@70 196 (** val pred_strong2 : nat -> nat **)
adamc@70 198 let pred_strong2 = function
adamc@70 199 | O -> assert false (* absurd case *)
adamc@70 200 | S n' -> n'
adamc@70 203 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 205 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 207 Definition pred_strong3 (s : {n : nat | n > 0}) : {m : nat | proj1_sig s = S m} :=
adamc@70 208 match s return {m : nat | proj1_sig s = S m} with
adamc@70 209 | exist 0 pf => match zgtz pf with end
adam@426 210 | exist (S n') pf => exist _ n' (eq_refl _)
adam@495 213 (* begin hide *)
adam@495 214 (* begin thide *)
adam@495 215 Definition ugh := lt.
adam@495 216 (* end thide *)
adam@495 217 (* end hide *)
adam@282 219 Eval compute in pred_strong3 (exist _ 2 two_gt0).
adam@426 221 = exist (fun m : nat => 2 = S m) 1 (eq_refl 2)
adam@282 222 : {m : nat | proj1_sig (exist (lt 0) 2 two_gt0) = S m}
adam@423 226 (* begin hide *)
adam@437 227 (* begin thide *)
adam@423 228 Definition pred_strong := 0.
adam@437 229 (* end thide *)
adam@423 230 (* end hide *)
adam@474 232 (** A value in a subset type can be thought of as a%\index{dependent pair}% _dependent pair_ (or%\index{sigma type}% _sigma type_) of a base value and a proof about it. The function %\index{Gallina terms!proj1\_sig}%[proj1_sig] extracts the first component of the pair. It 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.
adamc@70 234 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 239 (** val pred_strong3 : nat -> nat **)
adamc@70 241 let pred_strong3 = function
adamc@70 242 | O -> assert false (* absurd case *)
adamc@70 243 | S n' -> n'
adamc@70 247 (** val pred_strong3 : nat -> nat **)
adamc@70 249 let pred_strong3 = function
adamc@70 250 | O -> assert false (* absurd case *)
adamc@70 251 | S n' -> n'
adam@335 254 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. (Recall that [False_rec] is the [Set]-level induction principle for [False], which can be used to produce a value in any [Set] given a proof of [False].) *)
adam@297 256 Definition pred_strong4 : forall n : nat, n > 0 -> {m : nat | n = S m}.
adamc@70 257 refine (fun n =>
adamc@70 259 | O => fun _ => False_rec _ _
adamc@70 260 | S n' => fun _ => exist _ n' _
adamc@77 263 (* begin thide *)
adam@335 264 (** 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. It may seem strange to change perspective so implicitly between programming and proving, but recall that programs and proofs are two sides of the same coin in Coq, thanks to the Curry-Howard correspondence.
adam@423 266 We do most of the work with the %\index{tactics!refine}%[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 272 _ : 0 > 0
adamc@70 278 S n' = S n'
adamc@70 281 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 284 refine (fun n =>
adamc@70 286 | O => fun _ => False_rec _ _
adamc@70 287 | S n' => fun _ => exist _ n' _
adamc@77 289 (* end thide *)
adam@423 292 (** We end the "proof" with %\index{Vernacular commands!Defined}%[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. (More formally, [Defined] marks an identifier as%\index{transparent}% _transparent_, allowing it to be unfolded; while [Qed] marks an identifier as%\index{opaque}% _opaque_, preventing unfolding.) Let us see what our proof script constructed. *)
adamc@70 297 fun n : nat =>
adamc@70 298 match n as n0 return (n0 > 0 -> {m : nat | n0 = S m}) with
adamc@70 300 fun _ : 0 > 0 =>
adamc@70 301 False_rec {m : nat | 0 = S m}
adamc@70 305 (Bool.absurd_eq_true false (pred_strong4_subproof n _)))))
adamc@70 306 | S n' =>
adamc@70 307 fun _ : S n' > 0 =>
adam@426 308 exist (fun m : nat => S n' = S m) n' (eq_refl (S n'))
adamc@70 310 : forall n : nat, n > 0 -> {m : nat | n = S m}
adam@442 313 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. *)
adam@282 315 Eval compute in pred_strong4 two_gt0.
adam@426 317 = exist (fun m : nat => 2 = S m) 1 (eq_refl 2)
adam@282 318 : {m : nat | 2 = S m}
adam@442 321 A tactic modifier called %\index{tactics!abstract}%[abstract] can be helpful for producing shorter terms, by automatically abstracting subgoals into named lemmas. *)
adam@335 323 (* begin thide *)
adam@335 324 Definition pred_strong4' : forall n : nat, n > 0 -> {m : nat | n = S m}.
adam@335 325 refine (fun n =>
adam@335 327 | O => fun _ => False_rec _ _
adam@335 328 | S n' => fun _ => exist _ n' _
adam@335 333 (* end thide *)
adam@335 337 fun n : nat =>
adam@335 338 match n as n0 return (n0 > 0 -> {m : nat | n0 = S m}) with
adam@335 340 fun _H : 0 > 0 =>
adam@335 341 False_rec {m : nat | 0 = S m} (pred_strong4'_subproof n _H)
adam@335 342 | S n' =>
adam@335 343 fun _H : S n' > 0 =>
adam@335 344 exist (fun m : nat => S n' = S m) n' (pred_strong4'_subproof0 n _H)
adam@335 346 : forall n : nat, n > 0 -> {m : nat | n = S m}
adam@338 349 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. In this book, we will not dwell on the details of syntax extensions; the Coq manual gives a straightforward introduction to them. *)
adamc@70 351 Notation "!" := (False_rec _ _).
adamc@70 352 Notation "[ e ]" := (exist _ e _).
adam@297 354 Definition pred_strong5 : forall n : nat, n > 0 -> {m : nat | n = S m}.
adamc@70 355 refine (fun n =>
adamc@70 357 | O => fun _ => !
adamc@70 358 | S n' => fun _ => [n']
adam@282 362 (** By default, notations are also used in pretty-printing terms, including results of evaluation. *)
adam@282 364 Eval compute in pred_strong5 two_gt0.
adam@282 367 : {m : nat | 2 = S m}
adam@442 370 One other alternative is worth demonstrating. Recent Coq versions include a facility called %\index{Program}%[Program] that streamlines this style of definition. Here is a complete implementation using [Program].%\index{Vernacular commands!Obligation Tactic}\index{Vernacular commands!Program Definition}% *)
adamc@212 372 Obligation Tactic := crush.
adamc@212 374 Program Definition pred_strong6 (n : nat) (_ : n > 0) : {m : nat | n = S m} :=
adamc@212 376 | O => _
adamc@212 377 | S n' => n'
adam@495 380 (** 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 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. *)
adam@282 382 Eval compute in pred_strong6 two_gt0.
adam@282 385 : {m : nat | 2 = S m}
adam@442 388 In this case, we see that the new definition yields the same computational behavior as before. *)
adamc@71 391 (** * Decidable Proposition Types *)
adam@495 393 (** There is another type in the standard library that captures the idea of program values that indicate which of two propositions is true.%\index{Gallina terms!sumbool}% *)
adamc@71 397 Inductive sumbool (A : Prop) (B : Prop) : Set :=
adamc@71 398 left : A -> {A} + {B} | right : B -> {A} + {B}
adam@471 401 Here, the constructors of [sumbool] have types written in terms of a registered notation for [sumbool], such that the result type of each constructor desugars to [sumbool A B]. We can define some notations of our own to make working with [sumbool] more convenient. *)
adamc@71 403 Notation "'Yes'" := (left _ _).
adamc@71 404 Notation "'No'" := (right _ _).
adamc@71 405 Notation "'Reduce' x" := (if x then Yes else No) (at level 50).
adam@436 407 (** The %\coqdocnotation{%#<tt>#Reduce#</tt>#%}% 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 409 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. *)
adam@297 411 Definition eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.
adamc@212 412 refine (fix f (n m : nat) : {n = m} + {n <> m} :=
adamc@212 413 match n, m with
adamc@71 414 | O, O => Yes
adamc@71 415 | S n', S m' => Reduce (f n' m')
adamc@71 416 | _, _ => No
adam@282 420 Eval compute in eq_nat_dec 2 2.
adam@282 423 : {2 = 2} + {2 <> 2}
adam@282 427 Eval compute in eq_nat_dec 2 3.
adam@341 430 : {2 = 3} + {2 <> 3}
adam@442 433 Note that the %\coqdocnotation{%#<tt>#Yes#</tt>#%}% and %\coqdocnotation{%#<tt>#No#</tt>#%}% notations are hiding proofs establishing the correctness of the outputs.
adam@335 435 Our definition extracts to reasonable OCaml code. *)
adamc@71 440 (** val eq_nat_dec : nat -> nat -> sumbool **)
adamc@71 442 let rec eq_nat_dec n m =
adamc@71 444 | O -> (match m with
adamc@71 445 | O -> Left
adamc@71 446 | S n0 -> Right)
adamc@71 447 | S n' -> (match m with
adamc@71 448 | O -> Right
adamc@71 449 | S m' -> eq_nat_dec n' m')
adamc@71 453 (** val eq_nat_dec : nat -> nat -> sumbool **)
adamc@71 455 let rec eq_nat_dec n m =
adamc@71 457 | O -> (match m with
adamc@71 458 | O -> Left
adamc@71 459 | S n0 -> Right)
adamc@71 460 | S n' -> (match m with
adamc@71 461 | O -> Right
adamc@71 462 | S m' -> eq_nat_dec n' m')
adam@335 465 Proving this kind of decidable equality result is so common that Coq comes with a tactic for automating it.%\index{tactics!decide equality}% *)
adamc@71 467 Definition eq_nat_dec' (n m : nat) : {n = m} + {n <> m}.
adam@448 471 (** 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 <<Left>> and <<Right>> 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.%\index{Vernacular commands!Extract Inductive}% *)
adamc@71 473 Extract Inductive sumbool => "bool" ["true" "false"].
adamc@71 477 (** val eq_nat_dec' : nat -> nat -> bool **)
adamc@71 479 let rec eq_nat_dec' n m0 =
adamc@71 481 | O -> (match m0 with
adamc@71 482 | O -> true
adamc@71 483 | S n0 -> false)
adamc@71 484 | S n0 -> (match m0 with
adamc@71 485 | O -> false
adamc@71 486 | S n1 -> eq_nat_dec' n0 n1)
adamc@71 490 (** val eq_nat_dec' : nat -> nat -> bool **)
adamc@71 492 let rec eq_nat_dec' n m0 =
adamc@71 494 | O -> (match m0 with
adamc@71 495 | O -> true
adamc@71 496 | S n0 -> false)
adamc@71 497 | S n0 -> (match m0 with
adamc@71 498 | O -> false
adamc@71 499 | S n1 -> eq_nat_dec' n0 n1)
adam@448 504 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." *)
adam@337 506 (* EX: Write a function that decides if an element belongs to a list. *)
adamc@77 508 (* begin thide *)
adamc@204 509 Notation "x || y" := (if x then Yes else Reduce y).
adamc@72 511 (** 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 514 Variable A : Set.
adamc@72 515 Variable A_eq_dec : forall x y : A, {x = y} + {x <> y}.
adamc@72 517 (** The final function is easy to write using the techniques we have developed so far. *)
adamc@212 519 Definition In_dec : forall (x : A) (ls : list A), {In x ls} + {~ In x ls}.
adamc@212 520 refine (fix f (x : A) (ls : list A) : {In x ls} + {~ In x ls} :=
adamc@72 522 | nil => No
adamc@72 523 | x' :: ls' => A_eq_dec x x' || f x ls'
adam@282 528 Eval compute in In_dec eq_nat_dec 2 (1 :: 2 :: nil).
adam@469 531 : {In 2 (1 :: 2 :: nil)} + { ~ In 2 (1 :: 2 :: nil)}
adam@282 535 Eval compute in In_dec eq_nat_dec 3 (1 :: 2 :: nil).
adam@469 538 : {In 3 (1 :: 2 :: nil)} + { ~ In 3 (1 :: 2 :: nil)}
adam@469 541 The [In_dec] function has a reasonable extraction to OCaml. *)
adamc@77 544 (* end thide *)
adamc@72 547 (** val in_dec : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 list -> bool **)
adamc@72 549 let rec in_dec a_eq_dec x = function
adamc@72 550 | Nil -> false
adamc@72 551 | Cons (x', ls') ->
adamc@72 552 (match a_eq_dec x x' with
adamc@72 553 | true -> true
adamc@72 554 | false -> in_dec a_eq_dec x ls')
adamc@72 558 (** val in_dec : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 list -> bool **)
adamc@72 560 let rec in_dec a_eq_dec x = function
adamc@72 561 | Nil -> false
adamc@72 562 | Cons (x', ls') ->
adamc@72 563 (match a_eq_dec x x' with
adamc@72 564 | true -> true
adamc@72 565 | false -> in_dec a_eq_dec x ls')
adam@403 568 This is more or the less code for the corresponding function from the OCaml standard library. *)
adamc@72 571 (** * Partial Subset Types *)
adam@335 573 (** 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 failure than returning a default value, as [pred] does for [0]. One approach is to define this type family %\index{Gallina terms!maybe}%[maybe], which is a version of [sig] that allows obligation-free failure. *)
adamc@89 575 Inductive maybe (A : Set) (P : A -> Prop) : Set :=
adamc@72 576 | Unknown : maybe P
adamc@72 577 | Found : forall x : A, P x -> maybe P.
adamc@73 579 (** We can define some new notations, analogous to those we defined for subset types. *)
adamc@72 581 Notation "{{ x | P }}" := (maybe (fun x => P)).
adamc@72 582 Notation "??" := (Unknown _).
adam@335 583 Notation "[| x |]" := (Found _ x _).
adamc@73 585 (** Now our next version of [pred] is trivial to write. *)
adam@297 587 Definition pred_strong7 : forall n : nat, {{m | n = S m}}.
adamc@73 588 refine (fun n =>
adam@380 589 match n return {{m | n = S m}} with
adamc@73 590 | O => ??
adam@335 591 | S n' => [|n'|]
adam@282 595 Eval compute in pred_strong7 2.
adam@282 598 : {{m | 2 = S m}}
adam@282 602 Eval compute in pred_strong7 0.
adam@282 605 : {{m | 0 = S m}}
adam@442 608 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 %\index{Gallina terms!sumor}%[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 612 Inductive sumor (A : Type) (B : Prop) : Type :=
adamc@73 613 inleft : A -> A + {B} | inright : B -> A + {B}
adam@442 616 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 618 Notation "!!" := (inright _ _).
adam@335 619 Notation "[|| x ||]" := (inleft _ [x]).
adam@335 621 (** 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. *)
adam@297 623 Definition pred_strong8 : forall n : nat, {m : nat | n = S m} + {n = 0}.
adamc@73 624 refine (fun n =>
adamc@73 626 | O => !!
adam@335 627 | S n' => [||n'||]
adam@282 631 Eval compute in pred_strong8 2.
adam@282 634 : {m : nat | 2 = S m} + {2 = 0}
adam@282 638 Eval compute in pred_strong8 0.
adam@282 641 : {m : nat | 0 = S m} + {0 = 0}
adam@335 645 (** As with our other maximally expressive [pred] function, we arrive at quite simple output values, thanks to notations. *)
adam@471 650 (** We can treat [maybe] like a monad%~\cite{Monads}\index{monad}\index{failure 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. %Note that the notation definition uses an ASCII \texttt{<-}, while later code uses (in this rendering) a nicer left arrow $\leftarrow$.% *)
adamc@72 652 Notation "x <- e1 ; e2" := (match e1 with
adamc@72 653 | Unknown => ??
adamc@72 654 | Found x _ => e2
adamc@72 656 (right associativity, at level 60).
adam@398 658 (** 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] _does_ find an answer, pass that answer on to [e2] to find the final result. The variable [x] can be considered bound in [e2].
adam@335 660 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. *)
adam@337 662 (* EX: Write a function that tries to compute predecessors of two [nat]s at once. *)
adam@337 664 (* begin thide *)
adam@297 665 Definition doublePred : forall n1 n2 : nat, {{p | n1 = S (fst p) /\ n2 = S (snd p)}}.
adamc@73 666 refine (fun n1 n2 =>
adamc@212 667 m1 <- pred_strong7 n1;
adamc@212 668 m2 <- pred_strong7 n2;
adam@337 671 (* end thide *)
adam@471 673 (** We can build a [sumor] version of the "bind" notation and use it to write a similarly straightforward version of this function. %Again, the notation definition exposes the ASCII syntax with an operator \texttt{<-{}-}, while the later code uses a nicer long left arrow $\longleftarrow$.% *)
clement@533 675 (** %\def\indash{-}\catcode-=13\def-{\indash\kern0pt }% *)
clement@533 676
adamc@73 677 Notation "x <-- e1 ; e2" := (match e1 with
adamc@73 678 | inright _ => !!
adamc@73 679 | inleft (exist x _) => e2
adamc@73 681 (right associativity, at level 60).
clement@533 683 (** %\catcode-=12% *)(* *)
adamc@73 684 (** printing * $\times$ *)
adam@337 686 (* EX: Write a more expressively typed version of the last exercise. *)
adam@337 688 (* begin thide *)
adam@297 689 Definition doublePred' : forall n1 n2 : nat,
adam@297 690 {p : nat * nat | n1 = S (fst p) /\ n2 = S (snd p)}
adamc@73 691 + {n1 = 0 \/ n2 = 0}.
adamc@73 692 refine (fun n1 n2 =>
adamc@212 693 m1 <-- pred_strong8 n1;
adamc@212 694 m2 <-- pred_strong8 n2;
adam@337 697 (* end thide *)
adam@392 699 (** This example demonstrates how judicious selection of notations can hide complexities in the rich types of programs. *)
adamc@72 702 (** * A Type-Checking Example *)
adam@335 704 (** We can apply these specification types to build a certified type checker for a simple expression language. *)
adamc@72 706 Inductive exp : Set :=
adamc@72 707 | Nat : nat -> exp
adamc@72 708 | Plus : exp -> exp -> exp
adamc@72 709 | Bool : bool -> exp
adamc@72 710 | And : exp -> exp -> exp.
adamc@75 712 (** We define a simple language of types and its typing rules, in the style introduced in Chapter 4. *)
adamc@72 714 Inductive type : Set := TNat | TBool.
adamc@72 716 Inductive hasType : exp -> type -> Prop :=
adamc@72 717 | HtNat : forall n,
adamc@72 718 hasType (Nat n) TNat
adamc@72 719 | HtPlus : forall e1 e2,
adamc@72 721 -> hasType e2 TNat
adamc@72 722 -> hasType (Plus e1 e2) TNat
adamc@72 723 | HtBool : forall b,
adamc@72 724 hasType (Bool b) TBool
adamc@72 725 | HtAnd : forall e1 e2,
adamc@72 727 -> hasType e2 TBool
adamc@72 728 -> hasType (And e1 e2) TBool.
adamc@75 730 (** It will be helpful to have a function for comparing two types. We build one using [decide equality]. *)
adamc@77 732 (* begin thide *)
adamc@75 733 Definition eq_type_dec : forall t1 t2 : type, {t1 = t2} + {t1 <> t2}.
adam@423 737 (** 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. *)
adamc@73 739 Notation "e1 ;; e2" := (if e1 then e2 else ??)
adamc@73 740 (right associativity, at level 60).
adam@335 742 (** 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 743 (* end thide *)
adam@297 745 Definition typeCheck : forall e : exp, {{t | hasType e t}}.
adamc@77 746 (* begin thide *)
adamc@72 749 refine (fix F (e : exp) : {{t | hasType e t}} :=
adam@380 750 match e return {{t | hasType e t}} with
adam@335 751 | Nat _ => [|TNat|]
adamc@72 752 | Plus e1 e2 =>
adamc@72 753 t1 <- F e1;
adamc@72 754 t2 <- F e2;
adam@335 758 | Bool _ => [|TBool|]
adamc@72 759 | And e1 e2 =>
adamc@72 760 t1 <- F e1;
adamc@72 761 t2 <- F e2;
adamc@77 766 (* end thide *)
adamc@75 769 (** Despite manipulating proofs, our type checker is easy to run. *)
adamc@72 771 Eval simpl in typeCheck (Nat 0).
adamc@75 774 : {{t | hasType (Nat 0) t}}
adamc@72 778 Eval simpl in typeCheck (Plus (Nat 1) (Nat 2)).
adamc@75 781 : {{t | hasType (Plus (Nat 1) (Nat 2)) t}}
adamc@72 785 Eval simpl in typeCheck (Plus (Nat 1) (Bool false)).
adamc@75 788 : {{t | hasType (Plus (Nat 1) (Bool false)) t}}
adam@442 791 The type checker also extracts to some reasonable OCaml code. *)
adamc@75 796 (** val typeCheck : exp -> type0 maybe **)
adamc@75 798 let rec typeCheck = function
adamc@75 799 | Nat n -> Found TNat
adamc@75 800 | Plus (e1, e2) ->
adamc@75 801 (match typeCheck e1 with
adamc@75 802 | Unknown -> Unknown
adamc@75 803 | Found t1 ->
adamc@75 804 (match typeCheck e2 with
adamc@75 805 | Unknown -> Unknown
adamc@75 806 | Found t2 ->
adamc@75 807 (match eq_type_dec t1 TNat with
adamc@75 809 (match eq_type_dec t2 TNat with
adamc@75 810 | true -> Found TNat
adamc@75 811 | false -> Unknown)
adamc@75 812 | false -> Unknown)))
adamc@75 813 | Bool b -> Found TBool
adamc@75 814 | And (e1, e2) ->
adamc@75 815 (match typeCheck e1 with
adamc@75 816 | Unknown -> Unknown
adamc@75 817 | Found t1 ->
adamc@75 818 (match typeCheck e2 with
adamc@75 819 | Unknown -> Unknown
adamc@75 820 | Found t2 ->
adamc@75 821 (match eq_type_dec t1 TBool with
adamc@75 823 (match eq_type_dec t2 TBool with
adamc@75 824 | true -> Found TBool
adamc@75 825 | false -> Unknown)
adamc@75 826 | false -> Unknown)))
adamc@75 830 (** val typeCheck : exp -> type0 maybe **)
adamc@75 832 let rec typeCheck = function
adamc@75 833 | Nat n -> Found TNat
adamc@75 834 | Plus (e1, e2) ->
adamc@75 835 (match typeCheck e1 with
adamc@75 836 | Unknown -> Unknown
adamc@75 837 | Found t1 ->
adamc@75 838 (match typeCheck e2 with
adamc@75 839 | Unknown -> Unknown
adamc@75 840 | Found t2 ->
adamc@75 841 (match eq_type_dec t1 TNat with
adamc@75 843 (match eq_type_dec t2 TNat with
adamc@75 844 | true -> Found TNat
adamc@75 845 | false -> Unknown)
adamc@75 846 | false -> Unknown)))
adamc@75 847 | Bool b -> Found TBool
adamc@75 848 | And (e1, e2) ->
adamc@75 849 (match typeCheck e1 with
adamc@75 850 | Unknown -> Unknown
adamc@75 851 | Found t1 ->
adamc@75 852 (match typeCheck e2 with
adamc@75 853 | Unknown -> Unknown
adamc@75 854 | Found t2 ->
adamc@75 855 (match eq_type_dec t1 TBool with
adamc@75 857 (match eq_type_dec t2 TBool with
adamc@75 858 | true -> Found TBool
adamc@75 859 | false -> Unknown)
adamc@75 860 | false -> Unknown)))
adam@423 865 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@77 867 (* begin thide *)
adamc@73 868 Notation "e1 ;;; e2" := (if e1 then e2 else !!)
adamc@73 869 (right associativity, at level 60).
adamc@75 871 (** Next, we prove a helpful lemma, which states that a given expression can have at most one type. *)
adamc@75 873 Lemma hasType_det : forall e t1,
adam@335 875 -> forall t2, hasType e t2
adamc@73 876 -> t1 = t2.
adamc@73 877 induction 1; inversion 1; crush.
adamc@75 880 (** Now we can define the type-checker. Its type expresses that it only fails on untypable expressions. *)
adamc@77 882 (* end thide *)
adam@297 883 Definition typeCheck' : forall e : exp, {t : type | hasType e t} + {forall t, ~ hasType e t}.
adamc@77 884 (* begin thide *)
adamc@75 887 (** We register all of the typing rules as hints. *)
adam@335 891 (** The lemma [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@75 893 (** Finally, the implementation of [typeCheck] can be transcribed literally, simply switching notations as needed. *)
adamc@212 895 refine (fix F (e : exp) : {t : type | hasType e t} + {forall t, ~ hasType e t} :=
adam@380 896 match e return {t : type | hasType e t} + {forall t, ~ hasType e t} with
adam@335 897 | Nat _ => [||TNat||]
adamc@73 898 | Plus e1 e2 =>
adamc@73 899 t1 <-- F e1;
adamc@73 900 t2 <-- F e2;
adam@335 904 | Bool _ => [||TBool||]
adamc@73 905 | And e1 e2 =>
adamc@73 906 t1 <-- F e1;
adamc@73 907 t2 <-- F e2;
adamc@73 911 end); clear F; crush' tt hasType; eauto.
adam@471 913 (** We clear [F], the local name for the recursive function, to avoid strange proofs that refer to recursive calls that we never make. Such a step is usually warranted when defining a recursive function with [refine]. The [crush] variant %\index{tactics!crush'}%[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 914 (* end thide *)
adamc@75 919 (** 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.
adam@335 921 Our new function remains easy to test: *)
adamc@73 923 Eval simpl in typeCheck' (Nat 0).
adamc@75 926 : {t : type | hasType (Nat 0) t} +
adamc@75 927 {(forall t : type, ~ hasType (Nat 0) t)}
adamc@73 931 Eval simpl in typeCheck' (Plus (Nat 1) (Nat 2)).