annotate src/Subset.v @ 71:db967eff40d7

sumbool
author Adam Chlipala <adamc@hcoop.net>
date Fri, 03 Oct 2008 12:02:44 -0400
parents 1e3c49602384
children 839d159cac5d
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@70 19 (** %\chapter{Subset Types and Variations}% *)
adamc@70 20
adamc@70 21 (** 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 22
adamc@70 23
adamc@70 24 (** * Introducing Subset Types *)
adamc@70 25
adamc@70 26 (** Let us consider several ways of implementing the natural number predecessor function. We start by displaying the definition from the standard library: *)
adamc@70 27
adamc@70 28 Print pred.
adamc@70 29 (** [[
adamc@70 30
adamc@70 31 pred = fun n : nat => match n with
adamc@70 32 | 0 => 0
adamc@70 33 | S u => u
adamc@70 34 end
adamc@70 35 : nat -> nat
adamc@70 36 ]] *)
adamc@70 37
adamc@70 38 (** We can use a new command, [Extraction], to produce an OCaml version of this function. *)
adamc@70 39
adamc@70 40 Extraction pred.
adamc@70 41
adamc@70 42 (** %\begin{verbatim}
adamc@70 43 (** val pred : nat -> nat **)
adamc@70 44
adamc@70 45 let pred = function
adamc@70 46 | O -> O
adamc@70 47 | S u -> u
adamc@70 48 \end{verbatim}%
adamc@70 49
adamc@70 50 #<pre>
adamc@70 51 (** val pred : nat -> nat **)
adamc@70 52
adamc@70 53 let pred = function
adamc@70 54 | O -> O
adamc@70 55 | S u -> u
adamc@70 56 </pre># *)
adamc@70 57
adamc@70 58 (** 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 59
adamc@70 60 Lemma zgtz : 0 > 0 -> False.
adamc@70 61 crush.
adamc@70 62 Qed.
adamc@70 63
adamc@70 64 Definition pred_strong1 (n : nat) : n > 0 -> nat :=
adamc@70 65 match n return (n > 0 -> nat) with
adamc@70 66 | O => fun pf : 0 > 0 => match zgtz pf with end
adamc@70 67 | S n' => fun _ => n'
adamc@70 68 end.
adamc@70 69
adamc@70 70 (** 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 71
adamc@70 72 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 73
adamc@70 74 (** [[
adamc@70 75 Definition pred_strong1' (n : nat) (pf : n > 0) : nat :=
adamc@70 76 match n with
adamc@70 77 | O => match zgtz pf with end
adamc@70 78 | S n' => n'
adamc@70 79 end.
adamc@70 80
adamc@70 81 [[
adamc@70 82 Error: In environment
adamc@70 83 n : nat
adamc@70 84 pf : n > 0
adamc@70 85 The term "pf" has type "n > 0" while it is expected to have type
adamc@70 86 "0 > 0"
adamc@70 87 ]]
adamc@70 88
adamc@70 89 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 90
adamc@70 91 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 92
adamc@70 93 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 94
adamc@70 95 Let us now take a look at the OCaml code Coq generates for [pred_strong1]. *)
adamc@70 96
adamc@70 97 Extraction pred_strong1.
adamc@70 98
adamc@70 99 (** %\begin{verbatim}
adamc@70 100 (** val pred_strong1 : nat -> nat **)
adamc@70 101
adamc@70 102 let pred_strong1 = function
adamc@70 103 | O -> assert false (* absurd case *)
adamc@70 104 | S n' -> n'
adamc@70 105 \end{verbatim}%
adamc@70 106
adamc@70 107 #<pre>
adamc@70 108 (** val pred_strong1 : nat -> nat **)
adamc@70 109
adamc@70 110 let pred_strong1 = function
adamc@70 111 | O -> assert false (* absurd case *)
adamc@70 112 | S n' -> n'
adamc@70 113 </pre># *)
adamc@70 114
adamc@70 115 (** 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 116
adamc@70 117 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 118
adamc@70 119 Print sig.
adamc@70 120 (** [[
adamc@70 121
adamc@70 122 Inductive sig (A : Type) (P : A -> Prop) : Type :=
adamc@70 123 exist : forall x : A, P x -> sig P
adamc@70 124 For sig: Argument A is implicit
adamc@70 125 For exist: Argument A is implicit
adamc@70 126 ]]
adamc@70 127
adamc@70 128 [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 129
adamc@70 130 We rewrite [pred_strong1], using some syntactic sugar for subset types. *)
adamc@70 131
adamc@70 132 Locate "{ _ : _ | _ }".
adamc@70 133 (** [[
adamc@70 134
adamc@70 135 Notation Scope
adamc@70 136 "{ x : A | P }" := sig (fun x : A => P)
adamc@70 137 : type_scope
adamc@70 138 (default interpretation)
adamc@70 139 ]] *)
adamc@70 140
adamc@70 141 Definition pred_strong2 (s : {n : nat | n > 0}) : nat :=
adamc@70 142 match s with
adamc@70 143 | exist O pf => match zgtz pf with end
adamc@70 144 | exist (S n') _ => n'
adamc@70 145 end.
adamc@70 146
adamc@70 147 Extraction pred_strong2.
adamc@70 148
adamc@70 149 (** %\begin{verbatim}
adamc@70 150 (** val pred_strong2 : nat -> nat **)
adamc@70 151
adamc@70 152 let pred_strong2 = function
adamc@70 153 | O -> assert false (* absurd case *)
adamc@70 154 | S n' -> n'
adamc@70 155 \end{verbatim}%
adamc@70 156
adamc@70 157 #<pre>
adamc@70 158 (** val pred_strong2 : nat -> nat **)
adamc@70 159
adamc@70 160 let pred_strong2 = function
adamc@70 161 | O -> assert false (* absurd case *)
adamc@70 162 | S n' -> n'
adamc@70 163 </pre>#
adamc@70 164
adamc@70 165 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 166
adamc@70 167 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 168
adamc@70 169 Definition pred_strong3 (s : {n : nat | n > 0}) : {m : nat | proj1_sig s = S m} :=
adamc@70 170 match s return {m : nat | proj1_sig s = S m} with
adamc@70 171 | exist 0 pf => match zgtz pf with end
adamc@70 172 | exist (S n') _ => exist _ n' (refl_equal _)
adamc@70 173 end.
adamc@70 174
adamc@70 175 (** 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 176
adamc@70 177 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 178
adamc@70 179 Extraction pred_strong3.
adamc@70 180
adamc@70 181 (** %\begin{verbatim}
adamc@70 182 (** val pred_strong3 : nat -> nat **)
adamc@70 183
adamc@70 184 let pred_strong3 = function
adamc@70 185 | O -> assert false (* absurd case *)
adamc@70 186 | S n' -> n'
adamc@70 187 \end{verbatim}%
adamc@70 188
adamc@70 189 #<pre>
adamc@70 190 (** val pred_strong3 : nat -> nat **)
adamc@70 191
adamc@70 192 let pred_strong3 = function
adamc@70 193 | O -> assert false (* absurd case *)
adamc@70 194 | S n' -> n'
adamc@70 195 </pre>#
adamc@70 196
adamc@70 197 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 198
adamc@70 199 Definition pred_strong4 (n : nat) : n > 0 -> {m : nat | n = S m}.
adamc@70 200 refine (fun n =>
adamc@70 201 match n return (n > 0 -> {m : nat | n = S m}) with
adamc@70 202 | O => fun _ => False_rec _ _
adamc@70 203 | S n' => fun _ => exist _ n' _
adamc@70 204 end).
adamc@70 205
adamc@70 206 (** 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 207
adamc@70 208 [[
adamc@70 209
adamc@70 210 2 subgoals
adamc@70 211
adamc@70 212 n : nat
adamc@70 213 _ : 0 > 0
adamc@70 214 ============================
adamc@70 215 False
adamc@70 216 ]]
adamc@70 217
adamc@70 218 [[
adamc@70 219
adamc@70 220 subgoal 2 is:
adamc@70 221 S n' = S n'
adamc@70 222 ]]
adamc@70 223
adamc@70 224 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 225
adamc@70 226 Undo.
adamc@70 227 refine (fun n =>
adamc@70 228 match n return (n > 0 -> {m : nat | n = S m}) with
adamc@70 229 | O => fun _ => False_rec _ _
adamc@70 230 | S n' => fun _ => exist _ n' _
adamc@70 231 end); crush.
adamc@70 232 Defined.
adamc@70 233
adamc@70 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 prooof script constructed. *)
adamc@70 235
adamc@70 236 Print pred_strong4.
adamc@70 237 (** [[
adamc@70 238
adamc@70 239 pred_strong4 =
adamc@70 240 fun n : nat =>
adamc@70 241 match n as n0 return (n0 > 0 -> {m : nat | n0 = S m}) with
adamc@70 242 | 0 =>
adamc@70 243 fun _ : 0 > 0 =>
adamc@70 244 False_rec {m : nat | 0 = S m}
adamc@70 245 (Bool.diff_false_true
adamc@70 246 (Bool.absurd_eq_true false
adamc@70 247 (Bool.diff_false_true
adamc@70 248 (Bool.absurd_eq_true false (pred_strong4_subproof n _)))))
adamc@70 249 | S n' =>
adamc@70 250 fun _ : S n' > 0 =>
adamc@70 251 exist (fun m : nat => S n' = S m) n' (refl_equal (S n'))
adamc@70 252 end
adamc@70 253 : forall n : nat, n > 0 -> {m : nat | n = S m}
adamc@70 254 ]]
adamc@70 255
adamc@70 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.
adamc@70 257
adamc@70 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. *)
adamc@70 259
adamc@70 260 Notation "!" := (False_rec _ _).
adamc@70 261 Notation "[ e ]" := (exist _ e _).
adamc@70 262
adamc@70 263 Definition pred_strong5 (n : nat) : n > 0 -> {m : nat | n = S m}.
adamc@70 264 refine (fun n =>
adamc@70 265 match n return (n > 0 -> {m : nat | n = S m}) with
adamc@70 266 | O => fun _ => !
adamc@70 267 | S n' => fun _ => [n']
adamc@70 268 end); crush.
adamc@70 269 Defined.
adamc@71 270
adamc@71 271
adamc@71 272 (** * Decidable Proposition Types *)
adamc@71 273
adamc@71 274 (** 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 275
adamc@71 276 Print sumbool.
adamc@71 277 (** [[
adamc@71 278
adamc@71 279 Inductive sumbool (A : Prop) (B : Prop) : Set :=
adamc@71 280 left : A -> {A} + {B} | right : B -> {A} + {B}
adamc@71 281 For left: Argument A is implicit
adamc@71 282 For right: Argument B is implicit
adamc@71 283 ]] *)
adamc@71 284
adamc@71 285 (** We can define some notations to make working with [sumbool] more convenient. *)
adamc@71 286
adamc@71 287 Notation "'Yes'" := (left _ _).
adamc@71 288 Notation "'No'" := (right _ _).
adamc@71 289 Notation "'Reduce' x" := (if x then Yes else No) (at level 50).
adamc@71 290
adamc@71 291 (** 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 292
adamc@71 293 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 294
adamc@71 295 Definition eq_nat_dec (n m : nat) : {n = m} + {n <> m}.
adamc@71 296 refine (fix f (n m : nat) {struct n} : {n = m} + {n <> m} :=
adamc@71 297 match n, m return {n = m} + {n <> m} with
adamc@71 298 | O, O => Yes
adamc@71 299 | S n', S m' => Reduce (f n' m')
adamc@71 300 | _, _ => No
adamc@71 301 end); congruence.
adamc@71 302 Defined.
adamc@71 303
adamc@71 304 (** Our definition extracts to reasonable OCaml code. *)
adamc@71 305
adamc@71 306 Extraction eq_nat_dec.
adamc@71 307
adamc@71 308 (** %\begin{verbatim}
adamc@71 309 (** val eq_nat_dec : nat -> nat -> sumbool **)
adamc@71 310
adamc@71 311 let rec eq_nat_dec n m =
adamc@71 312 match n with
adamc@71 313 | O -> (match m with
adamc@71 314 | O -> Left
adamc@71 315 | S n0 -> Right)
adamc@71 316 | S n' -> (match m with
adamc@71 317 | O -> Right
adamc@71 318 | S m' -> eq_nat_dec n' m')
adamc@71 319 \end{verbatim}%
adamc@71 320
adamc@71 321 #<pre>
adamc@71 322 (** val eq_nat_dec : nat -> nat -> sumbool **)
adamc@71 323
adamc@71 324 let rec eq_nat_dec n m =
adamc@71 325 match n with
adamc@71 326 | O -> (match m with
adamc@71 327 | O -> Left
adamc@71 328 | S n0 -> Right)
adamc@71 329 | S n' -> (match m with
adamc@71 330 | O -> Right
adamc@71 331 | S m' -> eq_nat_dec n' m')
adamc@71 332 </pre>#
adamc@71 333
adamc@71 334 Proving this kind of decidable equality result is so common that Coq comes with a tactic for automating it. *)
adamc@71 335
adamc@71 336 Definition eq_nat_dec' (n m : nat) : {n = m} + {n <> m}.
adamc@71 337 decide equality.
adamc@71 338 Defined.
adamc@71 339
adamc@71 340 (** 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 341
adamc@71 342 Extract Inductive sumbool => "bool" ["true" "false"].
adamc@71 343 Extraction eq_nat_dec'.
adamc@71 344
adamc@71 345 (** %\begin{verbatim}
adamc@71 346 (** val eq_nat_dec' : nat -> nat -> bool **)
adamc@71 347
adamc@71 348 let rec eq_nat_dec' n m0 =
adamc@71 349 match n with
adamc@71 350 | O -> (match m0 with
adamc@71 351 | O -> true
adamc@71 352 | S n0 -> false)
adamc@71 353 | S n0 -> (match m0 with
adamc@71 354 | O -> false
adamc@71 355 | S n1 -> eq_nat_dec' n0 n1)
adamc@71 356 \end{verbatim}%
adamc@71 357
adamc@71 358 #<pre>
adamc@71 359 (** val eq_nat_dec' : nat -> nat -> bool **)
adamc@71 360
adamc@71 361 let rec eq_nat_dec' n m0 =
adamc@71 362 match n with
adamc@71 363 | O -> (match m0 with
adamc@71 364 | O -> true
adamc@71 365 | S n0 -> false)
adamc@71 366 | S n0 -> (match m0 with
adamc@71 367 | O -> false
adamc@71 368 | S n1 -> eq_nat_dec' n0 n1)
adamc@71 369 </pre># *)