comparison src/GeneralRec.v @ 351:bb1a470c1757

Well-founded recursion
author Adam Chlipala <adam@chlipala.net>
date Wed, 26 Oct 2011 15:12:21 -0400
parents ad315efc3b6b
children ab60b10890ed
comparison
equal deleted inserted replaced
350:ad315efc3b6b 351:bb1a470c1757
6 * The license text is available at: 6 * The license text is available at:
7 * http://creativecommons.org/licenses/by-nc-nd/3.0/ 7 * http://creativecommons.org/licenses/by-nc-nd/3.0/
8 *) 8 *)
9 9
10 (* begin hide *) 10 (* begin hide *)
11 Require Import List. 11 Require Import Arith List.
12 12
13 Require Import CpdtTactics. 13 Require Import CpdtTactics Coinductive.
14 14
15 Set Implicit Arguments. 15 Set Implicit Arguments.
16 (* end hide *) 16 (* end hide *)
17 17
18 18
19 (** %\chapter{General Recursion}% *) 19 (** %\chapter{General Recursion}% *)
20 20
21 (** Termination of all programs is a crucial property of Gallina. Nonterminating programs introduce logical inconsistency, where any theorem can be proved with an infinite loop. Coq uses a small set of conservative, syntactic criteria to check termination of all recursive definitions. These criteria are insufficient to support the natural encodings of a variety of important programming idioms. Further, since Coq makes it so convenient to encode mathematics computationally, with functional programs, we may find ourselves wanting to employ more complicated recursion in mathematical definitions.
22
23 What exactly are the conservative criteria that we run up against? For %\emph{%#<i>#recursive#</i>#%}% definitions, recursive calls are only allowed on %\emph{%#<i>#syntactic subterms#</i>#%}% of the original primary argument, a restriction known as %\index{primitive recursion}\emph{%#<i>#primitive recursion#</i>#%}%. In fact, Coq's handling of reflexive inductive types (those defined in terms of functions returning the same type) gives a bit more flexibility than in traditional primitive recursion, but the term is still applied commonly. In the previous chapter, we saw how %\emph{%#<i>#co-recursive#</i>#%}% definitions are checked against a syntactic guardness condition that guarantees productivity.
24
25 Many natural recursion patterns satisfy neither condition. For instance, there is our simple running example in this chapter, merge sort. We will study three different approaches to more flexible recursion, and the latter two of the approaches will even support definitions that may fail to terminate on certain inputs.
26
27 Before proceeding, it is important to note that the problem here is not as fundamental as it may appear. The final example of the previous chapter demonstrated what is called a %\index{deep embedding}\emph{%#<i>#deep embedding#</i>#%}% of the syntax and semantics of a programming language. That is, we gave a mathematical definition of a language of programs and their meanings. This language clearly admitted non-termination, and we could think of writing all our sophisticated recursive functions with such explicit syntax types. However, in doing so, we forfeit our chance to take advantage of Coq's very good built-in support for reasoning about Gallina programs. We would rather use a %\index{shallow embedding}\emph{%#<i>#shallow embedding#</i>#%}%, where we model informal constructs by encoding them as normal Gallina programs. Each of the three techniques of this chapter follows that style. *)
28
29
30 (** * Well-Founded Recursion *)
31
32 (** The essence of terminating recursion is that there are no infinite chains of nested recursive calls. This intuition is commonly mapped to the mathematical idea of a %\index{well-founded relation}\emph{%#<i>#well-founded relation#</i>#%}%, and the associated standard technique in Coq is %\index{well-founded recursion}\emph{%#<i>#well-founded recursion#</i>#%}%. The syntactic-subterm relation that Coq applies by default is well-founded, but many cases demand alternate well-founded relations. To demonstrate, let us see where we get stuck on attempting a standard merge sort implementation. *)
33
34 Section mergeSort.
35 Variable A : Type.
36 Variable le : A -> A -> bool.
37 (** We have a set equipped with some %``%#"#less-than-or-equal-to#"#%''% test. *)
38
39 (** A standard function inserts an element into a sorted list, preserving sortedness. *)
40
41 Fixpoint insert (x : A) (ls : list A) : list A :=
42 match ls with
43 | nil => x :: nil
44 | h :: ls' =>
45 if le x h
46 then x :: ls
47 else h :: insert x ls'
48 end.
49
50 (** We will also need a function to merge two sorted lists. (We use a less efficient implementation than usual, because the more efficient implementation already forces us to think about well-founded recursion, while here we are only interested in setting up the example of merge sort.) *)
51
52 Fixpoint merge (ls1 ls2 : list A) : list A :=
53 match ls1 with
54 | nil => ls2
55 | h :: ls' => insert h (merge ls' ls2)
56 end.
57
58 (** The last helper function for classic merge sort is the one that follows, to partition a list arbitrarily into two pieces of approximately equal length. *)
59
60 Fixpoint partition (ls : list A) : list A * list A :=
61 match ls with
62 | nil => (nil, nil)
63 | h :: nil => (h :: nil, nil)
64 | h1 :: h2 :: ls' =>
65 let (ls1, ls2) := partition ls' in
66 (h1 :: ls1, h2 :: ls2)
67 end.
68
69 (** Now, let us try to write the final sorting function, using a natural number %``%#"#[<=]#"#%''% test [leb] from the standard library.
70 [[
71 Fixpoint mergeSort (ls : list A) : list A :=
72 if leb (length ls) 2
73 then ls
74 else let lss := partition ls in
75 merge (mergeSort (fst lss)) (mergeSort (snd lss)).
76 ]]
77
78 <<
79 Recursive call to mergeSort has principal argument equal to
80 "fst (partition ls)" instead of a subterm of "ls".
81 >>
82
83 The definition is rejected for not following the simple primitive recursion criterion. In particular, it is not apparent that recursive calls to [mergeSort] are syntactic subterms of the original argument [ls]; indeed, they are not, yet we know this is a well-founded recursive definition.
84
85 To produce an acceptable definition, we need to choose a well-founded relation and prove that [mergeSort] respects it. A good starting point is an examination of how well-foundedness is formalized in the Coq standard library. *)
86
87 Print well_founded.
88 (** %\vspace{-.15in}% [[
89 well_founded =
90 fun (A : Type) (R : A -> A -> Prop) => forall a : A, Acc R a
91 ]]
92
93 The bulk of the definitional work devolves to the %\index{accessibility relation}\index{Gallina terms!Acc}\emph{%#<i>#accessibility#</i>#%}% relation [Acc], whose definition we may also examine. *)
94
95 Print Acc.
96 (** %\vspace{-.15in}% [[
97 Inductive Acc (A : Type) (R : A -> A -> Prop) (x : A) : Prop :=
98 Acc_intro : (forall y : A, R y x -> Acc R y) -> Acc R x
99 ]]
100
101 In prose, an element [x] is accessible for a relation [R] if every element %``%#"#less than#"#%''% [x] according to [R] is also accessible. Since [Acc] is defined inductively, we know that any accessibility proof involves a finite chain of invocations, in a certain sense which we can make formal. Building on last chapter's examples, let us define a co-inductive relation that is closer to the usual informal notion of %``%#"#absence of infinite decreasing chains.#"#%''% *)
102
103 CoInductive isChain A (R : A -> A -> Prop) : stream A -> Prop :=
104 | ChainCons : forall x y s, isChain R (Cons y s)
105 -> R y x
106 -> isChain R (Cons x (Cons y s)).
107
108 (** We can now prove that any accessible element cannot be the beginning of any infinite decreasing chain. *)
109
110 (* begin thide *)
111 Lemma noChains' : forall A (R : A -> A -> Prop) x, Acc R x
112 -> forall s, ~isChain R (Cons x s).
113 induction 1; crush;
114 match goal with
115 | [ H : isChain _ _ |- _ ] => inversion H; eauto
116 end.
117 Qed.
118
119 (** From here, the absence of infinite decreasing chains in well-founded sets is immediate. *)
120
121 Theorem noChains : forall A (R : A -> A -> Prop), well_founded R
122 -> forall s, ~isChain R s.
123 destruct s; apply noChains'; auto.
124 Qed.
125 (* end thide *)
126
127 (** Absence of infinite decreasing chains implies absence of infinitely nested recursive calls, for any recursive definition that respects the well-founded relation. The [Fix] combinator from the standard library formalizes that intuition: *)
128
129 Check Fix.
130 (** %\vspace{-.15in}%[[
131 Fix
132 : forall (A : Type) (R : A -> A -> Prop),
133 well_founded R ->
134 forall P : A -> Type,
135 (forall x : A, (forall y : A, R y x -> P y) -> P x) ->
136 forall x : A, P x
137 ]]
138
139 A call to %\index{Gallina terms!Fix}%[Fix] must present a relation [R] and a proof of its well-foundedness. The next argument, [P], is the possibly dependent range type of the function we build; the domain [A] of [R] is the function's domain. The following argument has this type:
140
141 [[
142 forall x : A, (forall y : A, R y x -> P y) -> P x
143 ]]
144
145 This is an encoding of the function body. The input [x] stands for the function argument, and the next input stands for the function we are defining. Recursive calls are encoded as calls to the second argument, whose type tells us it expects a value [y] and a proof that [y] is %``%#"#less than#"#%''% [x], according to [R]. In this way, we enforce the well-foundedness restriction on recursive calls.
146
147 The rest of [Fix]'s type tells us that it returns a function of exactly the type we expect, so we are now ready to use it to implement [mergeSort]. Careful readers may have noticed something unusual going on in the type of [Fix], where a program function takes a proof as an argument. Chapter 7 will include much more detail on that style of programming; here we will merely give a taste of what is to come.
148
149 Before writing [mergeSort], we need to settle on a well-founded relation. The right one for this example is based on lengths of lists. *)
150
151 Definition lengthOrder (ls1 ls2 : list A) :=
152 length ls1 < length ls2.
153
154 (** We must prove that the relation is truly well-founded. To save some space here, we skip right to nice, automated proof scripts, though we postpone introducing the principles behind such scripts into Part III of the book. Curious readers may still replace semicolons with periods and newlines to step through these scripts interactively. *)
155
156 Hint Constructors Acc.
157
158 Lemma lengthOrder_wf' : forall len, forall ls, length ls <= len -> Acc lengthOrder ls.
159 unfold lengthOrder; induction len; crush.
160 Defined.
161
162 Theorem lengthOrder_wf : well_founded lengthOrder.
163 red; intro; eapply lengthOrder_wf'; eauto.
164 Defined.
165
166 (** Notice that we end these proofs with %\index{Vernacular commands!Defined}%[Defined], not [Qed]. The alternate command marks the theorems as %\emph{transparent}%, so that the details of their proofs may be used during program execution. Why could such details possibly matter for computation? It turns out that [Fix] satisfies the primitive recursion restriction by declaring itself as %\emph{%#<i>#recursive in the structure of [Acc] proofs#</i>#%}%. This is possible because [Acc] proofs follow a predictable inductive structure. We must do work, as in the last theorem's proof, to establish that all elements of a type belong to [Acc], but the automatic unwinding of those proofs during recursion is straightforward. If we ended the proof with [Qed], the proof details would be hidden from computation, in which case the unwinding process would get stuck.
167
168 To justify our two recursive [mergeSort] calls, we will also need to prove that [partition] respects the [lengthOrder] relation. These proofs, too, must be kept transparent, to avoid stuckness of [Fix] evaluation. *)
169
170 Lemma partition_wf : forall len ls, 2 <= length ls <= len
171 -> let (ls1, ls2) := partition ls in
172 lengthOrder ls1 ls /\ lengthOrder ls2 ls.
173 unfold lengthOrder; induction len; crush; do 2 (destruct ls; crush);
174 destruct (le_lt_dec 2 (length ls));
175 repeat (match goal with
176 | [ _ : length ?E < 2 |- _ ] => destruct E
177 | [ _ : S (length ?E) < 2 |- _ ] => destruct E
178 | [ IH : _ |- context[partition ?L] ] =>
179 specialize (IH L); destruct (partition L); destruct IH
180 end; crush).
181 Defined.
182
183 Ltac partition := intros ls ?; intros; generalize (@partition_wf (length ls) ls);
184 destruct (partition ls); destruct 1; crush.
185
186 Lemma partition_wf1 : forall ls, 2 <= length ls
187 -> lengthOrder (fst (partition ls)) ls.
188 partition.
189 Defined.
190
191 Lemma partition_wf2 : forall ls, 2 <= length ls
192 -> lengthOrder (snd (partition ls)) ls.
193 partition.
194 Defined.
195
196 Hint Resolve partition_wf1 partition_wf2.
197
198 (** To write the function definition itself, we use the %\index{tactics!refine}%[refine] tactic as a convenient way to write a program that needs to manipulate proofs, without writing out those proofs manually. We also use a replacement [le_lt_dec] for [leb] that has a more interesting dependent type. Again, more detail on these points will come in Chapter 7. *)
199
200 Definition mergeSort : list A -> list A.
201 (* begin thide *)
202 refine (Fix lengthOrder_wf (fun _ => list A)
203 (fun (ls : list A)
204 (mergeSort : forall ls' : list A, lengthOrder ls' ls -> list A) =>
205 if le_lt_dec 2 (length ls)
206 then let lss := partition ls in
207 merge (mergeSort (fst lss) _) (mergeSort (snd lss) _)
208 else ls)); subst lss; eauto.
209 Defined.
210 (* end thide *)
211 End mergeSort.
212
213 (** The important thing is that it is now easy to evaluate calls to [mergeSort]. *)
214
215 Eval compute in mergeSort leb (1 :: 2 :: 36 :: 8 :: 19 :: nil).
216 (** [= 1 :: 2 :: 8 :: 19 :: 36 :: nil] *)
217
218 (** Since the subject of this chapter is merely how to define functions with unusual recursion structure, we will not prove any further correctness theorems about [mergeSort]. Instead, we stop at proving that [mergeSort] has the expected computational behavior, for all inputs, not merely the one we just tested. *)
219
220 (* begin thide *)
221 Theorem mergeSort_eq : forall A (le : A -> A -> bool) ls,
222 mergeSort le ls = if le_lt_dec 2 (length ls)
223 then let lss := partition ls in
224 merge le (mergeSort le (fst lss)) (mergeSort le (snd lss))
225 else ls.
226 intros; apply (Fix_eq (@lengthOrder_wf A) (fun _ => list A)); intros.
227
228 (** The library theorem [Fix_eq] imposes one more strange subgoal upon us. We must prove that the function body is unable to distinguish between %``%#"#self#"#%''% arguments that map equal inputs to equal outputs. One might think this should be true of any Gallina code, but in fact this general %\index{extensionality}\emph{%#<i>#function extensionality#</i>#%}% property is neither provable nor disprovable within Coq. The type of [Fix_eq] makes clear what we must show manually: *)
229
230 Check Fix_eq.
231 (** %\vspace{-.15in}%[[
232 Fix_eq
233 : forall (A : Type) (R : A -> A -> Prop) (Rwf : well_founded R)
234 (P : A -> Type)
235 (F : forall x : A, (forall y : A, R y x -> P y) -> P x),
236 (forall (x : A) (f g : forall y : A, R y x -> P y),
237 (forall (y : A) (p : R y x), f y p = g y p) -> F x f = F x g) ->
238 forall x : A,
239 Fix Rwf P F x = F x (fun (y : A) (_ : R y x) => Fix Rwf P F y)
240 ]]
241
242 Most such obligations are dischargable with straightforward proof automation, and this example is no exception. *)
243
244 match goal with
245 | [ |- context[match ?E with left _ => _ | right _ => _ end] ] => destruct E
246 end; simpl; f_equal; auto.
247 Qed.
248 (* end thide *)
249
250 (** As a final test of our definition's suitability, we can extract to OCaml. *)
251
252 Extraction mergeSort.
253
254 (** <<
255 let rec mergeSort le x =
256 match le_lt_dec (S (S O)) (length x) with
257 | Left ->
258 let lss = partition x in
259 merge le (mergeSort le (fst lss)) (mergeSort le (snd lss))
260 | Right -> x
261 >>
262
263 We see almost precisely the same definition we would have written manually in OCaml! Chapter 7 shows how we can clean up a few of the remaining warts, like use of the mysterious constructors [Left] and [Right].
264
265 One more piece of the full picture is missing. To go on and prove correctness of [mergeSort], we would need more than a way of unfolding its definition. We also need an appropriate induction principle matched to the well-founded relation. Such a principle is available in the standard library, though we will say no more about its details here. *)
266
267 Check well_founded_induction.
268 (** %\vspace{-.15in}%[[
269 well_founded_induction
270 : forall (A : Type) (R : A -> A -> Prop),
271 well_founded R ->
272 forall P : A -> Set,
273 (forall x : A, (forall y : A, R y x -> P y) -> P x) ->
274 forall a : A, P a
275 ]]
276
277 Some more recent Coq features provide more convenient syntax for defining recursive functions. Interested readers can consult the Coq manual about the commands %\index{Function}%[Function] and %\index{Program Fixpoint}%[Program Fixpoint]. *)