• API
• FAQ
• Tools
• Archive
daily pastebin goal
69%
SHARE
TWEET

# Untitled

a guest Jul 21st, 2018 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. (** * Lists: Working with Structured Data *)
2.
3. Require Export Induction.
4. Module NatList.
5.
6. (* ################################################################# *)
7. (** * Pairs of Numbers *)
8.
9. (** In an [Inductive] type definition, each constructor can take
10.     any number of arguments -- none (as with [true] and [O]), one (as
11.     with [S]), or more than one, as here: *)
12.
13. Inductive natprod : Type :=
14. | pair : nat -> nat -> natprod.
15.
16. (** This declaration can be read: "There is just one way to
17.     construct a pair of numbers: by applying the constructor [pair] to
18.     two arguments of type [nat]." *)
19.
20. Check (pair 3 5).
21.
22. (** Here are two simple functions for extracting the first and
23.     second components of a pair.  The definitions also illustrate how
24.     to do pattern matching on two-argument constructors. *)
25.
26. Definition fst (p : natprod) : nat :=
27.   match p with
28.   | pair x y => x
29.   end.
30.
31. Definition snd (p : natprod) : nat :=
32.   match p with
33.   | pair x y => y
34.   end.
35.
36. Compute (fst (pair 3 5)).
37. (* ===> 3 *)
38.
39. (** Since pairs are used quite a bit, it is nice to be able to
40.     write them with the standard mathematical notation [(x,y)] instead
41.     of [pair x y].  We can tell Coq to allow this with a [Notation]
42.     declaration. *)
43.
44. Notation "( x , y )" := (pair x y).
45.
46. (** The new pair notation can be used both in expressions and in
47.     pattern matches (indeed, we've actually seen this already in the
48.     [Basics] chapter, in the definition of the [minus] function --
49.     this works because the pair notation is also provided as part of
50.     the standard library): *)
51.
52. Compute (fst (3,5)).
53.
54. Definition fst' (p : natprod) : nat :=
55.   match p with
56.   | (x,y) => x
57.   end.
58.
59. Definition snd' (p : natprod) : nat :=
60.   match p with
61.   | (x,y) => y
62.   end.
63.
64. Definition swap_pair (p : natprod) : natprod :=
65.   match p with
66.   | (x,y) => (y,x)
67.   end.
68.
69. (** Let's try to prove a few simple facts about pairs.
70.
71.     If we state things in a particular (and slightly peculiar) way, we
72.     can complete proofs with just reflexivity (and its built-in
73.     simplification): *)
74.
75. Theorem surjective_pairing' : forall (n m : nat),
76.   (n,m) = (fst (n,m), snd (n,m)).
77. Proof.
78.   reflexivity. (* [reflexivity] can expand the definitions of [fst] and [snd]
79.                   to resolve this. *)
80. Qed.
81.
82. (* Informal proof:
83.
84.    Theorem: [forall n m : nat, (n, m) = (fst (n, m), snd (n, m))].
85.
86.    Proof: by definition of [fst] and [snd].
87.
88.    - The [fst] of [(n, m)] is [n], and the [snd] of [(n, m)] is [m].
89.      But that yields [(n, m)], which matches the left side of the equation.
90.
91.   - So the theorem is true for [n] and [m], by the reflexivity of equality.
92.
93.   - Since we've shown that the theorem holds for an arbitrary [n] and [m],
94.     we've shown that it holds for all [n]s and [m]s. []
95.
96. *)
97.
98. (** But [reflexivity] is not enough if we state the lemma in a more
99.     natural way: *)
100.
101. Theorem surjective_pairing_stuck : forall (p : natprod),
102.   p = (fst p, snd p). (* Note that [fst p] and [snd p] are not in a form that
103.                          matches a constructor pattern. The constructors need a pair
104.                          of the form [fst (_, _)]. But here, we only have [p],
105.                          and there is not enough information in this theorem for
106.                          Coq to match [p] to the structure [(_, _)]. *)
107. Proof.
108.   simpl. (* Doesn't reduce anything! *)
109. Abort.
110.
111. (** We have to expose the structure of [p] so that [simpl] can
112.     perform the pattern match in [fst] and [snd].  We can do this with
113.     [destruct]. *)
114.
115. Theorem surjective_pairing : forall (p : natprod),
116.   p = (fst p, snd p).
117. Proof.
118.   intros p. (* Suppose [p] is a fixed pair. *)
119.   destruct p as [n m]. (* Let's proceed by case analysis. That is, let's consider
120.                           the different forms that [p] can have. If we look at the [natprod]
121.                           constructor, we can see it only has one constructor. So there's
122.                           only one case here: [pair _ _]. Let's name the first item [n],
123.                           and the second item [m]. So this will generate a goal
124.                           where [p] is replaced with [(n, m)]. That is, the goal
125.                           will become [(n, m) = (fst (n, m), snd (n, m))]. *)
126.   simpl. (* Then [simpl] can match [fst (n, m)] and [snd (n, m)] to simplify
127.             the right hand side of the quation to [(n, m)]. *)
128.   reflexivity. (* Now both sides of the equation match. *)
129. Qed.
130.
131. (* Informal proof:
132.
133.    Theorem: [forall p : natprod, p = (fst p, snd p)].
134.
135.    Proof: by case analysis on [p].
136.
137.    - Let [p] be a fixed pair. There is just one form that [p] can take: [(n, m)],
138.      where [n] and [m] are fixed numbers.
139.
140.    - So let us replace every [p] with [(n, m)] in the theorem.
141.
142.    - Then both sides of the equation are the same, which follows from
143.      the definition of [fst] and [snd].
144.
145.   - So the theorem is true for [p], by the reflexivity of equality.
146.
147.   - Since we've shown that the theorem holds for an arbitrary [p],
148.     we've shown that it holds for all [p]s. []
149.
150. *)
151.
152. (** Notice that, unlike its behavior with [nat]s, [destruct]
153.     generates just one subgoal here.  That's because [natprod]s can
154.     only be constructed in one way. *)
155.
156. (** **** Exercise: 1 star (snd_fst_is_swap)  *)
157. Theorem snd_fst_is_swap : forall (p : natprod),
158.   (snd p, fst p) = swap_pair p.
159. Proof.
160.   intros p. (* Suppose [p] is a fixed pair. *)
161.   destruct p as [n m]. (* By case analysis, let's consider the one case it can have: [(n, m)].
162.                           That converts the goal to [(snd (n, m,), fst (n, m)) = swap_pair (n, m)]. *)
163.   simpl. (* [simpl] can now match the constructors for [snd], [fst], and [swap_pair], and simplify. *)
164.   reflexivity. (* Both sides of the equation are the same now. *)
165. Qed.
166. (** [] *)
167.
168. (* Informal proof:
169.
170.   Theorem: [forall p : natprod, (snd p, fst p) = swap_pair p].
171.
172.   Proof: by case analysis on [p].
173.
174.   - Suppose [p] be is a fixed pair. Then [p] can have the form [(n, m)], where
175.     [n] and [m] are fixed numbers.
176.
177.   - By the definition of [fst] and [snd], the left side of the equation reduces to [(m, n)],
178.     and by the definition of [swap_pair], the right hand side reduces to [(m, n)].
179.
180.   - So the theorem is true for [p], by the reflexivity of equality.
181.
182.   - Since we've shown that the theorem holds for an arbitrary [p],
183.     we've shown that it holds for all [p]s. []
184.
185. *)
186.
187. (** **** Exercise: 1 star, optional (fst_swap_is_snd)  *)
188. Theorem fst_swap_is_snd : forall (p : natprod),
189.   fst (swap_pair p) = snd p.
190. Proof.
191.   intros p. (* Suppose [p] is a fixed pair. *)
192.   destruct p as [n m]. (* Consider the one form it can have: [(n, m)]. *)
193.   simpl. (* [simpl] can match the constructors of [swap_pair], [fst], and [snd] to simplify. *)
194.   reflexivity. (* Now both sides of the equation are the same. *)
195. Qed.
196. (** [] *)
197.
198.
199. (* ################################################################# *)
200. (** * Lists of Numbers *)
201.
202. (** Generalizing the definition of pairs, we can describe the
203.     type of _lists_ of numbers like this: "A list is either the empty
204.     list or else a pair of a number and another list." *)
205.
206. Inductive natlist : Type :=
207.   | nil  : natlist
208.   | cons : nat -> natlist -> natlist.
209.
210. (** For example, here is a three-element list: *)
211.
212. Definition mylist := cons 1 (cons 2 (cons 3 nil)).
213.
214. (** As with pairs, it is more convenient to write lists in
215.     familiar programming notation.  The following declarations
216.     allow us to use [::] as an infix [cons] operator and square
217.     brackets as an "outfix" notation for constructing lists. *)
218.
219. Notation "x :: l" := (cons x l)
220.                      (at level 60, right associativity).
221. Notation "[ ]" := nil.
222. Notation "[ x ; .. ; y ]" := (cons x .. (cons y nil) ..).
223.
224. (** It is not necessary to understand the details of these
225.     declarations, but in case you are interested, here is roughly
226.     what's going on.  The [right associativity] annotation tells Coq
227.     how to parenthesize expressions involving several uses of [::] so
228.     that, for example, the next three declarations mean exactly the
229.     same thing: *)
230.
231. Definition mylist1 := 1 :: (2 :: (3 :: nil)).
232. Definition mylist2 := 1 :: 2 :: 3 :: nil.
233. Definition mylist3 := [1;2;3].
234.
235. (** The [at level 60] part tells Coq how to parenthesize
236.     expressions that involve both [::] and some other infix operator.
237.     For example, since we defined [+] as infix notation for the [plus]
238.     function at level 50,
239.
240.   Notation "x + y" := (plus x y)
241.                       (at level 50, left associativity).
242.
243.     the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]
244.     will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1
245.     + (2 :: [3])].
246.
247.     (Expressions like "[1 + 2 :: [3]]" can be a little confusing when
248.     you read them in a [.v] file.  The inner brackets, around 3, indicate
249.     a list, but the outer brackets, which are invisible in the HTML
250.     rendering, are there to instruct the "coqdoc" tool that the bracketed
251.     part should be displayed as Coq code rather than running text.)
252.
253.     The second and third [Notation] declarations above introduce the
254.     standard square-bracket notation for lists; the right-hand side of
255.     the third one illustrates Coq's syntax for declaring n-ary
256.     notations and translating them to nested sequences of binary
257.     constructors. *)
258.
259. (* ----------------------------------------------------------------- *)
260. (** *** Repeat *)
261.
262. (** A number of functions are useful for manipulating lists.
263.     For example, the [repeat] function takes a number [n] and a
264.     [count] and returns a list of length [count] where every element
265.     is [n]. *)
266.
267. Fixpoint repeat (n count : nat) : natlist :=
268.   match count with
269.   | O => nil (* If [count] is [0], return the empty list. *)
270.   | S count' => n :: (repeat n count') (* If [count] is the successor of [count'],
271.                                           put [n] in front of the list,
272.                                           and then [repeat n] again [count'] times. *)
273.   end.
274.
275. (* ----------------------------------------------------------------- *)
276. (** *** Length *)
277.
278. (** The [length] function calculates the length of a list. *)
279.
280. Fixpoint length (l:natlist) : nat :=
281.   match l with
282.   | nil => O (* If [l] is empty, the length is [0]. *)
283.   | h :: t => S (length t) (* If [l] has a head [h] and a tail [t], then
284.                               the length will be one more than (the successor [S] of)
285.                               the length of the tail [t]. *)
286.   end.
287.
288. (* ----------------------------------------------------------------- *)
289. (** *** Append *)
290.
291. (** The [app] function concatenates (appends) two lists. *)
292.
293. Fixpoint app (l1 l2 : natlist) : natlist :=
294.   match l1 with
295.   | nil    => l2 (* If [l1] is empty, just return [l2]. *)
296.   | h :: t => h :: (app t l2) (* If [l2] has a head [h] and a tail [t], put [h] at the front
297.                                  of the list, and then append the tail [t] to [l2]. *)
298.   end.
299.
300. (** Actually, [app] will be used a lot in some parts of what
301.     follows, so it is convenient to have an infix operator for it. *)
302.
303. Notation "x ++ y" := (app x y)
304.                      (right associativity, at level 60).
305.
306. Example test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5].
307. Proof. reflexivity.  Qed.
308. Example test_app2:             nil ++ [4;5] = [4;5].
309. Proof. reflexivity.  Qed.
310. Example test_app3:             [1;2;3] ++ nil = [1;2;3].
311. Proof. reflexivity.  Qed.
312.
313. (* ----------------------------------------------------------------- *)
314. (** *** Head (with default) and Tail *)
315.
316. (** Here are two smaller examples of programming with lists.
317.     The [hd] function returns the first element (the "head") of the
318.     list, while [tl] returns everything but the first
319.     element (the "tail").
320.     Of course, the empty list has no first element, so we
321.     must pass a default value to be returned in that case.  *)
322.
323. Definition hd (default:nat) (l:natlist) : nat :=
324.   match l with
325.   | nil => default (* If [l] is empty, return the [default]. *)
326.   | h :: t => h (* If [l] has a head [h] and a tail [t], return the head [h]. *)
327.   end.
328.
329. Definition tl (l:natlist) : natlist :=
330.   match l with
331.   | nil => nil (* If [l] is empty, there is no tail, so return an empty list. *)
332.   | h :: t => t (* If [l] has a head [h] and a tail [t], return the tail [t]. *)
333.   end.
334.
335. Example test_hd1:             hd 0 [1;2;3] = 1.
336. Proof.
337.   simpl. (* [simpl] can match the constructors/cases of [hd] to simplify. *)
338.   reflexivity. (* Now both sides of the equation are the same. *)
339. Qed.
340. Example test_hd2:             hd 0 [] = 0.
341. Proof.
342.   reflexivity. (* [reflexivity] can do the simplification too. *)
343. Qed.
344. Example test_tl:              tl [1;2;3] = [2;3].
345. Proof. reflexivity.  Qed.
346.
347.
348. (* ----------------------------------------------------------------- *)
349. (** *** Exercises *)
350.
351. (** **** Exercise: 2 stars, recommended (list_funs)  *)
352. (** Complete the definitions of [nonzeros], [oddmembers] and
353.     [countoddmembers] below. Have a look at the tests to understand
354.     what these functions should do. *)
355.
356. Fixpoint nonzeros (l:natlist) : natlist :=
357.   match l with
358.   | nil => nil (* If [l] is empty, return the empty list. *)
359.   | h :: t => match beq_nat h 0 with (* If [l] has a head [h] and a tail [t], then
360.                                         check if the head [h] is [0]. *)
361.               | true => nonzeros t (* If it is, then ignore [h] and
362.                                       check for nonzeros in the tail [t]. *)
363.               | false => h :: (nonzeros t) (* If it isn't, put [h] at the front of the return
364.                                               list, and check for nonzeros in the tail [t]. *)
365.               end
366.   end.
367.
368. Example test_nonzeros:
369.   nonzeros [0;1;0;2;3;0;0] = [1;2;3].
370. Proof.
371.   reflexivity. (* [reflexivity] can match the constructors/cases and simplify
372.                   until both sides of the equation are the same. *)
373. Qed.
374.
375. Fixpoint oddmembers (l:natlist) : natlist :=
376.   match l with
377.   | nil => nil
378.   | h :: t => match oddb h with
379.               | false => oddmembers t
380.               | true => h :: (oddmembers t)
381.               end
382.   end.
383.
384. Example test_oddmembers:
385.   oddmembers [0;1;0;2;3;0;0] = [1;3].
386. Proof. reflexivity. Qed.
387.
388. Definition countoddmembers (l:natlist) : nat :=
389.   length (oddmembers l).
390.
391. Example test_countoddmembers1:
392.   countoddmembers [1;0;3;1;4;5] = 4.
393. Proof. reflexivity. Qed.
394.
395. Example test_countoddmembers2:
396.   countoddmembers [0;2;4] = 0.
397. Proof. reflexivity. Qed.
398.
399.
400. Example test_countoddmembers3:
401.   countoddmembers nil = 0.
402. Proof. reflexivity. Qed.
403. (** [] *)
404.
405. (** **** Exercise: 3 stars, advanced (alternate)  *)
406. (** Complete the definition of [alternate], which "zips up" two lists
407.     into one, alternating between elements taken from the first list
408.     and elements from the second.  See the tests below for more
409.     specific examples.
410.
411.     Note: one natural and elegant way of writing [alternate] will fail
412.     to satisfy Coq's requirement that all [Fixpoint] definitions be
413.     "obviously terminating."  If you find yourself in this rut, look
414.     for a slightly more verbose solution that considers elements of
415.     both lists at the same time.  (One possible solution requires
416.     defining a new kind of pairs, but this is not the only way.)  *)
417.
418. Fixpoint alternate (l1 l2 : natlist) : natlist :=
419.   match l1, l2 with
420.   | nil, nil => nil (* If [l1] and [l2] are both empty, there's nothing to zip up,
421.                        so return an empty list. *)
422.   | nil, h :: t => l2 (* If [l1] is empty, but [l2] has a head [h] and a tail [t], then
423.                          [l2] has some contents, so we can just return that. *)
424.   | h :: t, nil => l1 (* Ditto if [l1] has contents and [l2] is empty. *)
425.   | h1 :: t1, h2 :: t2 => h1 :: (h2 :: (alternate t1 t2)) (* If [l1] has head [h1] and a tail [t1],
426.                       and [l2] has a head [h2] and a tail [t2], then put [h1] and [h2] as the
427.                       first items of the return list, and then alternate the tails [t1] and [t2]. *)
428.   end.
429.
430. Example test_alternate1:
431.   alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].
432. Proof. reflexivity. Qed.
433.
434. Example test_alternate2:
435.   alternate [1] [4;5;6] = [1;4;5;6].
436. Proof. reflexivity. Qed.
437.
438. Example test_alternate3:
439.   alternate [1;2;3] [4] = [1;4;2;3].
440. Proof. reflexivity. Qed.
441.
442. Example test_alternate4:
443.   alternate [] [20;30] = [20;30].
444. Proof. reflexivity. Qed.
445. (** [] *)
446.
447. (* ----------------------------------------------------------------- *)
448. (** *** Bags via Lists *)
449.
450. (** A [bag] (or [multiset]) is like a set, except that each element
451.     can appear multiple times rather than just once.  One possible
452.     implementation is to represent a bag of numbers as a list. *)
453.
454. Definition bag := natlist.
455.
456. (** **** Exercise: 3 stars, recommended (bag_functions)  *)
457. (** Complete the following definitions for the functions
458.     [count], [sum], [add], and [member] for bags. *)
459.
460. Fixpoint count (v:nat) (s:bag) : nat :=
461.   match s with
462.   | nil => 0 (* If [s] is empty, then there are no [v]s in it. *)
463.   | h :: t => match beq_nat h v with (* If [s] has a head [h] and a tail [t], then check if
464.                                         the head [h] is the same value as [v]. *)
465.               | false => count v t (* If it's not, then ignore [h], and
466.                                       count the [v]s in the tail [t]. *)
467.               | true => S (count v t) (* If it is, then the number of [v]s in [s] will be one more
468.                                          (the successor [S]) than the count of [v]s in the tail [t]. *)
469.               end
470.   end.
471.
472. (** All these proofs can be done just by [reflexivity]. *)
473.
474. Example test_count1:              count 1 [1;2;3;1;4;1] = 3.
475. Proof. reflexivity. Qed.
476. Example test_count2:              count 6 [1;2;3;1;4;1] = 0.
477. Proof. reflexivity. Qed.
478.
479. (** Multiset [sum] is similar to set [union]: [sum a b] contains all
480.     the elements of [a] and of [b].  (Mathematicians usually define
481.     [union] on multisets a little bit differently -- using max instead
482.     of sum -- which is why we don't use that name for this operation.)
483.     For [sum] we're giving you a header that does not give explicit
484.     names to the arguments.  Moreover, it uses the keyword
485.     [Definition] instead of [Fixpoint], so even if you had names for
486.     the arguments, you wouldn't be able to process them recursively.
487.     The point of stating the question this way is to encourage you to
488.     think about whether [sum] can be implemented in another way --
489.     perhaps by using functions that have already been defined.  *)
490.
491. Definition sum : bag -> bag -> bag := app. (* We can just append all the bags together. *)
492.
493. Example test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.
494. Proof.
495.   reflexivity. (* [reflexivity] can still just match the constructors/cases and simplify. *)
496. Qed.
497.
498. Definition add (v:nat) (s:bag) : bag := v :: s. (* We can just put [v] at the front of the bag [s]. *)
499.
501. Proof. reflexivity. Qed.
503. Proof. reflexivity. Qed.
504.
505. Definition member (v:nat) (s:bag) : bool :=
506.   match count v s with (* Count how many [v]s are in [s]. *)
507.   | 0 => false (* If there are zero [v]s in [s], then [v] is not a member of [s]. *)
508.   | _ => true (* If there is any (other) number of [v]s in [s], then [v] is a member of [s]. *)
509.   end.
510.
511. Example test_member1:             member 1 [1;4;1] = true.
512. Proof. reflexivity. Qed.
513.
514. Example test_member2:             member 2 [1;4;1] = false.
515. Proof. reflexivity. Qed.
516. (** [] *)
517.
518. (** **** Exercise: 3 stars, optional (bag_more_functions)  *)
519. (* Do not modify the following line: *)
520. Definition manual_grade_for_bag_theorem : option (prod nat string) := None.
521. (** Here are some more [bag] functions for you to practice with. *)
522.
523. (** When [remove_one] is applied to a bag without the number to remove,
524.    it should return the same bag unchanged. *)
525.
526. Fixpoint remove_one (v:nat) (s:bag) : bag :=
527.   match s with
528.   | nil => nil (* If the bag [s] is empty, there are no [v]s to remove. Just return the empty list. *)
529.   | h :: t => match beq_nat h v with (* If the bag [s] has a head [h] and a tail [t], check if
530.                                         the head [h] is the same value as [v]. *)
531.               | true => t (* If it is, drop [h] and return just the tail [t]. *)
532.               | false => h :: (remove_one v t) (* If it's not, put [h] at the front of the return
533.                                                   list, and then remove one [v] from the tail [t]. *)
534.               end
535.   end.
536.
537. Example test_remove_one1:
538.   count 5 (remove_one 5 [2;1;5;4;1]) = 0.
539. Proof. reflexivity. Qed.
540.
541. Example test_remove_one2:
542.   count 5 (remove_one 5 [2;1;4;1]) = 0.
543. Proof. reflexivity. Qed.
544.
545. Example test_remove_one3:
546.   count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.
547. Proof. reflexivity. Qed.
548.
549. Example test_remove_one4:
550.   count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.
551. Proof. reflexivity. Qed.
552.
553. Fixpoint remove_all (v:nat) (s:bag) : bag :=
554.   match s with
555.   | nil => nil (* If [s] is empty, there are no [v]s to remove. So just return the empty list. *)
556.   | h :: t => match beq_nat h v with (* If [s] has a head [h] and a tail [t], check if [h]
557.                                         has the same value as [v]. *)
558.               | true => (remove_all v t) (* If it does, then drop the [h], and then remove all
559.                                             [v]s from the tail. *)
560.               | false => h :: (remove_all v t) (* If it doesn't, put the [h] at the front of the
561.                                                   return list, and remove all [v]s from [t]. *)
562.               end
563.   end.
564.
565. Example test_remove_all1:  count 5 (remove_all 5 [2;1;5;4;1]) = 0.
566. Proof. reflexivity. Qed.
567. Example test_remove_all2:  count 5 (remove_all 5 [2;1;4;1]) = 0.
568. Proof. reflexivity. Qed.
569. Example test_remove_all3:  count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.
570. Proof. reflexivity. Qed.
571. Example test_remove_all4:  count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.
572. Proof. reflexivity. Qed.
573.
574. (* Note: an empty multiset is a subset of every other multiset. *)
575. Fixpoint subset (s1:bag) (s2:bag) : bool :=
576.   match s1, s2 with
577.   | nil, nil => true (* If [s1] and [s2] are empty, then the first is a subset of the other. *)
578.   | nil, h :: t => true (* If [s1] is empty and [s2] has some contents (because it has a head [h]
579.                            and a tail [t]), then [s1] is a subset of [s2]. *)
580.   | h :: t, nil => false (* If [s1] has contents (because it has a head [h] and a tail [t]) and [s2]
581.                             is empty, then [s1] is not a subset of [s2]. *)
582.   | h1 :: t1, h2 :: t2 => match member h1 s2 with (* If [s1] has a head [h1] and a tail [t1], and if
583.                             [s2] has a head [h2] and a tail [t2], then check if the head [h1] of the
584.                             first bag is a member of [s2]. *)
585.                           | true => subset t1 (remove_one h1 s2) (* If it is, then remove [h1] from
586.                             [s2], and check if the tail [t1] of the first bag is a subset of that. *)
587.                           | false => false (* If [h1] is not a member of [s2], then we've found an
588.                              element in [s1] that's not in [s2]. This means [s1] cannot be a subset
589.                              of [s2], since to be a subset requires that all members of [s1] are
590.                              members of [s2]. *)
591.                           end
592.   end.
593.
594. Compute subset [1;2;2] [2;1;4;1].
595.
596. Example test_subset1:              subset [1;2] [2;1;4;1] = true.
597. Proof. reflexivity. Qed.
598. Example test_subset2:              subset [1;2;2] [2;1;4;1] = false.
599. Proof. reflexivity. Qed.
600. (** [] *)
601.
602. (** **** Exercise: 3 stars, recommended (bag_theorem)  *)
603. (** Write down an interesting theorem [bag_theorem] about bags
604.     involving the functions [count] and [add], and prove it.  Note
605.     that, since this problem is somewhat open-ended, it's possible
606.     that you may come up with a theorem which is true, but whose proof
607.     requires techniques you haven't learned yet.  Feel free to ask for
608.     help if you get stuck! *)
609.
610. (*
611. Theorem bag_theorem : ...
612. Proof.
613.   ...
614. Qed.
615. *)
616.
617. Theorem my_bag_theorem : forall s : bag, count 0 (add 0 s) = S (count 0 s).
618. Proof.
619.   intros s. (* Suppose [s] is a fixed bag. *)
620.   simpl. (* [simpl] can reduce the left hand side to [S (count 0 s). *)
621.     reflexivity. (* So both sides of the equation are the same. *)
622. Qed.
623. (** [] *)
624.
625. (* Informal proof:
626.
627.    Theorem: [forall s : bag, count 0 (add 0 s) = S (count 0 s)].
628.
629.    Proof: by the definition of [count] and [add] for bags.
630.
631.    - Suppose [s] is a fixed bag of numbers.
632.
633.    - Adding a [0] to [s], and then counting the zeros in [s], means that the
634.      number of [0]s in [s] will be one more than (the successor [S] of) counting
635.      the [0]s is [s], which is exactly what the other side of the equation says.
636.
637.    - So both sides of the equation are the same. The theorem is true for [s] by the
638.      reflexivity of equality.
639.
640.    - Since we've shown that the theorem holds for an arbitrary [s], we've shown that
641.      it holds for all [s]s. []
642.
643. *)
644.
645. (* ################################################################# *)
646. (** * Reasoning About Lists *)
647.
648. (** As with numbers, simple facts about list-processing
649.     functions can sometimes be proved entirely by simplification.  For
650.     example, the simplification performed by [reflexivity] is enough
651.     for this theorem... *)
652.
653. Theorem nil_app : forall l:natlist,
654.   [] ++ l = l.
655. Proof.
656.   reflexivity. (* [reflexivity] can match the constructors of [++] to simplify this. *)
657. Qed.
658.
659. (** ...because the [[]] is substituted into the
660.     "scrutinee" (the expression whose value is being "scrutinized" by
661.     the match) in the definition of [app], allowing the match itself
662.     to be simplified. *)
663.
664. (** Also, as with numbers, it is sometimes helpful to perform case
665.     analysis on the possible shapes (empty or non-empty) of an unknown
666.     list. *)
667.
668. Theorem tl_length_pred : forall l:natlist,
669.   pred (length l) = length (tl l).
670. Proof.
671.   intros l. (* Suppose [l] is a fixed list. *)
672.   destruct l as [| n l']. (* Let's consider the possible shapes a list can take. If you look
673.                              at the constructors for lists, there are two cases. One where
674.                              [l] is empty [nil], and the other where it [cons]s a number [n]
675.                              to another list [l']. Let's consider both cases. For the second
676.                              case, let's call the number [n] and the other list [l']. *)
677.   - (* Case: [l = nil] *)
678.     (* We need to show that one less than (i.e., the predecessor of) the length of [[]]
679.        is the same as the length of the tail of [[]]. *)
680.     reflexivity. (* The length of [[]] is [0], and the predessor of [0] is [0]. The tail of [[]]
681.                     is also an empty list [[]], so it's length is [0] too.
682.                     Both sides of the equation are the same. [reflexivity] can match these
683.                     cases in the constructors/definitions to simplify. *)
684.   - (* Case: [l = cons n l'] *)
685.     (* We need to show that one less than (i.e., the predecessor of) the length of [n :: l']
686.        is the same as the length of the tail of [n :: l']. *)
687.     simpl. (* We can simplify out (or "cancel out") the [pred] and [n] on the left side of the
688.               equation. That makes the left side just [length l']. Similarly, on the right hand
689.               side, we can take just the tail of [n :: l'], and get the length of that. So the
690.               right hand side of the equation is als [length l']. *)
691.     reflexivity. (* Both sides of the equation are the same now. *)
692. Qed.
693.
694. (* Informal proof:
695.
696.    Theorem: [forall l: natlist, pred (length l) = length (tl l)].
697.
698.    Proof: By case analysis on [l].
699.
700.    - Suppose [l] is a fixed list of numbers.
701.
702.    - Let's proceed by case analysis on [l].
703.
704.      - First, suppose [l] is the empty list [[]].
705.
706.        - On the left hand side of the equation: then the length of [[]] is [0],
707.          and the predecessor [pred] of [0] is [0].
708.
709.        - On the right hand side of the equation: the tail of [[]] is [[]],
710.          whose length is [0].
711.
712.        - Since both sides of the equation are the same, the theorem holds in this
713.          case by the reflexivity of equality.
714.
715.      - Second, suppose [l] is [cons n l'].
716.
717.        - On the left hand side of the equation, the predesesor of the length of [n :: l']
718.          will be the length of [l'].
719.
720.        - On the right hand side of the equation, the length of the tail of [n :: l']
721.          will be the length of [l'].
722.
723.        - Since both sides of the equation are the same, the theorem holds in this
724.          case by the reflexivity of equality.
725.
726.    - So the theorem holds for all shapes of [l].
727.
728.    - Since we've shown that the theorem holds for an arbitrary [l], we've shown that
729.      it holds for all [l]s. []
730.
731.  *)
732.
733. (** Here, the [nil] case works because we've chosen to define
734.     [tl nil = nil]. Notice that the [as] annotation on the [destruct]
735.     tactic here introduces two names, [n] and [l'], corresponding to
736.     the fact that the [cons] constructor for lists takes two
737.     arguments (the head and tail of the list it is constructing). *)
738.
739. (** Usually, though, interesting theorems about lists require
740.     induction for their proofs. *)
741.
742. (* ----------------------------------------------------------------- *)
743. (** *** Micro-Sermon *)
744.
745. (** Simply reading example proof scripts will not get you very far!
746.     It is important to work through the details of each one, using Coq
747.     and thinking about what each step achieves.  Otherwise it is more
748.     or less guaranteed that the exercises will make no sense when you
749.     get to them.  'Nuff said. *)
750.
751. (* ================================================================= *)
752. (** ** Induction on Lists *)
753.
754. (** Proofs by induction over datatypes like [natlist] are a
755.     little less familiar than standard natural number induction, but
756.     the idea is equally simple.  Each [Inductive] declaration defines
757.     a set of data values that can be built up using the declared
758.     constructors: a boolean can be either [true] or [false]; a number
759.     can be either [O] or [S] applied to another number; a list can be
760.     either [nil] or [cons] applied to a number and a list.
761.
762.     Moreover, applications of the declared constructors to one another
763.     are the _only_ possible shapes that elements of an inductively
764.     defined set can have, and this fact directly gives rise to a way
765.     of reasoning about inductively defined sets: a number is either
766.     [O] or else it is [S] applied to some _smaller_ number; a list is
767.     either [nil] or else it is [cons] applied to some number and some
768.     _smaller_ list; etc. So, if we have in mind some proposition [P]
769.     that mentions a list [l] and we want to argue that [P] holds for
770.     _all_ lists, we can reason as follows:
771.
772.       - First, show that [P] is true of [l] when [l] is [nil].
773.
774.       - Then show that [P] is true of [l] when [l] is [cons n l'] for
775.         some number [n] and some smaller list [l'], assuming that [P]
776.         is true for [l'].
777.
778.     Since larger lists can only be built up from smaller ones,
779.     eventually reaching [nil], these two arguments together establish
780.     the truth of [P] for all lists [l].  Here's a concrete example: *)
781.
782. Theorem app_assoc : forall l1 l2 l3 : natlist,
783.   (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).
784. Proof.
785.   intros l1 l2 l3. (* Suppose that [l1], [l2], and [l3] are fixed natural numbers. *)
786.   induction l1 as [| n l1' IHl1']. (* Let's proceed by case analysis on [l1].
787.                                       [l1] can have the form [[]], or [n :: l1'].
788.                                       Also, let's assume that the theorem holds for
789.                                       [l1']. Let's call that [IHl1']. *)
790.   - (* Case: [l1 = nil] *)
791.     (* We need to show that [([] ++ l2) ++ l3 = [] ++ (l2 ++ l3)]. *)
792.     reflexivity. (* [reflexivity] can remove the empty list from the equation by simplifying it,
793.                     and then both sides of the equation are the same. *)
794.   - (* Case [l1 = cons n l1'] *)
795.     (* We need to show that [((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ l2 ++ l3],
796.        when [(l1' ++ l2) ++ l3 = l1' ++ l2 ++ l3] (the induction hypothesis. *)
797.     simpl. (* [simpl] can move the [n] out front. I'm not sure how it does this. *)
798.     rewrite -> IHl1'. (* But now the induction hypothesis matches par of the left hand side
799.                          of the equation. So, we can replace the matching part. *)
800.     reflexivity. (* Now both sides of the equation are the same. *)
801. Qed.
802.
803. (* Informal proof:
804.
805.    Theorem: [forall l1 l2 l3 : natlist, (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].
806.
807.    Proof: by inductionon [l1].
808.
809.    - Suppose [l1], [l2], and [l3] are each a fixed list of numbers.
810.
811.    - First, consider the case where [l1] = [nil]. We need to show:
812.
813.        [([] ++ l2) ++ l3 = [] ++ l2 ++ l3].
814.
815.      - By the definition of [++], appending empty lists to other lists has
816.        no effect, so we can drop the empty lists. That yields
817.        [l2 ++ l3 = l2 ++ l3].
818.
819.      - Then both sides of the equation are the same, so the theorem holds
820.        for this case, by the reflexivity of equality.
821.
822.    - Second, consider the case where [l1] is a list with a head element [n]
823.      and a tail list [l1'], and assume the induction hypothesis:
824.
825.        [(l1' ++ l2) ++ l3 = l1' ++ l2 ++ l3]
826.
827.    -  We need to show that:
828.
829.        [((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ l2 ++ l3]
830.
831.        - By the definition of [cons], we can move the [n] up front on both sides
832.          of the equation, which yields:
833.
834.            [n :: (l1' ++ l2) ++ l3 = n :: l1' ++ l2 ++ l3]
835.
836.        - The induction hypothesis says [(l1' ++ l2) ++ l3] is the same as
837.          [l1' ++ l2 ++ l3], so we can replace [l1' ++ l2 ++ l3] with
838.          [(l1' ++ l2) ++ l3]. That yields:
839.
840.            [n :: (l1' ++ l2) ++ l3 = n :: (l1' ++ l2) ++ l3]
841.
842.        - Both sides of the equation are the same, so the theorem holds for
843.          this case too, by the reflexivity of equality.
844.
845.    - We've shown that the theorem holds for all shapes that [l1] can take.
846.
847.    - Since we've shown that the theorem holds for an arbitrary [l1], [l2], and [l3],
848.      we've shown that the theorem holds for all [l1], [l2], and [l3]. []
849.
850. *)
851.
852. (** Notice that, as when doing induction on natural numbers, the
853.     [as...] clause provided to the [induction] tactic gives a name to
854.     the induction hypothesis corresponding to the smaller list [l1']
855.     in the [cons] case. Once again, this Coq proof is not especially
856.     illuminating as a static written document -- it is easy to see
857.     what's going on if you are reading the proof in an interactive Coq
858.     session and you can see the current goal and context at each
859.     point, but this state is not visible in the written-down parts of
860.     the Coq proof.  So a natural-language proof -- one written for
861.     human readers -- will need to include more explicit signposts; in
862.     particular, it will help the reader stay oriented if we remind
863.     them exactly what the induction hypothesis is in the second
864.     case. *)
865.
866. (** For comparison, here is an informal proof of the same theorem. *)
867.
868. (** _Theorem_: For all lists [l1], [l2], and [l3],
869.    [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].
870.
871.    _Proof_: By induction on [l1].
872.
873.    - First, suppose [l1 = []].  We must show
874.
875.        ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),
876.
877.      which follows directly from the definition of [++].
878.
879.    - Next, suppose [l1 = n::l1'], with
880.
881.        (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)
882.
883.      (the induction hypothesis). We must show
884.
885.        ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).
886.
887.      By the definition of [++], this follows from
888.
889.        n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),
890.
891.      which is immediate from the induction hypothesis.  [] *)
892.
893. (* ----------------------------------------------------------------- *)
894. (** *** Reversing a List *)
895.
896. (** For a slightly more involved example of inductive proof over
897.     lists, suppose we use [app] to define a list-reversing function
898.     [rev]: *)
899.
900. Fixpoint rev (l:natlist) : natlist :=
901.   match l with
902.   | nil    => nil (* If [l] is empty, there's nothing to reverse. *)
903.   | h :: t => rev t ++ [h] (* If [l] has head [h] and a tail [t], reverse the tail [t],
904.                               then append the head [h] to the end of that. *)
905.   end.
906.
907. Example test_rev1:            rev [1;2;3] = [3;2;1].
908. Proof. reflexivity.  Qed.
909. Example test_rev2:            rev nil = nil.
910. Proof. reflexivity.  Qed.
911.
912. (* ----------------------------------------------------------------- *)
913. (** *** Properties of [rev] *)
914.
915. (** Now let's prove some theorems about our newly defined [rev].
916.     For something a bit more challenging than what we've seen, let's
917.     prove that reversing a list does not change its length.  Our first
918.     attempt gets stuck in the successor case... *)
919.
920. Theorem rev_length_firsttry : forall l : natlist,
921.   length (rev l) = length l.
922. Proof.
923.   intros l. (* Suppose [l] is a fixed list of numbers. *)
924.   induction l as [| n l' IHl'].
925.   - (* l = [] *)
926.     reflexivity.
927.   - (* l = n :: l' *)
928.     (* This is the tricky case.  Let's begin as usual
929.        by simplifying. *)
930.     simpl.
931.     (* Now we seem to be stuck: the goal is an equality
932.        involving [++], but we don't have any useful equations
933.        in either the immediate context or in the global
934.        environment!  We can make a little progress by using
935.        the IH to rewrite the goal... *)
936.     rewrite <- IHl'.
937.     (* ... but now we can't go any further. *)
938. Abort.
939.
940. (** So let's take the equation relating [++] and [length] that
941.     would have enabled us to make progress and prove it as a separate
942.     lemma. *)
943.
944. Theorem app_length : forall l1 l2 : natlist,
945.   length (l1 ++ l2) = (length l1) + (length l2).
946. Proof.
947.   (* WORKED IN CLASS *)
948.   intros l1 l2. (* Suppose [l1] and [l2] are each a fixed list of numbers. *)
949.   induction l1 as [| n l1' IHl1']. (* Let's proceed by induction on [l1]. [l1] can either be an
950.                empty list [nil], or it can have a head [n] and a tail [l1']. Let's assume (the
951.                induction hypothesis [IHl1'] that [length (l1' ++ l2) = (length l1) + (length l2)]. *)
952.   - (* Case: [l1 = nil] *)
953.     (* We must show that [length ([] ++ l2) = length [] + length l2] *)
954.     reflexivity. (* [reflexivity] can simplify the [[]] and [length []] cases.
955.                     And then the equation is the same on both sides. *)
956.   - (* Case: [l1 = cons n l1'] *)
957.     (* We must show that [length ((n :: l1') ++ l2) = length (n :: l1') ++ length l2], with an
958.        induction hypothesis: [length (l1' ++ l2) = length l1' ++ length l2]. *)
959.     simpl. (* [simpl] can match the [length] case and see that length [n :: l1'] is the same as
960.               the successor [S] of the length of [l1']. *)
961.     rewrite -> IHl1'. (* Now we can use the inductive hypothesis to rewrite the left hand side
962.                          of the equation. *)
963.     reflexivity. (* And now both sides of the equation are the same. *)
964. Qed.
965.
966. (* Informal proof:
967.
968.    Theorem: [forall l1 l2 : natlist, length (l1 ++ l2) = (length l1) + (length l2)].
969.
970.    Proof: by induction on [l1].
971.
972.    - Suppose [l1] and [l2] are fixed lists of numbers.
973.
974.    - Let's show that the theorem holds for all shapes that [l1] can take (i.e., let's
975.      prove this by induction). [l1] can take two shapes: it can be an empty list [nil],
976.      or it can have a head [n] and a tail [l1'].
977.
978.    - First, consider the case where [l1] is empty.
979.      We need to show [length ([] ++ l2) = (length []) + (length l2)].
980.
981.      - By the definition of [++], [[] ++ l2] is the same as [l2], and [length []]
982.        is [0]. So that yields:
983.
984.          [length l2 = length l2]
985.
986.      - Both sides of the equation are the same, so the theorem holds for this case
987.        by the reflexivity of equality.
988.
989.    - Second, consider the case where [l1] has a head [n] and a tail [l1'], and suppose
990.      an induction hypothesis:
991.
992.        [length (l1' ++ l2) = (length l1') + (length l2)]
993.
994.      We need to show:
995.
996.        [length ((n :: l1') ++ l2) = (length (n :: l1')) + (length l2)]
997.
998.      - By the definition of [length], the length of [n :: l1'] is the same as the
999.        successor [S] of the length of [l1']. So we can rewrite:
1000.
1001.          [S (length (l1' ++ l2)) = S (length l1' + length l2)]
1002.
1003.      - The induction hypothesis says that [length (l1' ++ l2)] is the same as
1004.        [length l1' + length l2]. So we can replace the one with the other, which yields:
1005.
1006.          [S (length (l1' ++ l2)) = S (length (l1' ++ l2))]
1007.
1008.      - Both sides of the equation are the same, so the theorem holds for this case
1009.        by the reflexivity of equality too.
1010.
1011.    - We have shown that the theorem holds for all the shapes [l1] can take.
1012.
1013.    - Since we have shown that the theorem holds for an arbitrary [l1] and [l2],
1014.      we have shown that it holds for all [l1] and [l2]s. []
1015.
1016. *)
1017.
1018. (** Note that, to make the lemma as general as possible, we
1019.     quantify over _all_ [natlist]s, not just those that result from an
1020.     application of [rev].  This should seem natural, because the truth
1021.     of the goal clearly doesn't depend on the list having been
1022.     reversed.  Moreover, it is easier to prove the more general
1023.     property. *)
1024.
1025. (** Now we can complete the original proof. *)
1026.
1027. Theorem rev_length : forall l : natlist,
1028.   length (rev l) = length l.
1029. Proof.
1030.   intros l. induction l as [| n l' IHl'].
1031.   - (* l = nil *)
1032.     reflexivity.
1033.   - (* l = cons *)
1034.     simpl.
1035.     (* rewrite -> app_length. rewrite -> plus_comm. *)
1036.     rewrite -> app_length, plus_comm. (* you can do [rewrite -> app_length], then
1037.                                          [rewrite -> plus_comm], to see the details. *)
1038.     simpl.
1039.     rewrite -> IHl'.
1040.     reflexivity.  Qed.
1041.
1042. (** For comparison, here are informal proofs of these two theorems:
1043.
1044.     _Theorem_: For all lists [l1] and [l2],
1045.        [length (l1 ++ l2) = length l1 + length l2].
1046.
1047.     _Proof_: By induction on [l1].
1048.
1049.     - First, suppose [l1 = []].  We must show
1050.
1051.         length ([] ++ l2) = length [] + length l2,
1052.
1053.       which follows directly from the definitions of
1054.       [length] and [++].
1055.
1056.     - Next, suppose [l1 = n::l1'], with
1057.
1058.         length (l1' ++ l2) = length l1' + length l2.
1059.
1060.       We must show
1061.
1062.         length ((n::l1') ++ l2) = length (n::l1') + length l2).
1063.
1064.       This follows directly from the definitions of [length] and [++]
1065.       together with the induction hypothesis. [] *)
1066.
1067. (** _Theorem_: For all lists [l], [length (rev l) = length l].
1068.
1069.     _Proof_: By induction on [l].
1070.
1071.       - First, suppose [l = []].  We must show
1072.
1073.           length (rev []) = length [],
1074.
1075.         which follows directly from the definitions of [length]
1076.         and [rev].
1077.
1078.       - Next, suppose [l = n::l'], with
1079.
1080.           length (rev l') = length l'.
1081.
1082.         We must show
1083.
1084.           length (rev (n :: l')) = length (n :: l').
1085.
1086.         By the definition of [rev], this follows from
1087.
1088.           length ((rev l') ++ [n]) = S (length l')
1089.
1090.         which, by the previous lemma, is the same as
1091.
1092.           length (rev l') + length [n] = S (length l').
1093.
1094.         This follows directly from the induction hypothesis and the
1095.         definition of [length]. [] *)
1096.
1097. (** The style of these proofs is rather longwinded and pedantic.
1098.     After the first few, we might find it easier to follow proofs that
1099.     give fewer details (which can easily work out in our own minds or
1100.     on scratch paper if necessary) and just highlight the non-obvious
1101.     steps.  In this more compressed style, the above proof might look
1102.     like this: *)
1103.
1104. (** _Theorem_:
1105.      For all lists [l], [length (rev l) = length l].
1106.
1107.     _Proof_: First, observe that [length (l ++ [n]) = S (length l)]
1108.      for any [l] (this follows by a straightforward induction on [l]).
1109.      The main property again follows by induction on [l], using the
1110.      observation together with the induction hypothesis in the case
1111.      where [l = n'::l']. [] *)
1112.
1113. (** Which style is preferable in a given situation depends on
1114.     the sophistication of the expected audience and how similar the
1115.     proof at hand is to ones that the audience will already be
1116.     familiar with.  The more pedantic style is a good default for our
1117.     present purposes. *)
1118.
1119.
1120.
1121. (* ================================================================= *)
1122. (** ** [Search] *)
1123.
1124. (** We've seen that proofs can make use of other theorems we've
1125.     already proved, e.g., using [rewrite].  But in order to refer to a
1126.     theorem, we need to know its name!  Indeed, it is often hard even
1127.     to remember what theorems have been proven, much less what they
1128.     are called.
1129.
1130.     Coq's [Search] command is quite helpful with this.  Typing
1131.     [Search foo] will cause Coq to display a list of all theorems
1132.     involving [foo].  For example, try uncommenting the following line
1133.     to see a list of theorems that we have proved about [rev]: *)
1134.
1135. (*  Search rev. *)
1136.
1137. (** Keep [Search] in mind as you do the following exercises and
1138.     throughout the rest of the book; it can save you a lot of time!
1139.
1140.     If you are using ProofGeneral, you can run [Search] with [C-c
1141.     C-a C-a]. Pasting its response into your buffer can be
1142.     accomplished with [C-c C-;]. *)
1143.
1144. (* ================================================================= *)
1145. (** ** List Exercises, Part 1 *)
1146.
1147. (** **** Exercise: 3 stars (list_exercises)  *)
1148. (** More practice with lists: *)
1149.
1150. Theorem app_nil_r : forall l : natlist,
1151.   l ++ [] = l.
1152. Proof.
1153.   intros l. (* Suppose [l] is a fixed list. *)
1154.   induction l as [| n l' IHl']. (* Let's proceed by induction on [l]. *)
1155.   - (* Case: [l = []]. *)
1156.     (* We must show that [[] ++ [] = []]. *)
1157.     reflexivity. (* after simplifying, both sides of the equation are the same. *)
1158.   - (* Case: [l = [n :: l'], with the induction hypothesis: [n :: l' ++ [] = n :: l']. *)
1159.     simpl. (* [simpl] removes the parentheses. Why? *)
1160.     rewrite -> IHl'. (* The induction hypothesis says [l' ++ []] is the same as [l'].
1161.                         So let's replace [l' ++ []] with [l']. *)
1162.     reflexivity. (* Now both sides of the equation are the same. *)
1163. Qed.
1164.
1165. (* Informal proof:
1166.
1167.    Theorem: [forall l : natlist, l ++ [] = l].
1168.
1169.    Proof: by inductiont on [l].
1170.
1171.    - Suppose [l] is a fixed list of numbers.
1172.
1173.    - Let's proceed by induction on [l].
1174.
1175.      - First consider the case where [l] is [[]].
1176.        We must show that [[] ++ [] = []].
1177.
1178.        - By the definition of [++], [[] ++ []] is the same as []].
1179.
1180.        - Then both sides of the equation are the same.
1181.
1182.        - So the theorem holds for this case, by the reflexivity of equality.
1183.
1184.      - Now consider the case where [l] has a head [n] and a tail [l1],
1185.        and assume an induction hypothesis:
1186.
1187.          [l' ++ [] = l'].
1188.
1189.        We must show that [n :: l' ++ [] = n :: l'].
1190.
1191.        - The induction hypothesis says that [l' ++ []] is the same as [l'].
1192.          So we can replace [l' ++ []] with [l']. That yields [n :: l' = n :: l'].
1193.
1194.        - Both sides of the equation are the same, so this theorem holds
1195.          for this case too, by the reflexivity of equality.
1196.
1197.      - We've shown that the theorem holds for all shapes that [l] can take.
1198.
1199.    - Since we've shown that the theorem holds for an arbitrary [l],
1200.      we've shown that it holds for all [l]s. []
1201.
1202. *)
1203.
1204. Theorem rev_app_distr: forall l1 l2 : natlist,
1205.   rev (l1 ++ l2) = rev l2 ++ rev l1.
1206. Proof.
1207.   intros l1 l2. (* Suppose [l1] and [l2] are fixed numbers. *)
1208.   induction l1 as [| n' l1' IHl1']. (* Proceed by induction on [l1]. *)
1209.   - (* Case: [l1 = []]. *)
1210.     (* We must show that [rev ([] ++ l2) = rev l2 ++ rev []]. *)
1211.     simpl. (* By the definition of [++], [simpl] can reduce [[] ++ l2] to [l2] on the left side
1212.               of the equation. By the definition of [rev], it can reduce [rev []] on the right
1213.               side of the equation to []. *)
1214.     rewrite -> app_nil_r. (* By [app_nil_r], [rev l2 ++ []] is the same as [rev l2]. *)
1215.     reflexivity. (* Now both sides of the equation are the same. *)
1216.   - (* Case: [l1 = n' :: l1], with induction hypothesis: [rev (l1' ++ l2) = rev l2 ++ rev l1']. *)
1217.     (* We need to show that [rev ((n' :: l2) ++ l2) = rev l2 ++ rev (n' :: l2)]. *)
1218.     simpl. (* By the definition of [rev], [simpl] can see that [rev n' :: l1'] is the same as
1219.              [rev l1' ++ [n']]. So it does that replacement. *)
1220.     rewrite -> IHl1'. (* The induction hypothesis says that [rev (l1' ++ l2)] is the same as
1221.                          [rev l2 ++ rev l1']. So we can replace the one with the other. *)
1222.     rewrite -> app_assoc. (* Now the only difference between the two sides of the equation is
1223.                              the parentheses. But we have a lemma which says that [++] is
1224.                              associative. So we can rewrite the left side of the equation
1225.                              with different parentheses. *)
1226.     reflexivity. (* Now both sides of the equation are the same. *)
1227. Qed.
1228.
1229. (* Informal proof:
1230.
1231.    Theorem: [forall l1 l2 : nat, rev (l1 ++ l2) = rev l2 ++ rev l1].
1232.
1233.    Proof: by induction on [l1].
1234.
1235.    - Suppose [l1] and [l2] are each a fixed list of numbers.
1236.
1237.    - Let's proceed by induction on [l1]. That is, let's consider all the shapes that
1238.      [l1] can take.
1239.
1240.    - First, consider the case where [l1] is the empty list [[]].
1241.      We must show [rev ([] ++ l2) = rev l2 ++ rev []].
1242.
1243.      - By the definition of [++], [[] ++ l2] is the same as [l2]. And by the definition of
1244.        [rev], [rev []] is the same as [[]]. Both of those replacements yield:
1245.
1246.          [rev l2 = rev l2 ++ []]
1247.
1248.      - By the lemma [app_nil_r], [rev l2 ++ []] is the same as [rev l2].
1249.
1250.      - Now both sides of the equation are the same, so the theorem holds for this case
1251.        by the reflexivity of equality.
1252.
1253.    - Second, consider the case where [l1] has a head [n'] and a tail [l1'],
1254.      with an induction hypothesis:
1255.
1256.        [rev (l1' ++ l2) = rev l2 ++ rev l1'].
1257.
1258.      We must show:
1259.
1260.        [rev ((n' :: l1') ++ l2) = rev l2 ++ rev (n' :: l1')].
1261.
1262.      - By the definition of [rev], [rev (n' :: l1')] is the same as [rev l1' ++ [n']].
1263.        So if we make that replacement, that yields:
1264.
1265.          [rev ((l1' ++ [n']) ++ l2) = rev l2 ++ (rev l1' ++ [n'])].
1266.
1267.      - Again, [rev ((l1' ++ n') ++ l2)] is the same as [(rev l2 ++ rev l1') ++ [n']].
1268.        So that yields:
1269.
1270.          [(rev l2 ++ rev l1') ++ [n'] = rev l2 ++ rev l1' ++ [n']].
1271.
1272.      - By the lemma [app_assoc], [++] is associative, so we can arrange the parentheses
1273.        to make the left side of the equation match the right side.
1274.
1275.      - Both sides of the equation are the same, so the theorem holds for this case too,
1276.        by the reflexivity of equality.
1277.
1278.    - We've shown that the theorem holds for all shapes that [l1] can take.
1279.
1280.    - Since we've shown that the theorem holds for an arbitrary [l1], we've shown that
1281.      it holds for all [l1]s. []
1282.
1283. *)
1284.
1285. Theorem rev_involutive : forall l : natlist,
1286.   rev (rev l) = l.
1287. Proof.
1288.   intros l.
1289.   induction l as [| n l' IHl'].
1290.   - simpl. reflexivity.
1291.   - simpl. rewrite -> rev_app_distr. simpl. rewrite -> IHl'. reflexivity.
1292. Qed.
1293.
1294. (** There is a short solution to the next one.  If you find yourself
1295.     getting tangled up, step back and try to look for a simpler
1296.     way. *)
1297.
1298. Theorem app_assoc4 : forall l1 l2 l3 l4 : natlist,
1299.   l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.
1300. Proof.
1301.   intros l1 l2 l3 l4.
1302.   induction l1 as [| n1 l1' IHl1'].
1303.   - simpl. rewrite -> app_assoc. reflexivity.
1304.   - simpl. rewrite <- IHl1'. reflexivity.
1305. Qed.
1306.
1308.
1309. Lemma nonzeros_app : forall l1 l2 : natlist,
1310.   nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).
1311. Proof.
1312.   intros l1 l2.
1313.   induction l1 as [| n1 l1' IHl1'].
1314.   - simpl. reflexivity.
1315.   - induction n1 as [| n1' IHn1'].
1316.     + simpl. rewrite -> IHl1'. reflexivity.
1317.     + simpl. rewrite <- IHl1'. reflexivity.
1318. Qed.
1319. (** [] *)
1320.
1321. (** **** Exercise: 2 stars (beq_natlist)  *)
1322. (** Fill in the definition of [beq_natlist], which compares
1323.     lists of numbers for equality.  Prove that [beq_natlist l l]
1324.     yields [true] for every list [l]. *)
1325.
1326. Fixpoint beq_natlist (l1 l2 : natlist) : bool :=
1327.   match l1, l2 with
1328.   | nil, nil => true
1329.   | nil, h :: t => false
1330.   | h :: t, nil => false
1331.   | h1 :: t1, h2 :: t2 => match beq_nat h1 h2 with
1332.                           | true => beq_natlist t1 t2
1333.                           | false => false
1334.                           end
1335.   end.
1336.
1337. Example test_beq_natlist1 :
1338.   (beq_natlist nil nil = true).
1339. Proof. reflexivity. Qed.
1340.
1341. Example test_beq_natlist2 :
1342.   beq_natlist [1;2;3] [1;2;3] = true.
1343. Proof. reflexivity. Qed.
1344.
1345. Example test_beq_natlist3 :
1346.   beq_natlist [1;2;3] [1;2;4] = false.
1347. Proof. reflexivity. Qed.
1348.
1349. Theorem beq_natlist_refl : forall l:natlist,
1350.   true = beq_natlist l l.
1351. Proof.
1352.   intros l.
1353.   induction l as [| n l' IHl'].
1354.   - reflexivity.
1355.   - destruct n.
1356.     + simpl.
1357.       rewrite -> IHl'.
1358.       reflexivity.
1359.     + simpl.
1360.       rewrite <- beq_nat_refl.
1361.       rewrite -> IHl'.
1362.       reflexivity.
1363. Qed.
1364. (** [] *)
1365.
1366. (* ================================================================= *)
1367. (** ** List Exercises, Part 2 *)
1368.
1369. (** Here are a couple of little theorems to prove about your
1370.     definitions about bags above. *)
1371.
1372. (** **** Exercise: 1 star (count_member_nonzero)  *)
1373. Theorem count_member_nonzero : forall (s : bag),
1374.   leb 1 (count 1 (1 :: s)) = true.
1375. Proof.
1376.   intros s.
1377.   simpl.
1378.   reflexivity.
1379. Qed.
1380. (** [] *)
1381.
1383.
1384. Theorem ble_n_Sn : forall n,
1385.   leb n (S n) = true.
1386. Proof.
1387.   intros n. induction n as [| n' IHn'].
1388.   - (* 0 *)
1389.     simpl.  reflexivity.
1390.   - (* S n' *)
1391.     simpl.  rewrite IHn'.  reflexivity.  Qed.
1392.
1393. (** **** Exercise: 3 stars, advanced (remove_decreases_count)  *)
1394. Theorem remove_decreases_count: forall (s : bag),
1395.   leb (count 0 (remove_one 0 s)) (count 0 s) = true.
1396. Proof.
1397.   intros s.
1398.   Search count.
1399.   induction s as [| n s' IHs'].
1400.   - simpl. reflexivity.
1401.   - simpl.
1402.     destruct n.
1403.     + simpl. rewrite -> ble_n_Sn. reflexivity.
1404.     + simpl. rewrite -> IHs'. reflexivity.
1405. Qed.
1406. (** [] *)
1407.
1408. (** **** Exercise: 3 stars, optional (bag_count_sum)  *)
1409. (** Write down an interesting theorem [bag_count_sum] about bags
1410.     involving the functions [count] and [sum], and prove it using
1411.     Coq.  (You may find that the difficulty of the proof depends on
1412.     how you defined [count]!) *)
1413.
1414. Theorem bag_count_sum : forall s1 s2 : bag,
1415.     count 0 s1 + count 0 s2 = count 0 (sum s1 s2).
1416. Proof.
1417.   intros s1 s2. (* Suppose [s1] and [s2] are fixed bags of numbers. *)
1418.   induction s1 as [| n s1' IHs1']. (* Let's proceed by induction on [s1]. *)
1419.   - (* Case: [s1 = []]. *)
1420.     (* We need to show that [count 0 [] + count 0 s2 = count 0 (sum [] s2)]. *)
1421.     simpl. (* By the definition of [count] and [sum], we can drop the empty lists. *)
1422.     reflexivity. (* That renders both sides of the equation the same. *)
1423.   - (* Case: [s1 = [n :: s1'],
1424.        with induction hypothesis: [count 0 s1' + count 0 s2 = count 0 (sum s1' s2)]. *)
1425.     (* We need to show that:
1426.        [count 0 (n :: s1') + count 0 s2 = count 0 (sum (n :: s1') s2)]. *)
1427.     destruct n as [| n']. (* Let's proceed by case analysis on [n]. That is, let's prove the goal
1428.                    holds for each shape of [n]. *)
1429.     + (* Case: [n = 0]. *)
1430.       (* We need to show that:
1431.          [count 0 (0 :: s1') + count 0 s2 = count 0 (sum(0 :: s1') s2)]. *)
1432.       simpl. (* [simpl] can use the definition of [count] and the assumption that [n = 0]
1433.                 to figure out that the [count 0] of [n :: sl'] is the successor [S]
1434.                 of (count 0 s1'). *)
1435.       rewrite -> IHs1'. (* The induction hypothesis tells us that [count 0 s1' + count 0 s2]
1436.                            is the same as [count 0 (sum s1' s2)]. So we can rewrite. *)
1437.       reflexivity. (* Now both sides of the equation are the same. *)
1438.     + (* Case: [n = S n']. *)
1439.       (* We must show that:
1440.          [(count 0 (S n' :: s1') + count 0 s2 = count 0 (sum (S n' :: s1') s2)]. *)
1441.       simpl. (* [simpl] can see in [S n' :: s1'] that the head of the list [S n'] is not [0].
1442.                 So it won't count any [0]s in the head of the list! Because of that, it removes
1443.                 the head [S n'] of the list and just considers [s1'] on both sides of the
1444.                 equation. *)
1445.       rewrite -> IHs1'. (* But now the equation looks just like the inductive hypothesis.
1446.                            So we can rewrite. *)
1447.       reflexivity. (* Now both sides of the equation both look the same. *)
1448. Qed.
1449. (** [] *)
1450.
1451. (** **** Exercise: 4 stars, advanced (rev_injective)  *)
1452. (* Do not modify the following line: *)
1453. Definition manual_grade_for_rev_injective : option (prod nat string) := None.
1454. (** Prove that the [rev] function is injective -- that is,
1455.
1456.     forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.
1457.
1458.     (There is a hard way and an easy way to do this.) *)
1459.
1460. (* FILL IN HERE *)
1461. (** [] *)
1462.
1463. (* ################################################################# *)
1464. (** * Options *)
1465.
1466. (** Suppose we want to write a function that returns the [n]th
1467.     element of some list.  If we give it type [nat -> natlist -> nat],
1468.     then we'll have to choose some number to return when the list is
1469.     too short... *)
1470.
1471. Fixpoint nth_bad (l:natlist) (n:nat) : nat :=
1472.   match l with
1473.   | nil => 42  (* arbitrary! *)
1474.   | a :: l' => match beq_nat n O with
1475.                | true => a
1476.                | false => nth_bad l' (pred n)
1477.                end
1478.   end.
1479.
1480. (** This solution is not so good: If [nth_bad] returns [42], we
1481.     can't tell whether that value actually appears on the input
1482.     without further processing. A better alternative is to change the
1483.     return type of [nth_bad] to include an error value as a possible
1484.     outcome. We call this type [natoption]. *)
1485.
1486. Inductive natoption : Type :=
1487.   | Some : nat -> natoption
1488.   | None : natoption.
1489.
1490. (** We can then change the above definition of [nth_bad] to
1491.     return [None] when the list is too short and [Some a] when the
1492.     list has enough members and [a] appears at position [n]. We call
1493.     this new function [nth_error] to indicate that it may result in an
1494.     error. *)
1495.
1496. Fixpoint nth_error (l:natlist) (n:nat) : natoption :=
1497.   match l with
1498.   | nil => None
1499.   | a :: l' => match beq_nat n O with
1500.                | true => Some a
1501.                | false => nth_error l' (pred n)
1502.                end
1503.   end.
1504.
1505. Example test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.
1506. Proof. reflexivity. Qed.
1507. Example test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.
1508. Proof. reflexivity. Qed.
1509. Example test_nth_error3 : nth_error [4;5;6;7] 9 = None.
1510. Proof. reflexivity. Qed.
1511.
1512. (** (In the HTML version, the boilerplate proofs of these
1513.     examples are elided.  Click on a box if you want to see one.)
1514.
1515.     This example is also an opportunity to introduce one more small
1516.     feature of Coq's programming language: conditional
1517.     expressions... *)
1518.
1519.
1520. Fixpoint nth_error' (l:natlist) (n:nat) : natoption :=
1521.   match l with
1522.   | nil => None
1523.   | a :: l' => if beq_nat n O then Some a
1524.                else nth_error' l' (pred n)
1525.   end.
1526.
1527. (** Coq's conditionals are exactly like those found in any other
1528.     language, with one small generalization.  Since the boolean type
1529.     is not built in, Coq actually supports conditional expressions over
1530.     _any_ inductively defined type with exactly two constructors.  The
1531.     guard is considered true if it evaluates to the first constructor
1532.     in the [Inductive] definition and false if it evaluates to the
1533.     second. *)
1534.
1535. (** The function below pulls the [nat] out of a [natoption], returning
1536.     a supplied default in the [None] case. *)
1537.
1538. Definition option_elim (d : nat) (o : natoption) : nat :=
1539.   match o with
1540.   | Some n' => n'
1541.   | None => d
1542.   end.
1543.
1544. (** **** Exercise: 2 stars (hd_error)  *)
1545. (** Using the same idea, fix the [hd] function from earlier so we don't
1546.     have to pass a default element for the [nil] case.  *)
1547.
1548. Definition hd_error (l : natlist) : natoption :=
1549.   match l with
1550.   | nil => None
1551.   | h :: t => Some h
1552.   end.
1553.
1554. Example test_hd_error1 : hd_error [] = None.
1555. Proof. reflexivity. Qed.
1556.
1557. Example test_hd_error2 : hd_error [1] = Some 1.
1558. Proof. reflexivity. Qed.
1559.
1560. Example test_hd_error3 : hd_error [5;6] = Some 5.
1561. Proof. reflexivity. Qed.
1562. (** [] *)
1563.
1564. (** **** Exercise: 1 star, optional (option_elim_hd)  *)
1565. (** This exercise relates your new [hd_error] to the old [hd]. *)
1566.
1567. Theorem option_elim_hd : forall (l:natlist) (default:nat),
1568.   hd default l = option_elim default (hd_error l).
1569. Proof.
1570.   intros l default.
1571.   induction l as [ | h l' IHl' ].
1572.   - reflexivity.
1573.   - reflexivity.
1574. Qed.
1575. (** [] *)
1576.
1577. End NatList.
1578.
1579. (* ################################################################# *)
1580. (** * Partial Maps *)
1581.
1582. (** As a final illustration of how data structures can be defined in
1583.     Coq, here is a simple _partial map_ data type, analogous to the
1584.     map or dictionary data structures found in most programming
1585.     languages. *)
1586.
1587. (** First, we define a new inductive datatype [id] to serve as the
1588.     "keys" of our partial maps. *)
1589.
1590. Inductive id : Type :=
1591.   | Id : nat -> id.
1592.
1593. (** Internally, an [id] is just a number.  Introducing a separate type
1594.     by wrapping each nat with the tag [Id] makes definitions more
1595.     readable and gives us the flexibility to change representations
1596.     later if we wish. *)
1597.
1598. (** We'll also need an equality test for [id]s: *)
1599.
1600. Definition beq_id (x1 x2 : id) :=
1601.   match x1, x2 with
1602.   | Id n1, Id n2 => beq_nat n1 n2
1603.   end.
1604.
1605. (** **** Exercise: 1 star (beq_id_refl)  *)
1606. Theorem beq_id_refl : forall x, true = beq_id x x.
1607. Proof.
1608.   intros x.
1609.   induction x as [n].
1610.   - simpl.
1611.     induction n as [| n' IHn'].
1612.     + reflexivity.
1613.     + simpl. rewrite <- IHn'. reflexivity.
1614. Qed.
1615. (** [] *)
1616.
1617. (** Now we define the type of partial maps: *)
1618.
1619. Module PartialMap.
1620. Export NatList.
1621.
1622. Inductive partial_map : Type :=
1623.   | empty  : partial_map
1624.   | record : id -> nat -> partial_map -> partial_map.
1625.
1626. (** This declaration can be read: "There are two ways to construct a
1627.     [partial_map]: either using the constructor [empty] to represent an
1628.     empty partial map, or by applying the constructor [record] to
1629.     a key, a value, and an existing [partial_map] to construct a
1630.     [partial_map] with an additional key-to-value mapping." *)
1631.
1632. (** The [update] function overrides the entry for a given key in a
1633.     partial map (or adds a new entry if the given key is not already
1634.     present). *)
1635.
1636. Definition update (d : partial_map)
1637.                   (x : id) (value : nat)
1638.                   : partial_map :=
1639.   record x value d.
1640.
1641. (** Last, the [find] function searches a [partial_map] for a given
1642.     key.  It returns [None] if the key was not found and [Some val] if
1643.     the key was associated with [val]. If the same key is mapped to
1644.     multiple values, [find] will return the first one it
1645.     encounters. *)
1646.
1647. Fixpoint find (x : id) (d : partial_map) : natoption :=
1648.   match d with
1649.   | empty         => None
1650.   | record y v d' => if beq_id x y
1651.                      then Some v
1652.                      else find x d'
1653.   end.
1654.
1655.
1656. (** **** Exercise: 1 star (update_eq)  *)
1657. Theorem update_eq :
1658.   forall (d : partial_map) (x : id) (v: nat),
1659.     find x (update d x v) = Some v.
1660. Proof.
1661.   intros d x v.
1662.   induction d  as [| x' v' d' IHd' ].
1663.   - simpl. rewrite <- beq_id_refl. reflexivity.
1664.   - simpl. rewrite <- beq_id_refl. reflexivity.
1665. Qed.
1666. (** [] *)
1667.
1668. (** **** Exercise: 1 star (update_neq)  *)
1669. Theorem update_neq :
1670.   forall (d : partial_map) (x y : id) (o: nat),
1671.     beq_id x y = false -> find x (update d y o) = find x d.
1672. Proof.
1673.   intros d x y o.
1674.   intros H.
1675.   simpl.
1676.   rewrite -> H.
1677.   reflexivity.
1678. Qed.
1679. (** [] *)
1680. End PartialMap.
1681.
1682. (** **** Exercise: 2 stars (baz_num_elts)  *)
1683. (** Consider the following inductive definition: *)
1684.
1685. Inductive baz : Type :=
1686.   | Baz1 : baz -> baz
1687.   | Baz2 : baz -> bool -> baz.
1688.
1689. (** How _many_ elements does the type [baz] have?