comparison src/Subset.v @ 70:1e3c49602384

Start of Subset
author Adam Chlipala <adamc@hcoop.net>
date Fri, 03 Oct 2008 11:39:59 -0400
parents
children db967eff40d7
comparison
equal deleted inserted replaced
69:de9f78d68053 70:1e3c49602384
1 (* Copyright (c) 2008, Adam Chlipala
2 *
3 * This work is licensed under a
4 * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0
5 * Unported License.
6 * The license text is available at:
7 * http://creativecommons.org/licenses/by-nc-nd/3.0/
8 *)
9
10 (* begin hide *)
11 Require Import List.
12
13 Require Import Tactics.
14
15 Set Implicit Arguments.
16 (* end hide *)
17
18
19 (** %\chapter{Subset Types and Variations}% *)
20
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. *)
22
23
24 (** * Introducing Subset Types *)
25
26 (** Let us consider several ways of implementing the natural number predecessor function. We start by displaying the definition from the standard library: *)
27
28 Print pred.
29 (** [[
30
31 pred = fun n : nat => match n with
32 | 0 => 0
33 | S u => u
34 end
35 : nat -> nat
36 ]] *)
37
38 (** We can use a new command, [Extraction], to produce an OCaml version of this function. *)
39
40 Extraction pred.
41
42 (** %\begin{verbatim}
43 (** val pred : nat -> nat **)
44
45 let pred = function
46 | O -> O
47 | S u -> u
48 \end{verbatim}%
49
50 #<pre>
51 (** val pred : nat -> nat **)
52
53 let pred = function
54 | O -> O
55 | S u -> u
56 </pre># *)
57
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. *)
59
60 Lemma zgtz : 0 > 0 -> False.
61 crush.
62 Qed.
63
64 Definition pred_strong1 (n : nat) : n > 0 -> nat :=
65 match n return (n > 0 -> nat) with
66 | O => fun pf : 0 > 0 => match zgtz pf with end
67 | S n' => fun _ => n'
68 end.
69
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].
71
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. *)
73
74 (** [[
75 Definition pred_strong1' (n : nat) (pf : n > 0) : nat :=
76 match n with
77 | O => match zgtz pf with end
78 | S n' => n'
79 end.
80
81 [[
82 Error: In environment
83 n : nat
84 pf : n > 0
85 The term "pf" has type "n > 0" while it is expected to have type
86 "0 > 0"
87 ]]
88
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.
90
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.
92
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.
94
95 Let us now take a look at the OCaml code Coq generates for [pred_strong1]. *)
96
97 Extraction pred_strong1.
98
99 (** %\begin{verbatim}
100 (** val pred_strong1 : nat -> nat **)
101
102 let pred_strong1 = function
103 | O -> assert false (* absurd case *)
104 | S n' -> n'
105 \end{verbatim}%
106
107 #<pre>
108 (** val pred_strong1 : nat -> nat **)
109
110 let pred_strong1 = function
111 | O -> assert false (* absurd case *)
112 | S n' -> n'
113 </pre># *)
114
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.
116
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]. *)
118
119 Print sig.
120 (** [[
121
122 Inductive sig (A : Type) (P : A -> Prop) : Type :=
123 exist : forall x : A, P x -> sig P
124 For sig: Argument A is implicit
125 For exist: Argument A is implicit
126 ]]
127
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.
129
130 We rewrite [pred_strong1], using some syntactic sugar for subset types. *)
131
132 Locate "{ _ : _ | _ }".
133 (** [[
134
135 Notation Scope
136 "{ x : A | P }" := sig (fun x : A => P)
137 : type_scope
138 (default interpretation)
139 ]] *)
140
141 Definition pred_strong2 (s : {n : nat | n > 0}) : nat :=
142 match s with
143 | exist O pf => match zgtz pf with end
144 | exist (S n') _ => n'
145 end.
146
147 Extraction pred_strong2.
148
149 (** %\begin{verbatim}
150 (** val pred_strong2 : nat -> nat **)
151
152 let pred_strong2 = function
153 | O -> assert false (* absurd case *)
154 | S n' -> n'
155 \end{verbatim}%
156
157 #<pre>
158 (** val pred_strong2 : nat -> nat **)
159
160 let pred_strong2 = function
161 | O -> assert false (* absurd case *)
162 | S n' -> n'
163 </pre>#
164
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.
166
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. *)
168
169 Definition pred_strong3 (s : {n : nat | n > 0}) : {m : nat | proj1_sig s = S m} :=
170 match s return {m : nat | proj1_sig s = S m} with
171 | exist 0 pf => match zgtz pf with end
172 | exist (S n') _ => exist _ n' (refl_equal _)
173 end.
174
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.
176
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. *)
178
179 Extraction pred_strong3.
180
181 (** %\begin{verbatim}
182 (** val pred_strong3 : nat -> nat **)
183
184 let pred_strong3 = function
185 | O -> assert false (* absurd case *)
186 | S n' -> n'
187 \end{verbatim}%
188
189 #<pre>
190 (** val pred_strong3 : nat -> nat **)
191
192 let pred_strong3 = function
193 | O -> assert false (* absurd case *)
194 | S n' -> n'
195 </pre>#
196
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. *)
198
199 Definition pred_strong4 (n : nat) : n > 0 -> {m : nat | n = S m}.
200 refine (fun n =>
201 match n return (n > 0 -> {m : nat | n = S m}) with
202 | O => fun _ => False_rec _ _
203 | S n' => fun _ => exist _ n' _
204 end).
205
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:
207
208 [[
209
210 2 subgoals
211
212 n : nat
213 _ : 0 > 0
214 ============================
215 False
216 ]]
217
218 [[
219
220 subgoal 2 is:
221 S n' = S n'
222 ]]
223
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. *)
225
226 Undo.
227 refine (fun n =>
228 match n return (n > 0 -> {m : nat | n = S m}) with
229 | O => fun _ => False_rec _ _
230 | S n' => fun _ => exist _ n' _
231 end); crush.
232 Defined.
233
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. *)
235
236 Print pred_strong4.
237 (** [[
238
239 pred_strong4 =
240 fun n : nat =>
241 match n as n0 return (n0 > 0 -> {m : nat | n0 = S m}) with
242 | 0 =>
243 fun _ : 0 > 0 =>
244 False_rec {m : nat | 0 = S m}
245 (Bool.diff_false_true
246 (Bool.absurd_eq_true false
247 (Bool.diff_false_true
248 (Bool.absurd_eq_true false (pred_strong4_subproof n _)))))
249 | S n' =>
250 fun _ : S n' > 0 =>
251 exist (fun m : nat => S n' = S m) n' (refl_equal (S n'))
252 end
253 : forall n : nat, n > 0 -> {m : nat | n = S m}
254 ]]
255
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.
257
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. *)
259
260 Notation "!" := (False_rec _ _).
261 Notation "[ e ]" := (exist _ e _).
262
263 Definition pred_strong5 (n : nat) : n > 0 -> {m : nat | n = S m}.
264 refine (fun n =>
265 match n return (n > 0 -> {m : nat | n = S m}) with
266 | O => fun _ => !
267 | S n' => fun _ => [n']
268 end); crush.
269 Defined.