{"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\n\nModule NatList.\n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as in this definition: *)\n\nInductive natprod : Type :=\n pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\n(** We can construct an element of [natprod] like this: *)\n\nCheck (pair 3 5).\n\n(** Here are two simple function definitions for extracting the\n first and second components of a pair. (The definitions also\n illustrate how to do pattern matching on two-argument\n constructors.) *)\n\nDefinition fst (p : natprod) : nat :=\n match p with\n | pair x y => x\n end.\nDefinition snd (p : natprod) : nat :=\n match p with\n | pair x y => y\n end.\n\nEval compute in (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this notation is provided as part of the standard\n library): *)\n\nEval compute in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n match p with\n | (x,y) => x\n end.\nDefinition snd' (p : natprod) : nat :=\n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n match p with\n | (x,y) => (y,x)\n end.\n\n(** Let's try and prove a few simple facts about pairs. If we\n state the lemmas in a particular (and slightly peculiar) way, we\n can prove them with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** Note that [reflexivity] is not enough if we state the lemma in a\n more natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct].\n\n Notice that, unlike for [nat]s, [destruct] doesn't generate an\n extra subgoal here. That's because [natprod]s can only be\n constructed in one way. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p. destruct p as [m n]. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros p. destruct p as [m n]. reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n describe the type of _lists_ of numbers like this: \"A list is\n either the empty list or else a pair of a number and another\n list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following two declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n but in case you are interested, here is roughly what's going on.\n\n The [right associativity] annotation tells Coq how to parenthesize\n expressions involving several uses of [::] so that, for example,\n the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\nNotation \"x + y\" := (plus x y)\n (at level 50, left associativity).\n The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (By the way, it's worth noting in passing that expressions like \"[1\n + 2 :: [3]]\" can be a little confusing when you read them in a .v\n file. The inner brackets, around 3, indicate a list, but the outer\n brackets, which are invisible in the HTML rendering, are there to\n instruct the \"coqdoc\" tool that the bracketed part should be\n displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\").\n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | nil => nil\n | 0 :: t => nonzeros t\n | h :: t => h :: nonzeros t\n end.\n\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t =>\n match oddb h with\n | true => h :: oddmembers t\n | false => oddmembers t\n end\n end.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\n reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n length (oddmembers l).\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\n reflexivity. Qed.\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\n reflexivity. Qed.\nExample test_countoddmembers3: countoddmembers nil = 0.\n reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h1 :: t1 => (* h :: alternate l2 t elegant but doesn't work*)\n match l2 with\n | nil => l1\n | h2 :: t2 => h1 :: h2 :: alternate t1 t2\n end\n end.\n\n\nExample test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n reflexivity. Qed.\nExample test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].\n reflexivity. Qed.\nExample test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].\n reflexivity. Qed.\nExample test_alternate4: alternate [] [20;30] = [20;30].\n reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n multiple times instead of just once. One reasonable\n implementation of bags is to represent a bag of numbers as a\n list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat :=\n match s with\n | nil => 0\n | h :: t =>\n match beq_nat h v with\n | true => S (count v t)\n | false => count v t\n end\n end.\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\n reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\n reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag :=\n app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\n reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag :=\n cons v s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\n reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\n reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n negb (beq_nat 0 (count v s)).\n\nExample test_member1: member 1 [1;4;1] = true.\n reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\n reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n (* When remove_one is applied to a bag without the number to remove,\n it should return the same bag unchanged. *)\n match s with\n | nil => nil\n | h :: t =>\n match beq_nat h v with\n | true => t\n | false => h :: remove_one v t\n end\n end.\n\nExample test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n reflexivity. Qed.\nExample test_remove_one2: count 5 (remove_one 5 [2;1;4;1]) = 0.\n reflexivity. Qed.\nExample test_remove_one3: count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n reflexivity. Qed.\nExample test_remove_one4: count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | h :: t =>\n match beq_nat h v with\n | true => remove_all v t\n | false => h :: remove_all v t\n end\n end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\n reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n match s2 with\n | nil =>\n match s1 with\n | nil => true\n | _ => false\n end\n | h :: t => subset (remove_one h s1) t\n end.\n\n(* should better say that this is \"subbag\" function, because of the second example. *)\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\n reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\n reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (bag_theorem) *)\n(** Write down an interesting theorem about bags involving the\n functions [count] and [add], and prove it. Note that, since this\n problem is somewhat open-ended, it's possible that you may come up\n with a theorem which is true, but whose proof requires techniques\n you haven't learned yet. Feel free to ask for help if you get\n stuck! *)\n\n(*\n * add an element to the bag, and counting its occurrence,\n * is the same as taking the successor of the result of counting\n * on the original bag\n *)\nTheorem count_add_theorem: forall v : nat, forall s : bag,\n count v (add v s) = S (count v s).\nProof.\n intros v k. simpl.\n assert (forall n : nat, beq_nat n n = true).\n intros n. induction n as [|n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite IHn'. reflexivity.\n assert (beq_nat v v = true). apply H. rewrite H0.\n reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match position\n in the definition of [app], allowing the match itself to be\n simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n l'\".\n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proofs will not get you very far! It is\n very important to work through the details of each one, using Coq\n and thinking about what each step of the proof achieves.\n Otherwise it is more or less guaranteed that the exercises will\n make no sense. *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n perhaps a little less familiar than standard natural number\n induction, but the basic idea is equally simple. Each [Inductive]\n declaration defines a set of data values that can be built up from\n the declared constructors: a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to a number; a\n list can be either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two things together establish the\n truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_ass : forall l1 l2 l3 : natlist,\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n intros l1 l2 l3. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons n l1'\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n static written document -- it is easy to see what's going on if\n you are reading the proof in an interactive Coq session and you\n can see the current goal and context at each point, but this state\n is not visible in the written-down parts of the Coq proof. So a\n natural-language proof -- one written for human readers -- will\n need to include more explicit signposts; in particular, it will\n help the reader stay oriented if we remind them exactly what the\n induction hypothesis is in the second case. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n (the induction hypothesis). We must show\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]]\n By the definition of [++], this follows from\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n which is immediate from the induction hypothesis. []\n\n Here is a similar example to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist,\n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** For a slightly more involved example of an inductive proof\n over lists, suppose we define a \"cons on the right\" function\n [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist :=\n match l with\n | nil => [v]\n | h :: t => h :: (snoc t v)\n end.\n\n(** ... and use it to define a list-reversing function [rev]\n like this: *)\n\nFixpoint rev (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => snoc (rev t) h\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** Now let's prove some more list theorems using our newly\n defined [snoc] and [rev]. For something a little more challenging\n than the inductive proofs we've seen so far, let's prove that\n reversing a list does not change its length. Our first attempt at\n this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n :: l'\".\n (* This is the tricky case. Let's begin as usual\n by simplifying. *)\n simpl.\n (* Now we seem to be stuck: the goal is an equality\n involving [snoc], but we don't have any equations\n in either the immediate context or the global\n environment that have anything to do with [snoc]!\n\n We can make a little progress by using the IH to\n rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation about [snoc] that would have\n enabled us to make progress and prove it as a separate lemma.\n*)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n length (snoc l n) = S (length l).\nProof.\n intros n l. induction l as [| n' l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n' l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed.\n\n(**\n Note that we make the lemma as _general_ as possible: in particular,\n we quantify over _all_ [natlist]s, not just those that result\n from an application of [rev]. This should seem natural,\n because the truth of the goal clearly doesn't depend on\n the list having been reversed. Moreover, it is much easier\n to prove the more general property.\n*)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons\".\n simpl. rewrite -> length_snoc.\n rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n _Theorem_: For all numbers [n] and lists [l],\n [length (snoc l n) = S (length l)].\n\n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (snoc [] n) = S (length []),\n which follows directly from the definitions of\n [length] and [snoc].\n\n - Next, suppose [l = n'::l'], with\n length (snoc l' n) = S (length l').\n We must show\n length (snoc (n' :: l') n) = S (length (n' :: l')).\n By the definitions of [length] and [snoc], this\n follows from\n S (length (snoc l' n)) = S (S (length l')),\n]]\n which is immediate from the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (rev []) = length [],\n which follows directly from the definitions of [length]\n and [rev].\n\n - Next, suppose [l = n::l'], with\n length (rev l') = length l'.\n We must show\n length (rev (n :: l')) = length (n :: l').\n By the definition of [rev], this follows from\n length (snoc (rev l') n) = S (length l')\n which, by the previous lemma, is the same as\n S (length (rev l')) = S (length l').\n This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n and pedantic. After the first few, we might find it easier to\n follow proofs that give fewer details (since we can easily work\n them out in our own minds or on scratch paper if necessary) and\n just highlight the non-obvious steps. In this more compressed\n style, the above proof might look more like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that\n length (snoc l n) = S (length l)\n for any [l]. This follows by a straightforward induction on [l].\n The main property now follows by another straightforward\n induction on [l], using the observation together with the\n induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and on how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for\n present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, using [rewrite], and later we will see other ways\n of reusing previous theorems. But in order to refer to a theorem,\n we need to know its name, and remembering the names of all the\n theorems we might ever want to use can become quite difficult! It\n is often hard even to remember what theorems have been proven,\n much less what they are named.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following to\n see a list of theorems that we have proved about [rev]: *)\n\n(* SearchAbout rev. *)\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the course; it can save you a lot of time! *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist,\n l ++ [] = l.\nProof.\n intros l. induction l as [|h t].\n Case \"l = nil\". reflexivity.\n Case \"l = h :: t\". simpl. rewrite IHt. reflexivity. Qed.\n\nLemma rev_involutive_helper : forall h : nat, forall t : natlist,\n rev (snoc t h) = h :: rev t.\nProof.\n intros h t. induction t as [|h1 t1].\n Case \"t = nil\". reflexivity.\n Case \"t = h1 t1\". simpl. rewrite IHt1. reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros l. induction l as [|h t].\n Case \"l = nil\". reflexivity.\n Case \"l = h t\". simpl.\n rewrite rev_involutive_helper. rewrite IHt. reflexivity.\nQed.\n\n(** There is a short solution to the next exercise. If you find\n yourself getting tangled up, step back and try to look for a\n simpler way. *)\n\nTheorem app_ass4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros l1 l2 l3 l4.\n rewrite app_ass. rewrite app_ass. reflexivity.\nQed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n snoc l n = l ++ [n].\nProof.\n intros l n. induction l as [|h t].\n Case \"l = nil\". reflexivity.\n Case \"l = h t\". simpl. rewrite IHt. reflexivity.\nQed.\n\n\nTheorem distr_rev : forall l1 l2 : natlist,\n rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n intros l1 l2. induction l1 as [|h1 t1].\n Case \"l1 = nil\". simpl. rewrite app_nil_end. reflexivity.\n Case \"l1 = h1 t1\".\n simpl. rewrite snoc_append. rewrite snoc_append.\n rewrite IHt1. rewrite app_ass. reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros l1 l2. induction l1 as [|h t].\n Case \"l1 = nil\". reflexivity.\n Case \"l2 = h t\". simpl. rewrite IHt.\n induction h as [|h'].\n SCase \"h = 0\". reflexivity.\n SCase \"h = S h'\". reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 2 stars (list_design) *)\n(** Design exercise:\n - Write down a non-trivial theorem involving [cons]\n ([::]), [snoc], and [app] ([++]).\n - Prove it. *)\n\nTheorem cons_app_cnos_exercise : forall (m n : nat) (ms ns : natlist),\n cons m ms ++ snoc ns n = (cons m (snoc (ms ++ ns) n)).\nProof.\n intros m n ms ns. simpl.\n rewrite snoc_append. rewrite snoc_append.\n rewrite app_ass. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n definitions about bags in the previous problem. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n intros s. reflexivity.\nQed.\n\n(** The following lemma about [ble_nat] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n ble_nat n (S n) = true.\nProof.\n intros n. induction n as [| n'].\n Case \"0\".\n simpl. reflexivity.\n Case \"S n'\".\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n intros s. induction s as [|n s'].\n Case \"s = nil\". reflexivity.\n Case \"s = cons n s'\". simpl.\n induction n as [|n'].\n SCase \"n = 0\". simpl. rewrite ble_n_Sn. reflexivity.\n SCase \"n = S n'\". simpl. rewrite IHs'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *)\n(** Write down an interesting theorem about bags involving the\n functions [count] and [sum], and prove it.*)\n\nLemma plus_n_0 : forall n : nat,\n n + 0 = n.\nProof.\n intros n. induction n as [|n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem count_sum_exercise : forall (n : nat) (xs ys : natlist),\n count n xs + count n ys = count n (sum xs ys).\nProof.\n intros n xs ys.\n induction xs as [|x' xs'].\n Case \"xs = nil\". reflexivity.\n Case \"xs = x' :: xs'\". simpl. destruct (beq_nat x' n).\n SCase \"x' = n\". rewrite <- IHxs'. reflexivity.\n SCase \"x' /= n\". rewrite IHxs'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nThere is a hard way and an easy way to solve this exercise.\n*)\nTheorem rev_inj : forall (l1 l2 : natlist),\n rev l1 = rev l2 -> l1 = l2.\nProof.\n intros l1 l2 H.\n assert (rev (rev l1) = rev (rev l2)).\n rewrite H. reflexivity.\n rewrite <- rev_involutive. rewrite <- H0.\n rewrite rev_involutive. reflexivity.\nQed.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n(** Here is another type definition that is often useful in\n day-to-day programming: *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption.\n\n(** One use of [natoption] is as a way of returning \"error\n codes\" from functions. For example, suppose we want to write a\n function that returns the [n]th element of some list. If we give\n it type [nat -> natlist -> nat], then we'll have to return some\n number when the list is too short! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with\n | true => a\n | false => index_bad (pred n) l'\n end\n end.\n\n(** On the other hand, if we give it type [nat -> natlist ->\n natoption], then we can return [None] when the list is too short\n and [Some a] when the list has enough members and [a] appears at\n position [n]. *)\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None\n | a :: l' => match beq_nat n O with\n | true => Some a\n | false => index (pred n) l'\n end\n end.\n\nExample test_index1 : index 0 [4;5;6;7] = Some 4.\nProof. reflexivity. Qed.\nExample test_index2 : index 3 [4;5;6;7] = Some 7.\nProof. reflexivity. Qed.\nExample test_index3 : index 10 [4;5;6;7] = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n small feature of Coq's programming language: conditional\n expressions... *)\n\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None\n | a :: l' => if beq_nat n O then Some a else index' (pred n) l'\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_opt (l : natlist) : natoption :=\n match l with\n | [] => None\n | h :: d => Some h\n end.\n\nExample test_hd_opt1 : hd_opt [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_opt l).\nProof.\n intros l default. induction l as [|n l'].\n Case \"l = nil\". reflexivity.\n Case \"l = cons n l'\". reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n match l1 with\n | [] => match l2 with\n | [] => true\n | y :: ys => false\n end\n | x :: xs => match l2 with\n | [] => false\n | y :: ys => andb (beq_nat x y) (beq_natlist xs ys)\n end\n end.\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\nExample test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\nExample test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nLemma beq_nat_refl : forall (n : nat),\n beq_nat n n = true.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = nil\". reflexivity.\n Case \"l = cons n l'\". simpl. rewrite <- IHl'.\n rewrite beq_nat_refl. reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Dictionaries *)\n\n(** As a final illustration of how fundamental data structures\n can be defined in Coq, here is the declaration of a simple\n [dictionary] data type, using numbers for both the keys and the\n values stored under these keys. (That is, a dictionary represents\n a finite map from numbers to numbers.) *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n | empty : dictionary\n | record : nat -> nat -> dictionary -> dictionary.\n\n(** This declaration can be read: \"There are two ways to construct a\n [dictionary]: either using the constructor [empty] to represent an\n empty dictionary, or by applying the constructor [record] to\n a key, a value, and an existing [dictionary] to construct a\n [dictionary] with an additional key to value mapping.\" *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n (record key value d).\n\n(** Here is a function [find] that searches a [dictionary] for a\n given key. It evaluates evaluates to [None] if the key was not\n found and [Some val] if the key was mapped to [val] in the\n dictionary. If the same key is mapped to multiple values, [find]\n will return the first one it finds. *)\n\nFixpoint find (key : nat) (d : dictionary) : natoption :=\n match d with\n | empty => None\n | record k v d' => if (beq_nat key k)\n then (Some v)\n else (find key d')\n end.\n\n\n(** **** Exercise: 1 star (dictionary_invariant1) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n (find k (insert k v d)) = Some v.\nProof.\n intros d k v. simpl. rewrite beq_nat_refl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),\n beq_nat m n = false -> find m d = find m (insert n o d).\nProof.\n intros d m n o H. simpl. rewrite H. reflexivity.\nQed.\n(** [] *)\n\n\n\nEnd Dictionary.\n\nEnd NatList.\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n", "meta": {"author": "Javran", "repo": "Thinking-dumps", "sha": "bfb0639c81078602e4b57d9dd89abd17fce0491f", "save_path": "github-repos/coq/Javran-Thinking-dumps", "path": "github-repos/coq/Javran-Thinking-dumps/Thinking-dumps-bfb0639c81078602e4b57d9dd89abd17fce0491f/software-foundations/old/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953275045356249, "lm_q2_score": 0.9381240155738166, "lm_q1q2_score": 0.8942902134959164}} {"text": "Require Import Arith.\nRequire Import Bool.\n\n(**************)\n(* Exercise 1 *)\n(**************)\n\n(* We first want to prove that our definition of add satisfies commutativity. *)\n\nFixpoint add n m := \n match n with 0 => m | S p => add p (S m) end.\n\nLemma addnS : forall n m, add n (S m) = S (add n m).\n induction n.\n - intros m; simpl.\n auto.\n - intros m; simpl.\n apply IHn.\nQed.\n\n(* Q1. Prove the following two theorems: beware that you will probably need\n addnS. *)\n\n(* Already done during the lecture ? *)\nLemma addn0 : forall n, add n 0 = n.\n induction n.\n - unfold add.\n reflexivity.\n - simpl.\n rewrite <- IHn at 2.\n apply (addnS n 0).\nQed.\n\nLemma add_comm : forall n m, add n m = add m n.\n induction n.\n - induction m.\n * reflexivity.\n * rewrite -> addn0.\n simpl.\n reflexivity.\n - intro.\n simpl.\n rewrite IHn.\n simpl.\n reflexivity.\nQed.\n\n(* Q2. Now state and prove the associativity of this function. *)\n\n(* Q3. Now state and prove a theorem that expresses that the add function\n returns the same result as the addition available in the loaded libraries\n (given by function plus) *)\n\n(*********************)\n(* Exercise 2: lists *)\n(*********************)\nRequire Import List Bool_nat.\nRequire Import Coq.omega.Omega.\n\n(* From lecture 2 *)\nClass Eq (A : Type) := cmp : A -> A -> bool.\n\nInfix \"==\" := cmp (at level 70, no associativity).\n\nInstance bool_Eq : Eq nat := beq_nat.\n(* beq_nat comes from the Coq library. *)\n\nFixpoint multiplicity (n : nat)(l : list nat) : nat := \n match l with \n nil => 0%nat \n | a :: l' => \n if n == a then S (multiplicity n l') \n else multiplicity n l' \n end. \n\n\nDefinition is_perm (l l' : list nat) := \n forall n, multiplicity n l = multiplicity n l'.\n\n(* Q4. Show the following theorem : *)\n\nLemma multiplicity_app (x : nat) (l1 l2 : list nat) : \n multiplicity x (l1 ++ l2) = multiplicity x l1 + multiplicity x l2.\n induction l1.\n - simpl.\n reflexivity.\n - simpl.\n destruct (x == a).\n + simpl.\n rewrite IHl1.\n reflexivity.\n + assumption.\nQed.\n\n(* Note : for Q5 and Q6, you will probably have an opportunity\n to use the omega tactic *)\n\n(* Q5. State and prove a theorem that expresses that element counts are\n preserved by reverse. *)\n\n\n(* Q6. Show the following theorem. *)\n\nLemma is_perm_transpose x y l1 l2 l3 : \n is_perm (l1 ++ x::l2 ++ y::l3) (l1 ++ y :: l2 ++ x :: l3).\n unfold is_perm.\n intro.\n rewrite! multiplicity_app.\n simpl.\n rewrite! multiplicity_app.\n simpl.\n destruct (n == x), (n == y); try reflexivity; try omega.\nQed.\n\n(* Q7 : Complete the following lemma using only a reasonning\n on the function rev_app defined in Lecture3.v *)\n(* Excerpt from Lectuer3.v - Begin *)\nFixpoint rev_app (A : Type)(l1 l2 : list A) : list A :=\n match l1 with\n | nil => l2\n | a :: tl => rev_app A tl (a :: l2)\n end.\n\nLemma rev_app_nil : forall A (l1 : list A), \nrev_app A l1 nil = rev l1.\nProof.\nintros A l1.\nassert (Htmp: forall l2, rev_app A l1 l2 = rev l1 ++ l2).\n+ induction l1; intros l2.\n * simpl. auto.\n * simpl.\n rewrite app_assoc_reverse.\n simpl.\n apply IHl1.\n+ rewrite Htmp. \n rewrite app_nil_r.\n auto.\nQed.\n(* Excerpt from Lecture3.v - End *)\n\nLemma rev_rev_id : forall A (l:list A), rev (rev l) = l.\nProof.\n intros.\n rewrite <- rev_app_nil.\n rewrite <- rev_app_nil.\nAdmitted.\n\n(* Q8 : What does this function do? *)\nFixpoint mask (A : Type)(m : list bool)(s : list A) {struct m} :=\n match m, s with\n | b :: m', x :: s' => if b then x :: mask A m' s' else mask A m' s'\n | _, _ => nil\n end.\n\nArguments mask [A] _ _.\n\n(* Q9 Prove that : *)\nLemma mask_cat : forall A m1 (s1 : list A),\n length m1 = length s1 ->\n forall m2 s2, mask (m1 ++ m2) (s1 ++ s2) = mask m1 s1 ++ mask m2 s2.\nAdmitted.\n\n(**************)\n(* Exercise 3 *)\n(**************)\n\n(* Define an inductive type formula : Type that represents the *)\n(*abstract language of propositional logic without variables: \nL = L /\\ L | L \\/ L | ~L | L_true | L_false\n*)\n\n\n(* Define a function formula_holds of type (formula -> Prop computing the *)\n(* Coq formula corresponding to an element of type formula *)\n\n(* Define a function isT_formula of type (formula -> bool) computing *)\n(* the intended truth value of (f : formula) *)\n\n\n(* prove that is (idT_formula f) evaluates to true, then its *)\n(*corresponding Coq formula holds ie.:\n\nRequire Import Bool.\nLemma isT_formula_correct : forall f : formula, \n isT_formula f = true <-> formula_holds f.\n*)\n\n(**************)\n(* Exercise 4 *)\n(**************)\n\n(* We use the inductive type defined in the lecture: *)\n\nInductive natBinTree : Set :=\n| Leaf : natBinTree\n| Node : nat -> natBinTree -> natBinTree -> natBinTree.\n\n(* Define a function which sums all the values present in the tree.\n\nDefine a function is_zero_present : natBinTree -> bool, which tests whether\nthe value 0 is present or not in the tree.\n\nProve several simple statements about the fonctions tree_size\nand tree_height seen in the lecture\n\nDefine a function called mirror that computes the mirror image of a tree.\n\nProve that a tree and its mirror image have the same height.\n\nProve that mirror is involutive (ie the mirror image of the mirror image\nof the tree is this tree).\n\nIt is possible to navigate in a binary tree, given a tree t and\na path like \"from the root, go to the left subtree, then \n go to the right subtree, then go to the left subtree, etc. \"\n\nSuch a path can be easily represented by a list of directions. *)\n\nInductive direction : Set := L (* go left *) | R (* go right *).\n\n\n(* Define in Coq a function get_label that takes a tree and some path,\nand returns the label at which one arrives following the path\n(if any) *)\n\nFixpoint get_label (path : list direction)(t:natBinTree): option nat:= None.\n(* TO DO *)\n\n(* Consider the following function :\n*)\n\nFixpoint zero_present (t: natBinTree) : bool :=\nmatch t with Leaf => false\n | Node n t1 t2 => beq_nat n 0 ||\n zero_present t1 ||\n zero_present t2\nend.\n(* \nProve that whenever zero_present t = true, then there exists \nsome path p such that get_label p t = Some 0\n\n*)\n \n(**************)\n(* Exercise 5 *)\n(**************)\n\n(* Define the function \nsplit : forall A B : Set, list A * B -> (list A) * (list B)\n\nwhich transforms a list of pairs into a pair of lists\nand the function\ncombine : forall A B : Set, list A * list B -> list (A * B)\nwhich transforms a pair of lists into a list of pairs.\n\nWrite and prove two theorems relating the two functions.\n*)", "meta": {"author": "wdomitrz", "repo": "Coq-Exercises", "sha": "86d6ae9488901a0f61d45234a6b1c2c684cf60ef", "save_path": "github-repos/coq/wdomitrz-Coq-Exercises", "path": "github-repos/coq/wdomitrz-Coq-Exercises/Coq-Exercises-86d6ae9488901a0f61d45234a6b1c2c684cf60ef/coqITP2015-ex3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109756113862, "lm_q2_score": 0.9407897529939848, "lm_q1q2_score": 0.8941369069882081}} {"text": "Require Import Arith.\nRequire Import List ZArith.\nRequire Import Bool.\n(* We first want to prove that our definition of add satisfies commutativity. *)\n\nFixpoint add n m := \n match n with 0 => m | S p => add p (S m) end.\n\nLemma addnS : forall n m, add n (S m) = S (add n m).\ninduction n.\n intros m; simpl.\n reflexivity.\nintros m; simpl.\nnow apply IHn.\nQed.\n\n(* Q1. Prove the following two theorems: beware that you will probably need\n addnS. *)\nLemma addn0 : forall n, add n 0 = n.\nProof.\ninduction n;simpl;auto.\nrewrite addnS.\nrewrite IHn.\ntrivial.\nQed.\n\nLemma add_comm : forall n m, add n m = add m n.\nProof.\ninduction n;simpl.\nintros.\nrewrite addn0;auto.\nintros.\nrewrite addnS.\nrewrite IHn.\nrewrite addnS.\ntrivial.\nQed.\n\n(* Q2. Now state and prove the associativity of this function. *)\nLemma plus_assoc : forall n m p, add n (add m p)= add (add n m) p.\nProof.\n\n\n(* Q3. Now state and prove a theorem that expresses that the add function\n returns the same result as the addition available in the loaded libraries\n (given by function plus) *)\n\n(* Note that the theorems about commutativity and associativity could be\n consequences of add_plus. *)\n\n(* Programs about lists. *)\n\n\nFixpoint multiplicity (n : Z)(l : list Z) : nat := \n match l with \n nil => 0%nat \n | a :: l' => \n if Zeq_bool n a then S (multiplicity n l') \n else multiplicity n l' \n end. \n\nDefinition is_perm (l l' : list Z) := \n forall n, multiplicity n l = multiplicity n l'.\n\n(* Q4. Show the following theorem : *)\n\nLemma multiplicity_app (x : Z) (l1 l2 : list Z) : \n multiplicity x (l1 ++ l2) = multiplicity x l1 + multiplicity x l2.\nAdmitted.\n\n\n(* Q5. State and prove a theorem that expresses that element counts are\n preserved by reverse. *)\n\n\n(* Q6. Show the following theorem. You will probably have an occasion\n to use the ring tactic *)\n\n\nLemma is_perm_transpose x y l1 l2 l3 : \n is_perm (l1 ++ x::l2 ++ y::l3) (l1 ++ y :: l2 ++ x :: l3).\nAdmitted.\n\n\n(* Q5 : What does this function do? *)\nFixpoint mask (A : Type)(m : list bool)(s : list A) {struct m} :=\n match m, s with\n | b :: m', x :: s' => if b then x :: mask A m' s' else mask A m' s'\n | _, _ => nil\n end.\n\nImplicit Arguments mask.\n\n(* Q6 Prove that : *)\nLemma mask_cat A m1 (s1 : list A) :\n length m1 = length s1 ->\n forall m2 s2, mask (m1 ++ m2) (s1 ++ s2) = mask m1 s1 ++ mask m2 s2.\nAdmitted.", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Asian-Pacific Summer School/exercises/exercises/exercises4_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.972830765707344, "lm_q2_score": 0.9184802523931341, "lm_q1q2_score": 0.8935258472226872}} {"text": "(* Chap 2 Proof by Induction *)\nFrom LF Require Export Basics.\n\n(* Chap 2.1 Proof by Induction *)\n\nTheorem plus_n_O: forall n: nat, n = n + 0.\nProof.\n intros n.\n induction n.\n - reflexivity.\n - simpl. rewrite <- IHn. reflexivity.\nQed.\n\nTheorem minus_diag: forall n,\n minus n n = 0.\nProof.\n intros n.\n induction n.\n - reflexivity.\n - simpl. rewrite -> IHn. reflexivity.\nQed.\n\n(* Exercise basic_induction *)\n\nTheorem mult_0_r: forall n: nat,\n n * 0 = 0.\nProof.\n intros n.\n induction n.\n - reflexivity.\n - simpl. rewrite -> IHn. reflexivity.\nQed.\n\nTheorem plus_n_Sm : forall n m: nat,\n S (n + m) = n + (S m).\nProof.\n intros n m.\n induction n.\n - simpl. reflexivity.\n - simpl. rewrite -> IHn. reflexivity.\nQed.\n\nTheorem plus_comm : forall n m: nat,\n n + m = m + n.\nProof.\n intros n m.\n induction n.\n - simpl. rewrite <- plus_n_O. reflexivity.\n - simpl. rewrite -> IHn. rewrite plus_n_Sm. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p: nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p.\n induction n.\n - reflexivity.\n - simpl. rewrite -> IHn. reflexivity.\nQed.\n\n(* Exercise double_plus *)\nFixpoint double (n: nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\nLemma double_plus: forall n, double n = n + n.\nProof.\n intros n.\n induction n.\n - reflexivity.\n - simpl. rewrite IHn. rewrite -> plus_n_Sm. reflexivity.\nQed.\n\n(* Exercise evenb_S *)\nTheorem evenb_S: forall n: nat,\n evenb (S n) = negb (evenb n).\nProof.\n intros n.\n induction n.\n - reflexivity.\n - rewrite IHn. \n rewrite negb_involutive.\n reflexivity.\nQed.\n\n(* Chap 2.2 Proofs Within Proofs *)\nTheorem mult_0_plus' : forall n m: nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n). { reflexivity. }\n rewrite -> H.\n reflexivity.\nQed.\n\nTheorem plus_rearrange: forall n m p q: nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n assert (H: n + m = m + n). \n {\n rewrite -> plus_comm.\n reflexivity.\n }\n rewrite -> H.\n reflexivity.\nQed.\n\n(* Chap 2.3 Formal vs. Informal Proof *)\n(* Skipped *)\n\n(* ################################################################# *)\n(* More Exercises *)\n\n(** **** Exercise: 3 stars, standard, recommended (mult_comm)\n\n Use [assert] to help prove this theorem. You shouldn't need to\n use induction on [plus_swap].\n After that, prove commutativity of multiplication. (You will probably\n need to define and prove a separate subsidiary theorem to be used\n in the proof of this one. You may find that [plus_swap] comes in\n handy.) \n*)\nTheorem plus_swap: forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n rewrite -> plus_assoc.\n rewrite -> plus_assoc.\n assert (n + m = m + n).\n {\n rewrite -> plus_comm.\n reflexivity.\n }\n rewrite -> H.\n reflexivity.\nQed.\n\nTheorem mult_succ: forall m n: nat,\n m + m * n = m * S n.\nProof.\n intros m n.\n induction m.\n - reflexivity.\n - simpl. rewrite <- IHm. rewrite -> plus_swap. reflexivity.\nQed.\n\nTheorem mult_comm: forall m n: nat,\n m * n = n * m.\nProof.\n intros n m.\n induction n.\n - rewrite mult_0_r. reflexivity.\n - simpl. rewrite <- mult_succ. rewrite -> IHn. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, standard, optional (more_exercises) \n\n Take a piece of paper. For each of the following theorems, first\n _think_ about whether (a) it can be proved using only\n simplification and rewriting, (b) it also requires case\n analysis ([destruct]), or (c) it also requires induction. Write\n down your prediction. Then fill in the proof. (There is no need\n to turn in your piece of paper; this is just to encourage you to\n reflect before you hack!) *)\nCheck leb.\n\nTheorem leb_refl: forall n: nat,\n true = (n <=? n).\nProof.\n intros n.\n induction n.\n - reflexivity.\n - simpl. rewrite -> IHn. reflexivity.\nQed.\n\nTheorem zero_nbeq_S: forall n: nat,\n 0 =? (S n) = false.\nProof.\n intros n.\n reflexivity.\nQed.\n\nTheorem andb_false_r: forall b: bool,\n andb b false = false.\nProof.\n intros [].\n - reflexivity.\n - reflexivity.\nQed.\n\nTheorem plus_ble_compat_l: forall n m p: nat,\n n <=? m = true -> (p + n) <=? (p + m) = true.\nProof.\n intros n m p.\n intros H.\n induction p.\n - simpl. rewrite -> H. reflexivity.\n - simpl. rewrite -> IHp. reflexivity.\nQed.\n\nTheorem S_nbeq_0: forall n: nat,\n (S n) =? 0 = false.\nProof.\n intros n. \n reflexivity.\nQed.\n\nTheorem mult_1_l: forall n: nat, 1 * n = n.\nProof.\n intros n.\n simpl.\n rewrite <- plus_n_O.\n reflexivity.\nQed.\n\nTheorem all3_spec: forall b c: bool,\n orb\n (andb b c)\n (orb (negb b)\n (negb c))\n = true.\nProof.\n intros [] [].\n - reflexivity.\n - reflexivity.\n - reflexivity.\n - reflexivity.\nQed.\n\nTheorem mult_plus_distr_r: forall n m p: nat,\n (n + m) * p = (n * p) + (m * p).\nProof.\n intros n m p.\n induction n.\n - reflexivity.\n - simpl. rewrite -> IHn. rewrite -> plus_assoc. reflexivity.\nQed.\n\nTheorem mult_assoc: forall n m p: nat,\n n * (m * p) = (n * m) * p.\nProof.\n intros n m p.\n induction n.\n - reflexivity.\n - simpl. rewrite -> IHn. rewrite -> mult_plus_distr_r. reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, standard, optional (eqb_refl) \n\n Prove the following theorem. (Putting the [true] on the left-hand\n side of the equality may look odd, but this is how the theorem is\n stated in the Coq standard library, so we follow suit. Rewriting\n works equally well in either direction, so we will have no problem\n using the theorem no matter which way we state it.) *)\nTheorem eqb_refl: forall n: nat,\n true = (n =? n).\nProof.\n intros n.\n induction n.\n - reflexivity.\n - simpl. rewrite IHn. reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, standard, optional (plus_swap') \n\n The [replace] tactic allows you to specify a particular subterm to\n rewrite and what you want it rewritten to: [replace (t) with (u)]\n replaces (all copies of) expression [t] in the goal by expression\n [u], and generates [t = u] as an additional subgoal. This is often\n useful when a plain [rewrite] acts on the wrong part of the goal.\n\n Use the [replace] tactic to do a proof of [plus_swap'], just like\n [plus_swap] but without needing [assert (n + m = m + n)]. *)\nTheorem plus_swap' : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n rewrite -> plus_assoc.\n rewrite -> plus_assoc.\n replace (n + m) with (m + n).\n - reflexivity.\n - rewrite plus_comm. reflexivity.\nQed.\n(* Note: just a test, not official prove, so may be a little dump. *)\n\n(** **** Exercise: 3 stars, standard, recommended (binary_commute) \n\n Recall the [incr] and [bin_to_nat] functions that you\n wrote for the [binary] exercise in the [Basics] chapter. Prove\n that the following diagram commutes:\n\n incr\n bin ----------------------> bin\n | |\n bin_to_nat | | bin_to_nat\n | |\n v v\n nat ----------------------> nat\n S\n\n That is, incrementing a binary number and then converting it to\n a (unary) natural number yields the same result as first converting\n it to a natural number and then incrementing.\n Name your theorem [bin_to_nat_pres_incr] (\"pres\" for \"preserves\").\n\n Before you start working on this exercise, copy the definitions\n from your solution to the [binary] exercise here so that this file\n can be graded on its own. If you want to change your original\n definitions to make the property easier to prove, feel free to\n do so! *)\nTheorem bin_to_nat_pres_incr: forall n: bin,\n bin_to_nat (incr n) = S (bin_to_nat n).\nProof.\n intros n.\n induction n.\n - reflexivity.\n - simpl. reflexivity.\n - simpl. rewrite <- plus_n_O. rewrite <- plus_n_O. \n rewrite -> plus_n_Sm.\n rewrite -> plus_n_Sm.\n rewrite -> IHn.\n assert (H: forall t: nat, S t + S t = t + S (S t)).\n {\n intros t.\n destruct t.\n - reflexivity.\n - simpl. rewrite -> plus_n_Sm. reflexivity.\n }\n rewrite -> H.\n reflexivity.\nQed.\n\n(** **** Exercise: 5 stars, advanced (binary_inverse) \n\n This is a further continuation of the previous exercises about\n binary numbers. You may find you need to go back and change your\n earlier definitions to get things to work here.\n\n (a) First, write a function to convert natural numbers to binary\n numbers. Prove that, if we start with any [nat], convert it to \n binary, and convert it back, we get the same [nat] we started \n with. (Hint: If your definition of [nat_to_bin] involved any \n extra functions, you may need to prove a subsidiary lemma showing\n how such functions relate to [nat_to_bin].)\n (b) One might naturally expect that we should also prove the\n opposite direction -- that starting with a binary number,\n converting to a natural, and then back to binary should yield\n the same number we started with. However, this is not the\n case! Explain (in a comment) what the problem is.\n (c) Define a normalization function -- i.e., a function\n [normalize] going directly from [bin] to [bin] (i.e., _not_ by\n converting to [nat] and back) such that, for any binary number\n [b], converting [b] to a natural and then back to binary yields\n [(normalize b)]. Prove it. (Warning: This part is a bit\n tricky -- you may end up defining several auxiliary lemmas.\n One good way to find out what you need is to start by trying\n to prove the main statement, see where you get stuck, and see\n if you can find a lemma -- perhaps requiring its own inductive\n proof -- that will allow the main proof to make progress.) Don't\n define thi using nat_to_bin and bin_to_nat! \n*)\n\nFixpoint nat_to_bin (n: nat) : bin :=\n match n with\n | O => Z\n | S n' => incr (nat_to_bin n')\n end.\n\nTheorem nat_bin_nat: forall n: nat, bin_to_nat (nat_to_bin n) = n.\nProof.\n intros n.\n induction n.\n - reflexivity.\n - simpl. rewrite -> bin_to_nat_pres_incr.\n rewrite -> IHn. reflexivity.\nQed.\n\nFixpoint normalize (b: bin) : bin :=\n match b with\n | Z => Z\n | A b' =>\n match normalize b' with\n | Z => Z\n | b'' => A b''\n end\n | B b' => B (normalize b')\n end.\n\nCompute normalize (A (B (A (A Z)))).\n\nLemma normalize_incr_comm: forall b: bin, normalize (incr b) = incr (normalize b).\nProof.\n intros b.\n induction b.\n - reflexivity.\n - simpl. \n destruct (normalize b).\n + simpl. reflexivity.\n + simpl. reflexivity.\n + simpl. reflexivity.\n - simpl.\n rewrite -> IHb.\n destruct (normalize b).\n + simpl. reflexivity.\n + simpl. reflexivity.\n + simpl. reflexivity.\nQed.\n\nLemma twice_is_A: forall n: nat, nat_to_bin(n + n) = normalize (A (nat_to_bin n)).\nProof.\n intros n.\n induction n.\n - simpl. reflexivity.\n - replace (nat_to_bin (S n + S n)) with (incr (incr (nat_to_bin (n + n)))).\n rewrite IHn. \n rewrite <- normalize_incr_comm. \n rewrite <- normalize_incr_comm.\n reflexivity.\n simpl.\n rewrite <- plus_n_Sm. \n simpl. \n reflexivity.\nQed.\n\nLemma normalize_twice_eq_normalize: forall b: bin, normalize (normalize b) = normalize b.\nProof.\n intros b.\n induction b.\n - reflexivity.\n - simpl.\n destruct (normalize b).\n + reflexivity.\n + replace (normalize (A (A b0))) with (\n match normalize (A b0) with \n | Z => Z\n | A c => A (A c)\n | B c => A (B c)\n end\n ).\n rewrite -> IHb.\n reflexivity.\n simpl. reflexivity.\n + simpl. rewrite <- IHb. simpl. reflexivity.\n - simpl. rewrite IHb. reflexivity.\nQed.\n\n\nTheorem normalize_eq_bin_nat_bin: forall b: bin, normalize b = nat_to_bin (bin_to_nat b).\nProof.\n intros b.\n induction b.\n - reflexivity.\n - simpl. \n rewrite <- plus_n_O.\n rewrite -> twice_is_A.\n simpl. rewrite <- IHb.\n rewrite -> normalize_twice_eq_normalize.\n reflexivity.\n - simpl. rewrite -> IHb.\n rewrite <- plus_n_O.\n rewrite -> twice_is_A.\n rewrite <- IHb.\n simpl.\n rewrite -> normalize_twice_eq_normalize.\n destruct (normalize b).\n + reflexivity.\n + reflexivity.\n + reflexivity.\nQed.\n\n\n", "meta": {"author": "Galaxies99", "repo": "Logical-Foundations", "sha": "de2406647c0c22838b096a0dce346eb4d4be17e9", "save_path": "github-repos/coq/Galaxies99-Logical-Foundations", "path": "github-repos/coq/Galaxies99-Logical-Foundations/Logical-Foundations-de2406647c0c22838b096a0dce346eb4d4be17e9/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.9489172610565997, "lm_q1q2_score": 0.8927316273707533}} {"text": "From mathcomp\nRequire Import ssreflect ssrbool ssrnat eqtype seq.\n\nModule FunProg.\n\n(**\n---------------------------------------------------------------------\nExercise [Power of two]\n---------------------------------------------------------------------\nWrite the function [two_power] of type [nat -> nat], such that\n[two_power n = 2^n]. Use the functions that we have defined earlier.\n*)\n\nFixpoint two_power n := match n with \n | 0 => 1\n | m.+1 => 2 * (two_power m)\n end.\n\n(**\n---------------------------------------------------------------------\nExercise [Even numbers]\n---------------------------------------------------------------------\n\nDefine the function [evenB] of type [nat -> bool], such that it\nreturns [true] for even numbers and [false] otherwise. Use the\nfunction we have already defined.\n*)\n\nFixpoint evenB n := if n is m.+1 then ~~ (evenB m) else true.\n\n\n(**\n---------------------------------------------------------------------\nExercise [Division by 4]\n---------------------------------------------------------------------\n\nDefine the function [div4] that maps any natural number [n] to the\ninteger part of [n/4].\n*)\n\nFixpoint div4 n := if n is m.+4 then (div4 m).+1 else 0.\n\n(**\n---------------------------------------------------------------------\nExercise [Representing rational numbers]\n---------------------------------------------------------------------\n\nEvery strictly positive rational number can be obtained in aunique\nmanned by a succession of applications of functions [N] nad [D] on the\nnumber one, where [N] and [D] defined as follows:\n\n[[\nN(x) = 1 + x\n\nD(x) = 1/(1 + 1/x)\n]]\n\nDefine an inductive type (with three constructors), such that it\nuniquely defines strictly positive rational using the representation\nabove.\n\nThen, define the function that takes an element of the defined type\nnad returns a numerator and denominator of the corresponding fraction.\n*)\n\nInductive rational : Set :=\n One | N of rational | D of rational.\n\nFixpoint rat_to_frac (r: rational) : nat * nat :=\n match r with \n | One => (1, 1)\n | N x => let: (a, b) := rat_to_frac x \n in (b + a, b)\n | D x => let (a, b) := rat_to_frac x \n in (a, a + b)\n end. \n\n(**\n---------------------------------------------------------------------\nExercise [Infinitely-branching trees]\n---------------------------------------------------------------------\n\nDefine an inductive type of infinitely-branching trees (parametrized\nover a type [T]), whose leafs are represented by a constructor that\ndoesn't take parameters and a non-leaf nodes contain a value _and_ a\nfunction that takes a natural number and returns a child of the node\nwith a corresponding natural index.\n\nDefine a boolean function that takes such a tree (instantiated with a\ntype [nat]) and an argument of [n] type [nat] and checks whether the\nzero value occurs in it at a node reachable only by indices smaller\nthan a number [n]. Then write some \"test-cases\" for the defined\nfunction.\n\nHint: You might need to define a couple of auxiliary functions for\nthis exercise.\n\nHint: Sometimes you might need to provide the type arguments to\nconstructors explicitly.\n\n*)\n\nInductive inf_tree {T: Set} := Leaf | Node of T & (nat -> @inf_tree T).\n\nFixpoint check_subtrees (checker: nat -> bool) n :=\n if n is m.+1 \n then checker n || check_subtrees checker m\n else checker 0.\n\nFixpoint has_zero (t: @inf_tree nat) n {struct t} : bool :=\n match t with \n | Leaf => false\n | Node x f => (x == 0) || \n check_subtrees (fun s => has_zero (f s) n) n\n end.\n\nEval compute in \n has_zero (Node 2 (fun x => if x == 3 then Node 0 (fun x => Leaf) else Leaf)) 3.\n\n(**\n---------------------------------------------------------------------\nExercise [List-find]\n---------------------------------------------------------------------\n\nWrite a function that take a type [A], a function [f] of type [A ->\nbool] and a list [l], and return the first element [x] in [l], such\nthat [f x == true]. \n\n%\\hint% Use Coq's [option] type to account for the fact that the\n function of interest is partially-defined.\n*)\n\nFixpoint first_elt A (f: A -> bool) (l : seq A) : option A := \n if l is x::xs \n then if f x then Some x else first_elt A f xs\n else None.\n\n(**\n---------------------------------------------------------------------\nExercise [Generate a range]\n---------------------------------------------------------------------\n\nImplement a function that takes a number [n] and returns the list\ncontaining the natural numbers from [1] to [n], _in this order_.\n*)\n\nFixpoint nns n z :=\n if n is m.+1 \n then z :: (nns m (z.+1))\n else [::].\n\nDefinition Nns n := nns n 1.\n\n(**\n---------------------------------------------------------------------\nExercise [Standard list combinators]\n---------------------------------------------------------------------\n\nImplement the following higher-order functions on lists\n\n- map\n- filter\n- fold_left\n- fold_right\n- tail-recursive list reversal\n*)\n\nFixpoint fold_left {A B} (f: B -> A -> B) z (l: seq A): B :=\n if l is x::xs \n then fold_left f (f z x) xs\n else z.\n\nEval compute in fold_left (fun x y => x + y) 0 [::1;2;4].\n\nFixpoint fold_right {A B} (f: A -> B -> B) z (l: seq A): B :=\n if l is x::xs \n then (f x (fold_right f z xs))\n else z.\n\nEval compute in fold_left (fun x y => x + y) 5 [::1;2;4].\n\n(** \n---------------------------------------------------------------------\nExercises [No-stuttering lists]\n---------------------------------------------------------------------\n\nWe say that a list of numbers \"stutters\" if it repeats the same number\nconsecutively. The predicate \"nostutter ls\" means that ls does not\nstutter. Formulate an inductive definition for nostutter. Write some\n\"unit tests\" for this function.\n\n*)\n\nFixpoint eqn m n {struct m} :=\n match (m, n) with\n | (0, 0) => true\n | (m'.+1, n'.+1) => eqn m' n'\n | (_, _) => false\n end.\n\nFixpoint nostutter (l : seq nat): bool := \n if l is x1::xs1 \n then if xs1 is x2::xs2 then ~~(eqn x1 x2) && nostutter xs1\n else true\n else true.\n\nEval compute in nostutter [:: 1;2;3;4;5].\n\nEval compute in nostutter [:: 1;2;3;3;4;5].\n\n(** \n---------------------------------------------------------------------\nExercise [List alternation]\n---------------------------------------------------------------------\n\nImplement the recursive function [alternate] of type [seq nat -> seq\nnat -> seq nat], so it would construct the alternation of two\nsequences.\n\n%\\hint% The reason why the \"obvious\" elegant solution might fail is\n that the argument is not strictly decreasing.\n*)\n\nFixpoint alternate (l1 l2 : seq nat) : seq nat := \nmatch (l1, l2) with \n | ([::], ys) => ys\n | (xs, [::]) => xs\n | (x::xs, y::ys) => x :: y :: (alternate xs ys)\n end. \n\nEval compute in alternate [:: 1;2;3;4;5] [:: 1;2;3;4;6].\n\n(**\n---------------------------------------------------------------------\nExercise [Functions with dependently-typed result type]\n---------------------------------------------------------------------\n\nWrite a function that has a dependent result type and whose result is\n[true] for natural numbers of the form [4n + 1], [false] for numbers\nof the form [4n + 3] and [n] for numbers of the from [2n].\n\n%\\hint% Again, you might need to define a number of auxiliary\n (possibly, higher-order) functions to complete this exercise.\n*)\n\nFixpoint dep_type (n : nat) : Set := match n with \n | 0 => nat\n | 1 => bool\n | n'.+2 => dep_type n'\n end. \n\nFixpoint dep_value_aux (n: nat): dep_type n -> dep_type n := \n match n return dep_type n -> dep_type n with \n | 0 => fun x => x.+1\n | 1 => fun x => ~~x\n | n'.+2 => dep_value_aux n'\n end.\n\nFixpoint dep_value (n: nat): dep_type n := \n match n with \n | 0 => 0\n | 1 => true\n | n'.+2 => dep_value_aux n' (dep_value n')\n end.\n\nEval compute in dep_value 6.\n\nEnd FunProg.\n", "meta": {"author": "ilyasergey", "repo": "pnp", "sha": "dc32861434e072ed825ba1952cbb7acc4a3a4ce0", "save_path": "github-repos/coq/ilyasergey-pnp", "path": "github-repos/coq/ilyasergey-pnp/pnp-dc32861434e072ed825ba1952cbb7acc4a3a4ce0/solutions/FunProg_solutions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543366, "lm_q2_score": 0.9252299586383205, "lm_q1q2_score": 0.8917180759233767}} {"text": "Require Import Coq.Bool.Bool Coq.Arith.PeanoNat.\n\nClass Monoid {A : Type} (empty : A) (append : A -> A -> A):=\n {\n associativity : forall (x y z : A),\n append x (append y z) = append (append x y) z;\n\n l_neutral : forall (x : A), append empty x = x;\n r_neutral : forall (x : A), append x empty = x;\n }.\n\nInstance BoolMonoidOr : Monoid false orb :=\n {}.\n (* associativity *)\n Proof.\n intros. apply orb_assoc.\n (* l_neutral *)\n Proof.\n intros. apply orb_false_l.\n (* r_neutral *)\n Proof.\n intros. apply orb_false_r.\n Defined.\n\nInstance BoolMonoidAnd : Monoid true andb :=\n {}.\n (* associativity *)\n Proof.\n intros. apply andb_assoc.\n (* l_neutral *)\n Proof.\n intros. apply andb_true_l.\n (* r_neutral *)\n Proof.\n intros. apply andb_true_r.\n Defined.\n\nInstance NatMonoidPlus : Monoid 0 Nat.add :=\n {}.\n (* associativity *)\n Proof.\n intros. apply Nat.add_assoc.\n (* l_neutral *)\n Proof.\n intros. apply Nat.add_0_l.\n (* r_neutral *)\n Proof.\n intros. apply Nat.add_0_r.\n Defined.\n\nInstance NatMonoidMul : Monoid 1 Nat.mul :=\n {}.\n (* associativity *)\n Proof.\n intros. apply Nat.mul_assoc.\n (* l_neutral *)\n Proof.\n intros. apply Nat.mul_1_l.\n (* r_neutral *)\n Proof.\n intros. apply Nat.mul_1_r.\n Defined.\n", "meta": {"author": "mtrsk", "repo": "Regex-Play-Coq", "sha": "6f04e9299cfaa85377cf50d0470750d95abbb0b9", "save_path": "github-repos/coq/mtrsk-Regex-Play-Coq", "path": "github-repos/coq/mtrsk-Regex-Play-Coq/Regex-Play-Coq-6f04e9299cfaa85377cf50d0470750d95abbb0b9/src/Monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.974434786819155, "lm_q2_score": 0.9149009636941993, "lm_q1q2_score": 0.8915113255179965}} {"text": "(** * MoreProp: More about Propositions and Evidence *)\n\nRequire Export \"Prop\".\n\n\n(* ####################################################### *)\n(** * Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n [beautiful]) can be thought of as a _property_ -- i.e., it defines\n a subset of [nat], namely those numbers for which the proposition\n is provable. In the same way, a two-argument proposition can be\n thought of as a _relation_ -- i.e., it defines a set of pairs for\n which the proposition is provable. *)\n\nModule LeModule.\n\n\n(** One useful example is the \"less than or equal to\"\n relation on numbers. *)\n\n(** The following definition should be fairly intuitive. It\n says that there are two ways to give evidence that one number is\n less than or equal to another: either observe that they are the\n same number, or give evidence that the first is less than or equal\n to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n | le_n : forall n, le n n\n | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n [le_S] follow the same patterns as proofs about properties, like\n [ev] in chapter [Prop]. We can [apply] the constructors to prove [<=]\n goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n tactics like [inversion] to extract information from [<=]\n hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** Here are some sanity checks on the definition. (Notice that,\n although these are the same kind of simple \"unit tests\" as we gave\n for the testing functions we wrote in the first few lectures, we\n must construct their proofs explicitly -- [simpl] and\n [reflexivity] don't do the job, because the proofs aren't just a\n matter of simplifying computations.) *)\n\nTheorem test_le1 :\n 3 <= 3.\nProof.\n (* WORKED IN CLASS *)\n apply le_n. Qed.\n\nTheorem test_le2 :\n 3 <= 6.\nProof.\n (* WORKED IN CLASS *)\n apply le_S. apply le_S. apply le_S. apply le_n. Qed.\n\nTheorem test_le3 :\n (2 <= 1) -> 2 + 2 = 5.\nProof.\n (* WORKED IN CLASS *)\n intros H. inversion H. inversion H2. Qed.\n\n(** The \"strictly less than\" relation [n < m] can now be defined\n in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n | nn : next_nat n (S n).\n\nInductive next_even (n:nat) : nat -> Prop :=\n | ne_1 : ev (S n) -> next_even n (S n)\n | ne_2 : ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation) *)\n(** Define an inductive binary relation [total_relation] that holds\n between every pair of natural numbers. *)\n\nInductive total_relation : nat -> nat -> Prop :=\n t : forall n m, total_relation n m.\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n that never holds. *)\n\nInductive empty_relation : nat -> nat -> Prop :=\n e : forall n m, 2 + 2 = 5 -> empty_relation n m.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\n(** Here are a number of facts about the [<=] and [<] relations that\n we are going to need later in the course. The proofs make good\n practice exercises. *)\n\nTheorem Sn_le_m__n_le_m : forall n m,\n S n <= m -> n <= m.\nProof.\n intros n m H. induction H.\n Case \"le_n\". apply le_S. apply le_n.\n Case \"le_S\". apply le_S. apply IHle. Qed.\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n intros m n o H1 H2. induction H1 as [| n'].\n Case \"le_n\".\n apply H2.\n Case \"le_S\".\n apply IHle. apply Sn_le_m__n_le_m in H2. apply H2. Qed.\n\nTheorem O_le_n : forall n,\n 0 <= n.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\". apply le_n.\n Case \"n = S n'\". apply le_S. apply IHn'. Qed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n n <= m -> S n <= S m.\nProof.\n intros n m H. induction H.\n Case \"le_n\". apply le_n.\n Case \"le_S\". apply le_S. apply IHle. Qed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n S n <= S m -> n <= m.\nProof.\n intros n m H. inversion H.\n apply le_n.\n apply Sn_le_m__n_le_m. apply H1. Qed.\n\nTheorem le_plus_l : forall a b,\n a <= a + b.\nProof.\n intros a b. induction a as [| a'].\n Case \"a = 0\". simpl. apply O_le_n.\n Case \"a = S a'\". simpl. apply n_le_m__Sn_le_Sm. apply IHa'. Qed.\n\nTheorem plus_lt : forall n1 n2 m,\n n1 + n2 < m ->\n n1 < m /\\ n2 < m.\nProof.\n unfold lt. intros n1 n2 m H.\n split. (* eplained in Logic *)\n Case \"left\".\n induction n2 as [| n2'].\n SCase \"n2 = 0\".\n rewrite -> plus_0_r in H. apply H.\n SCase \"n2 = S n2'\".\n apply IHn2'. apply Sn_le_m__n_le_m.\n rewrite <- plus_n_Sm in H. apply H.\n Case \"right\".\n induction n1 as [| n1'].\n SCase \"n1 = 0\".\n simpl in H. apply H.\n SCase \"n1 = S n1'\".\n apply IHn1'. apply Sn_le_m__n_le_m. apply H. Qed.\n\nTheorem lt_S : forall n m,\n n < m ->\n n < S m.\nProof.\n unfold lt. intros n m H.\n apply n_le_m__Sn_le_Sm. apply Sn_le_m__n_le_m. apply H. Qed.\n\nTheorem ble_nat_true : forall n m,\n ble_nat n m = true -> n <= m.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\".\n intros m eq. apply O_le_n.\n Case \"n = S n'\".\n intros m eq. destruct m as [| m'].\n SCase \"m = 0\".\n inversion eq.\n SCase \"m = S m'\".\n apply n_le_m__Sn_le_Sm. apply IHn'. inversion eq. reflexivity. Qed.\n\nTheorem le_ble_nat : forall n m,\n n <= m ->\n ble_nat n m = true.\nProof.\n (* Hint: This may be easiest to prove by induction on [m]. *)\n intros n m. generalize dependent n. induction m as [| m'].\n Case \"m = 0\".\n intros n eq. inversion eq. reflexivity.\n Case \"m = S m'\".\n intros n eq. destruct n as [| n'].\n SCase \"n = 0\".\n reflexivity.\n SCase \"n = S n'\".\n simpl. apply IHm'. apply Sn_le_Sm__n_le_m. apply eq. Qed.\n\nTheorem ble_nat_true_trans : forall n m o,\n ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.\nProof.\n (* Hint: This theorem can be easily proved without using [induction]. *)\n intros n m o eq1 eq2. apply le_ble_nat.\n apply ble_nat_true in eq1. apply ble_nat_true in eq2.\n apply le_trans with (n:=m). apply eq1. apply eq2. Qed.\n\n(** **** exercise: 3 stars (R_provability) *)\nModule R.\n(** We can define three-place relations, four-place relations,\n etc., in just the same way as binary relations. For example,\n consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n | c1 : R 0 0 0\n | c2 : forall m n o, R m n o -> R (S m) n (S o)\n | c3 : forall m n o, R m n o -> R m (S n) (S o)\n | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n + [R 1 1 2]\n - [R 2 2 6]\n\n - If we dropped constructor [c5] from the definition of [R],\n would the set of provable propositions change? Briefly (1\n sentence) explain your answer.\n\n - If we dropped constructor [c4] from the definition of [R],\n would the set of provable propositions change? Briefly (1\n sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact) *)\n(** Relation [R] actually encodes a familiar function. State and prove two\n theorems that formally connects the relation and the function.\n That is, if [R m n o] is true, what can we say about [m],\n [n], and [o], and vice versa?\n*)\n\nTheorem R_plus : forall (m n o : nat),\n R m n o -> m + n = o.\nProof.\n intros m n o R. induction R.\n Case \"R = c1\".\n reflexivity.\n Case \"R = c2\".\n simpl. rewrite -> IHR. reflexivity.\n Case \"R = c3\".\n rewrite <- plus_n_Sm. rewrite -> IHR. reflexivity.\n Case \"R = c4\".\n simpl in IHR. rewrite <- plus_n_Sm in IHR. inversion IHR. reflexivity.\n Case \"R = c5\".\n rewrite -> plus_comm. apply IHR. Qed.\n\nTheorem plus_R : forall (m n o: nat),\n m + n = o -> R m n o.\nProof.\n intros m. induction m as [| m'].\n Case \"m = 0\".\n intros n. induction n as [| n'].\n SCase \"n = 0\".\n intros o H. simpl in H. rewrite <- H. apply c1.\n SCase \"n = S n'\".\n intros o H. simpl in H. rewrite <- H.\n apply c3. apply IHn'. reflexivity.\n Case \"m = S m'\".\n intros n. induction n as [| n'].\n SCase \"n = 0\".\n intros o H. rewrite -> plus_0_r in H. rewrite <- H.\n apply c2. apply IHm'. rewrite -> plus_0_r. reflexivity.\n SCase \"n = S n'\".\n intros o H. simpl in H. rewrite <- plus_n_Sm in H. rewrite <- H.\n apply c3. apply IHn'. reflexivity. Qed.\n(** [] *)\n\nEnd R.\n\n\n(* ##################################################### *)\n(** * Programming with Propositions *)\n\n(** A _proposition_ is a statement expressing a factual claim,\n like \"two plus two equals four.\" In Coq, propositions are written\n as expressions of type [Prop]. Although we haven't discussed this\n explicitly, we have already seen numerous examples. *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** Both provable and unprovable claims are perfectly good\n propositions. Simply _being_ a proposition is one thing; being\n _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n of type [Prop]. *)\n\n(** We've mainly seen one place that propositions can appear in Coq: in\n [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 :\n 2 + 2 = 4.\nProof. reflexivity. Qed.\n\n(** But they can be used in many other ways. For example, we have also seen that\n we can give a name to a proposition using a [Definition], just as we have\n given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop := 2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true :\n plus_fact.\nProof. reflexivity. Qed.\n\n(** We've seen several ways of constructing propositions.\n\n - We can define a new proposition primitively using [Inductive].\n\n - Given two expressions [e1] and [e2] of the same type, we can\n form the proposition [e1 = e2], which states that their\n values are equal.\n\n - We can combine propositions using implication and\n quantification. *)\n\n(** We have also seen _parameterized propositions_, such as [even] and\n [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even.\n(* ===> even : nat -> Prop *)\n\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n three equivalent ways: (1) \"[even] is a _function_ from numbers to\n propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n by a number [n],\" or (3) \"[even] is a _property_ of numbers.\" *)\n\n(** Propositions -- including parameterized propositions -- are\n first-class citizens in Coq. For example, we can define functions\n from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n P 0.\n\n(** Here are two more examples of passing parameterized propositions\n as arguments to a function.\n\n The first function, [true_for_all_numbers], takes a proposition\n [P] as argument and builds the proposition that [P] is true for\n all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n that, if [P] is true for some natural number [n'], then it is also\n true by the successor of [n'] -- i.e. that [P] is _preserved by\n successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n forall n', P n' -> P (S n').\n\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n forall (P:nat->Prop),\n true_for_zero P ->\n preserved_by_S P ->\n true_for_all_numbers P.\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even) *)\n(** Complete the definition of the [combine_odd_even] function\n below. It takes as arguments two properties of numbers [Podd] and\n [Peven]. As its result, it should return a new property [P] such\n that [P n] is equivalent to [Podd n] when [n] is odd, and\n equivalent to [Peven n] otherwise. *)\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n fun n => if oddb n then Podd n else Peven n.\n\n(** To test your definition, see whether you can prove the following\n facts: *)\n\nTheorem combine_odd_even_intro :\n forall (Podd Peven : nat -> Prop) (n : nat),\n (oddb n = true -> Podd n) ->\n (oddb n = false -> Peven n) ->\n combine_odd_even Podd Peven n.\nProof.\n intros Podd Peven n H1 H2. unfold combine_odd_even.\n destruct (oddb n).\n apply H1. reflexivity.\n apply H2. reflexivity. Qed.\n\nTheorem combine_odd_even_elim_odd :\n forall (Podd Peven : nat -> Prop) (n : nat),\n combine_odd_even Podd Peven n ->\n oddb n = true ->\n Podd n.\nProof.\n intros Podd Peven n H1 H2.\n unfold combine_odd_even in H1.\n rewrite -> H2 in H1. apply H1. Qed.\n\nTheorem combine_odd_even_elim_even :\n forall (Podd Peven : nat -> Prop) (n : nat),\n combine_odd_even Podd Peven n ->\n oddb n = false ->\n Peven n.\nProof.\n intros Podd Peven n H1 H2.\n unfold combine_odd_even in H1.\n rewrite -> H2 in H1. apply H1. Qed.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n parameterized propositions using [Definition], then can we also\n define them using [Fixpoint]? Of course we can! However, this\n kind of \"recursive parameterization\" doesn't correspond to\n anything very familiar from everyday mathematics. The following\n exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)\n(** Define a recursive function\n [true_upto_n__true_everywhere] that makes\n [true_upto_n_example] work. *)\n\nFixpoint true_upto_n__true_everywhere (n : nat) (P : nat -> Prop) : Prop :=\n match n with\n | O => forall m : nat, even m\n | S n' => even n -> true_upto_n__true_everywhere n' P\n end.\n\nExample true_upto_n_example :\n (true_upto_n__true_everywhere 3 (fun n => even n))\n = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n", "meta": {"author": "tymmym", "repo": "software-foundations", "sha": "940149ef3e1e5ae7640497ba392a4e3667dd0412", "save_path": "github-repos/coq/tymmym-software-foundations", "path": "github-repos/coq/tymmym-software-foundations/software-foundations-940149ef3e1e5ae7640497ba392a4e3667dd0412/MoreProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122732859021, "lm_q2_score": 0.9284087931273041, "lm_q1q2_score": 0.8893341775631967}} {"text": "(* \n standard, recommended (basic_induction)\n Prove the following using induction. You might need previously proven results.\n*)\n\nFrom LF Require Export basics.\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n intros.\n induction n.\n reflexivity.\n rewrite <- mult_n_O.\n reflexivity.\nQed. \n\n\nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof.\n intros.\n induction n.\n reflexivity.\n simpl.\n rewrite <- IHn.\n reflexivity.\nQed.\n\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros.\n induction n.\n - simpl.\n rewrite <- plus_n_O.\n reflexivity.\n - simpl.\n rewrite <- plus_n_Sm.\n rewrite <- IHn.\n reflexivity.\nQed.\n \n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros.\n induction n.\n reflexivity.\n simpl.\n rewrite <- IHn.\n reflexivity.\nQed.\n\n\n(******************************)\n\n(* \n standard (double_plus)\n Consider the following function, which doubles its argument:\n\n Fixpoint double (n:nat) :=\n match n with\n | O ⇒ O\n | S n' ⇒ S (S (double n'))\n end.\n Use induction to prove this simple fact about double: \n*)\n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n intros.\n induction n.\n reflexivity.\n simpl.\n rewrite -> IHn.\n rewrite -> plus_n_Sm.\n reflexivity.\nQed.\n \n(******************************)\n\n(* \n standard, optional (evenb_S)\n One inconvenient aspect of our definition of evenb n is the recursive call on-\n n - 2. This makes proofs about evenb n harder when done by induction on n,\n since we may need an induction hypothesis about n - 2.\n The following lemma gives an alternative characterization of evenb (S n) that-\n works better with induction: \n*)\n\nTheorem negb_involutive : forall b:bool,\n negb (negb b) = b.\nProof.\n destruct b.\n reflexivity.\n reflexivity.\nQed.\n\nTheorem evenb_S : forall n : nat,\n evenb (S n) = negb (evenb n).\nProof.\n intros.\n induction n.\n reflexivity.\n rewrite -> IHn.\n rewrite -> negb_involutive.\n reflexivity.\nQed.\n\n(******************************)\n\n(* \n standard, recommended (mult_comm)\n Use assert to help prove this theorem.-\n You shouldn't need to use induction on plus_swap. \n*)\n\nTheorem plus_swap : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros.\n rewrite -> plus_assoc.\n rewrite -> plus_assoc.\n assert (H: n + m = m + n).\n rewrite plus_comm. reflexivity.\n rewrite -> H. reflexivity.\nQed.\n\n\n(* Now prove commutativity of multiplication. \n You will probably want to define and prove a \"helper\" theorem to be used in-\n the proof of this one. Hint: what is n × (1 + k)? \n*)\n\nTheorem mult_1_plus_n : forall m n : nat,\n n * ( S m ) = n + ( n * m )\n.\nProof.\n intros.\n induction n.\n reflexivity.\n simpl.\n rewrite -> plus_swap.\n f_equal.\n f_equal.\n assumption.\nQed. \n\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m. \n\nProof.\n intros.\n induction n.\n rewrite <- mult_n_O.\n reflexivity.\n simpl.\n rewrite -> mult_1_plus_n.\n rewrite -> IHn.\n reflexivity.\nQed.\n \n\n(******************************)\n\n(* standard, optional (more_exercises) \n\n Take a piece of paper. For each of the following theorems, first\n _think_ about whether (a) it can be proved using only\n simplification and rewriting, (b) it also requires case\n analysis ([destruct]), or (c) it also requires induction. Write\n down your prediction. Then fill in the proof. (There is no need\n to turn in your piece of paper; this is just to encourage you to\n reflect before you hack!) *)\n\nCheck leb.\n\nTheorem leb_refl : forall n:nat,\n true = (n <=? n).\nProof.\n intros.\n induction n.\n reflexivity.\n simpl.\n assumption.\nQed.\n\nTheorem zero_nbeq_S : forall n:nat,\n 0 =? (S n) = false.\nProof.\n intros.\n reflexivity.\nQed.\n\nTheorem andb_false_r : forall b : bool,\n andb b false = false.\nProof.\n destruct b;reflexivity.\nQed.\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n n <=? m = true -> (p + n) <=? (p + m) = true.\nProof.\n intros.\n induction p.\n assumption.\n assumption.\nQed.\n\nTheorem S_nbeq_0 : forall n:nat,\n (S n) =? 0 = false.\nProof.\n intros.\n reflexivity.\nQed.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n intros.\n simpl.\n rewrite <- plus_n_O.\n reflexivity.\nQed.\n\n\n\nLemma excluded_middle: forall b : bool,\n orb b (negb b) = true.\nProof.\n intros.\n destruct b; reflexivity.\nQed.\n\nTheorem all3_spec : forall b c : bool,\n orb\n (andb b c)\n (orb (negb b)\n (negb c))\n = true.\nProof.\n intros.\n destruct b.\n simpl.\n rewrite excluded_middle; reflexivity.\n reflexivity.\nQed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n (n + m) * p = (n * p) + (m * p).\nProof.\n intros.\n induction n.\n reflexivity.\n simpl.\n rewrite -> IHn.\n rewrite -> plus_assoc.\n reflexivity.\nQed.\n\nTheorem mult_assoc : forall n m p : nat,\n n * (m * p) = (n * m) * p.\nProof.\n intros.\n induction n.\n reflexivity.\n simpl.\n rewrite -> IHn.\n rewrite mult_plus_distr_r.\n reflexivity.\nQed.\n\n\n(******************************)\n(* standard, recommended (binary_commute) \n\n Recall the [incr] and [bin_to_nat] functions that you\n wrote for the [binary] exercise in the [Basics] chapter. Prove\n that the following diagram commutes:\n\n incr\n bin ----------------------> bin\n | |\n bin_to_nat | | bin_to_nat\n | |\n v v\n nat ----------------------> nat\n S\n\n That is, incrementing a binary number and then converting it to\n a (unary) natural number yields the same result as first converting\n it to a natural number and then incrementing.\n Name your theorem [bin_to_nat_pres_incr] (\"pres\" for \"preserves\").\n*)\n\n\nLemma S_m_n : forall n m : nat,\n S ( m + n ) = S m + n.\nProof.\n intros.\n induction n;reflexivity.\nQed.\n\nLemma incr_m_S_nat_m : forall m : bin,\n bin_to_nat m + 1 = S (bin_to_nat m).\nProof.\n intros.\n induction m.\n reflexivity.\n simpl.\n rewrite <- plus_n_O.\n rewrite <- plus_assoc.\n rewrite -> IHm.\n rewrite S_m_n.\n rewrite <- plus_comm.\n reflexivity.\n simpl.\n rewrite <- plus_n_O.\n rewrite -> S_m_n.\n rewrite <- plus_comm.\n reflexivity.\nQed.\n\nLemma bin_to_nat_pres_incr : forall m : bin,\n bin_to_nat (incr m) = S (bin_to_nat m).\nProof.\n intros m.\n induction m.\n reflexivity.\n simpl.\n rewrite <- plus_n_O.\n rewrite <- plus_assoc.\n rewrite plus_n_Sm.\n rewrite <- incr_m_S_nat_m.\n reflexivity.\n simpl.\n rewrite <- plus_n_O.\n rewrite <- plus_n_O.\n rewrite -> IHm.\n simpl.\n rewrite <- incr_m_S_nat_m.\n simpl.\n rewrite -> S_m_n.\n rewrite -> S_m_n.\n rewrite -> S_m_n.\n rewrite <- plus_assoc.\n reflexivity.\nQed.\n\n\n\n\n(* advanced (binary_inverse) \n\n This is a further continuation of the previous exercises about\n binary numbers. You may find you need to go back and change your\n earlier definitions to get things to work here.\n\n (a) First, write a function to convert natural numbers to binary\n numbers. *)\n\nFixpoint nat_to_bin (n:nat) : bin :=\n match n with\n | O => Z\n | S n' => incr (nat_to_bin n')\n end.\n\n(** Prove that, if we start with any [nat], convert it to binary, and\n convert it back, we get the same [nat] we started with. (Hint: If\n your definition of [nat_to_bin] involved any extra functions, you\n may need to prove a subsidiary lemma showing how such functions\n relate to [nat_to_bin].) *)\n\nTheorem nat_bin_nat : forall n, bin_to_nat (nat_to_bin n) = n.\nProof.\n intros.\n induction n.\n reflexivity.\n simpl.\n rewrite bin_to_nat_pres_incr.\n rewrite IHn.\n reflexivity.\nQed.\n\n(** (b) One might naturally expect that we should also prove the\n opposite direction -- that starting with a binary number,\n converting to a natural, and then back to binary should yield\n the same number we started with. However, this is not the\n case! Explain (in a comment) what the problem is. *)\n\n(**** The defined Binary Representation for each nat is not unique.\n For example 0 can be represnted as Z, B Z, B B B Z, ... ****)\n\n\n(** (c) Define a normalization function -- i.e., a function\n [normalize] going directly from [bin] to [bin] (i.e., _not_ by\n converting to [nat] and back) such that, for any binary number\n [b], converting [b] to a natural and then back to binary yields\n [(normalize b)]. Prove it. (Warning: This part is a bit\n tricky -- you may end up defining several auxiliary lemmas.\n One good way to find out what you need is to start by trying\n to prove the main statement, see where you get stuck, and see\n if you can find a lemma -- perhaps requiring its own inductive\n proof -- that will allow the main proof to make progress.) Don't\n define this using [nat_to_bin] and [bin_to_nat]! *)\n\n\n\n(* Double of Z is Z and double of anything else is just itself with another-\n zero in front of it *)\nFixpoint double_bin (b:bin) : bin :=\n match b with \n | Z => Z\n | _ => A b\n end.\n\n(* Normal of Z is Z,\n Normal of anything in form of \"n'0\" is normal of n' with 0 in front of it-\n (see double_bin definition)\n Normal of anything in form of \"n'1\" is normal of n' whit 1 in front of it\n\n This Definition can be rewrite without double, just using B as zero-concatinator\n*)\nFixpoint normalize (b:bin) : bin :=\n match b with\n | Z => Z\n | A b' => double_bin( normalize b')\n | B b' => B (normalize b')\n end.\n\n\nLemma double_inc : forall m : bin,\n double_bin ( incr m ) = incr (incr ( double_bin m )).\nProof.\n intros.\n induction m; reflexivity.\nQed.\n\nLemma double_to_plus : forall n : nat, \n nat_to_bin (n + n) = double_bin (nat_to_bin n). \nProof.\n intros.\n induction n.\n simpl.\n reflexivity.\n simpl.\n rewrite <- plus_n_Sm.\n simpl.\n rewrite -> IHn.\n simpl.\n rewrite double_inc.\n reflexivity.\nQed.\n\nLemma plus_1_to_inct : forall n : nat,\n nat_to_bin (n + 1) = incr (nat_to_bin n).\nProof.\n intros.\n induction n.\n reflexivity.\n simpl.\n rewrite IHn.\n reflexivity.\nQed.\n\nLemma incr_double : forall m : bin,\n incr (double_bin m) = B m.\nProof.\n intros.\n induction m;reflexivity.\nQed.\n\nTheorem bin_nat_bin: forall m : bin,\n nat_to_bin (bin_to_nat m) = normalize m.\nProof.\n intros.\n induction m.\n reflexivity.\n simpl.\n rewrite <- plus_n_O.\n rewrite double_to_plus.\n rewrite IHm; reflexivity.\n simpl.\n rewrite <- plus_n_O.\n rewrite plus_1_to_inct.\n rewrite double_to_plus.\n rewrite IHm.\n rewrite incr_double.\n reflexivity.\nQed.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Sajadrahimi", "repo": "Software-Foundations-Coq", "sha": "507f417aae16898b7f6de68823bec13a96ab65e0", "save_path": "github-repos/coq/Sajadrahimi-Software-Foundations-Coq", "path": "github-repos/coq/Sajadrahimi-Software-Foundations-Coq/Software-Foundations-Coq-507f417aae16898b7f6de68823bec13a96ab65e0/ch1/induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172623206391, "lm_q2_score": 0.936285002192296, "lm_q1q2_score": 0.8884570010321872}} {"text": "(** * MoreProp: More about Propositions and Evidence *)\n\nRequire Export \"Prop\".\n\n\n(* ####################################################### *)\n(** * Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n [beautiful]) can be thought of as a _property_ -- i.e., it defines\n a subset of [nat], namely those numbers for which the proposition\n is provable. In the same way, a two-argument proposition can be\n thought of as a _relation_ -- i.e., it defines a set of pairs for\n which the proposition is provable. *)\n\nModule LeModule. \n\n\n(** One useful example is the \"less than or equal to\"\n relation on numbers. *)\n\n(** The following definition should be fairly intuitive. It\n says that there are two ways to give evidence that one number is\n less than or equal to another: either observe that they are the\n same number, or give evidence that the first is less than or equal\n to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n | le_n : forall n, le n n\n | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n [le_S] follow the same patterns as proofs about properties, like\n [ev] in chapter [Prop]. We can [apply] the constructors to prove [<=]\n goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n tactics like [inversion] to extract information from [<=]\n hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** Here are some sanity checks on the definition. (Notice that,\n although these are the same kind of simple \"unit tests\" as we gave\n for the testing functions we wrote in the first few lectures, we\n must construct their proofs explicitly -- [simpl] and\n [reflexivity] don't do the job, because the proofs aren't just a\n matter of simplifying computations.) *)\n \nTheorem test_le1 :\n 3 <= 3.\nProof.\n (* WORKED IN CLASS *)\n apply le_n. Qed.\n\nTheorem test_le2 :\n 3 <= 6.\nProof.\n (* WORKED IN CLASS *)\n apply le_S. apply le_S. apply le_S. apply le_n. Qed.\n\nTheorem test_le3 :\n (2 <= 1) -> 2 + 2 = 5.\nProof. \n (* WORKED IN CLASS *)\n intros H. inversion H. inversion H2. Qed.\n\n(** The \"strictly less than\" relation [n < m] can now be defined\n in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n | nn : next_nat n (S n).\n\nInductive next_even (n:nat) : nat -> Prop :=\n | ne_1 : ev (S n) -> next_even n (S n)\n | ne_2 : ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation) *)\n(** Define an inductive binary relation [total_relation] that holds\n between every pair of natural numbers. *)\nInductive total : nat -> nat -> Prop := \n |total' : forall (n m : nat), total n m.\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n that never holds. *)\nInductive empty : nat -> nat -> Prop := .\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\n(** Here are a number of facts about the [<=] and [<] relations that\n we are going to need later in the course. The proofs make good\n practice exercises. *)\n \nLemma S_Le : forall n m, S n <= m -> n <= m.\nProof.\n intros. induction H. apply le_S. apply le_n.\n apply le_S. apply IHle. Qed.\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n intros. induction H. apply H0. apply S_Le in H0. apply IHle in H0.\n apply H0. Qed.\n\n\n\nTheorem O_le_n : forall n,\n 0 <= n.\nProof.\n intros. induction n. apply le_n. apply le_S. apply IHn. Qed.\n\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n n <= m -> S n <= S m.\nProof. \n intros n m H. induction H. reflexivity.\n apply le_S. apply IHle. Qed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n S n <= S m -> n <= m.\nProof. \n intros. inversion H. apply le_n. apply S_Le in H1. apply H1.\n Qed.\n\nTheorem le_plus_l : forall a b,\n a <= a + b.\nProof. \n\n intros. induction a. simpl. apply O_le_n.\n simpl. apply n_le_m__Sn_le_Sm. apply IHa.\n Qed.\n\nTheorem plus_lt : forall n1 n2 m,\n n1 + n2 < m ->\n n1 < m /\\ n2 < m.\nProof. \n unfold lt. intros. apply conj. \n Case \"n1 < m\".\n induction H. \n SCase \"base case\". apply n_le_m__Sn_le_Sm. apply le_plus_l.\n SCase \"inductive case\". apply le_S. apply IHle.\n Case \"n2 < m\".\n induction H.\n SCase \"base case\". apply n_le_m__Sn_le_Sm. \n assert(H:n1 + n2 = n2 + n1). apply plus_comm. rewrite -> H.\n apply le_plus_l.\n SCase \"inductive case\". apply le_S. apply IHle.\n Qed.\n\nTheorem lt_S : forall n m,\n n < m ->\n n < S m.\nProof.\n unfold lt. intros. apply S_Le in H. apply n_le_m__Sn_le_Sm in H.\n apply H. Qed.\n\n\nTheorem ble_nat_true : forall n m,\n ble_nat n m = true -> n <= m.\nProof. \n intros n. induction n.\n intros. destruct m. apply le_n. apply O_le_n.\n intros. destruct m. simpl in H. inversion H.\n simpl in H. apply IHn in H. apply n_le_m__Sn_le_Sm.\n apply H. Qed.\n\nTheorem le_ble_nat : forall n m,\n n <= m ->\n ble_nat n m = true.\nProof.\n intros. generalize dependent n. induction m.\n intros. destruct n. reflexivity. inversion H.\n intros. destruct n. simpl. reflexivity. simpl.\n apply IHm. apply Sn_le_Sm__n_le_m. apply H.\n Qed.\n\nTheorem ble_nat_true_trans : forall n m o,\n ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true. \nProof.\n intros. apply le_ble_nat. apply ble_nat_true in H. apply ble_nat_true in H0.\n apply le_trans with (n := m). apply H. apply H0. Qed.\n\n(** **** Exercise: 3 stars (R_provability) *)\nModule R.\n(** We can define three-place relations, four-place relations,\n etc., in just the same way as binary relations. For example,\n consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n | c1 : R 0 0 0 \n | c2 : forall m n o, R m n o -> R (S m) n (S o)\n | c3 : forall m n o, R m n o -> R m (S n) (S o)\n | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n - [R 1 1 2] yes\n - [R 2 2 6] yes\n\n - If we dropped constructor [c5] from the definition of [R],\n would the set of provable propositions change? Briefly (1\n sentence) explain your answer.\n \nYes, then we could not prove either of the propositions \n\n\n - If we dropped constructor [c4] from the definition of [R],\n would the set of provable propositions change? Briefly (1\n sentence) explain your answer.\n\nNo, we could still prove both propositions\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact) *) \n(** Relation [R] actually encodes a familiar function. State and prove two\n theorems that formally connects the relation and the function. \n That is, if [R m n o] is true, what can we say about [m],\n [n], and [o], and vice versa?\n*)\n\nTheorem plusImpliesR : forall (m n o : nat), \n R m n o -> m + n = o.\nProof.\n intros.\n induction H.\n {reflexivity. }\n {simpl. apply f_equal. apply IHR. }\n {rewrite <- plus_n_Sm. apply f_equal. apply IHR. }\n {simpl in IHR. inversion IHR. rewrite <- plus_n_Sm in H1.\n inversion H1. reflexivity. }\n {rewrite -> plus_comm. apply IHR. }\n Qed.\n\nTheorem RImpliesPlus : forall (m n o : nat),\n m + n = o -> R m n o.\nProof.\n intros.\n Admitted.\n\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd R.\n\n\n(* ##################################################### *)\n(** * Programming with Propositions *)\n\n(** A _proposition_ is a statement expressing a factual claim,\n like \"two plus two equals four.\" In Coq, propositions are written\n as expressions of type [Prop]. Although we haven't discussed this\n explicitly, we have already seen numerous examples. *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** Both provable and unprovable claims are perfectly good\n propositions. Simply _being_ a proposition is one thing; being\n _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n of type [Prop]. *)\n\n(** We've mainly seen one place that propositions can appear in Coq: in\n [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 : \n 2 + 2 = 4.\nProof. reflexivity. Qed.\n\n(** But they can be used in many other ways. For example, we have also seen that\n we can give a name to a proposition using a [Definition], just as we have\n given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop := 2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true : \n plus_fact.\nProof. reflexivity. Qed.\n\n(** We've seen several ways of constructing propositions. \n\n - We can define a new proposition primitively using [Inductive].\n\n - Given two expressions [e1] and [e2] of the same type, we can\n form the proposition [e1 = e2], which states that their\n values are equal.\n\n - We can combine propositions using implication and\n quantification. *)\n\n(** We have also seen _parameterized propositions_, such as [even] and\n [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even. \n(* ===> even : nat -> Prop *)\n\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n three equivalent ways: (1) \"[even] is a _function_ from numbers to\n propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n by a number [n],\" or (3) \"[even] is a _property_ of numbers.\" *)\n\n(** Propositions -- including parameterized propositions -- are\n first-class citizens in Coq. For example, we can define functions\n from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n P 0.\n\n(** Here are two more examples of passing parameterized propositions\n as arguments to a function. \n\n The first function, [true_for_all_numbers], takes a proposition\n [P] as argument and builds the proposition that [P] is true for\n all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n that, if [P] is true for some natural number [n'], then it is also\n true by the successor of [n'] -- i.e. that [P] is _preserved by\n successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n forall n', P n' -> P (S n').\n\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n forall (P:nat->Prop),\n true_for_zero P ->\n preserved_by_S P -> \n true_for_all_numbers P. \n\n\n\n(** **** Exercise: 3 stars (combine_odd_even) *)\n(** Complete the definition of the [combine_odd_even] function\n below. It takes as arguments two properties of numbers [Podd] and\n [Peven]. As its result, it should return a new property [P] such\n that [P n] is equivalent to [Podd n] when [n] is odd, and\n equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n (fun n => if oddb n then Podd n else Peven n).\n\n\n(** To test your definition, see whether you can prove the following\n facts: *)\n\nTheorem combine_odd_even_intro : \n forall (Podd Peven : nat -> Prop) (n : nat),\n (oddb n = true -> Podd n) ->\n (oddb n = false -> Peven n) ->\n combine_odd_even Podd Peven n.\nProof.\n intros. unfold combine_odd_even. destruct (oddb n) eqn : H1. \n apply H. reflexivity. apply H0. reflexivity.\n Qed.\n\nTheorem combine_odd_even_elim_odd :\n forall (Podd Peven : nat -> Prop) (n : nat),\n combine_odd_even Podd Peven n ->\n oddb n = true ->\n Podd n.\nProof.\n intros. unfold combine_odd_even in H. rewrite -> H0 in H. apply H.\n Qed.\n\nTheorem combine_odd_even_elim_even :\n forall (Podd Peven : nat -> Prop) (n : nat),\n combine_odd_even Podd Peven n ->\n oddb n = false ->\n Peven n.\nProof.\n intros. unfold combine_odd_even in H. rewrite -> H0 in H.\n apply H. Qed.\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n parameterized propositions using [Definition], then can we also\n define them using [Fixpoint]? Of course we can! However, this\n kind of \"recursive parameterization\" doesn't correspond to\n anything very familiar from everyday mathematics. The following\n exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)\n(** Define a recursive function\n [true_upto_n__true_everywhere] that makes\n [true_upto_n_example] work. *)\n\n\nFixpoint true_upto_n__true_everywhere (n : nat) (p : nat -> Prop) : Prop := \n match n with\n |S n' => even n -> true_upto_n__true_everywhere n' p\n |0 => forall m : nat, even m\n end.\n\nExample true_upto_n_example :\n (true_upto_n__true_everywhere 3 (fun n => even n))\n = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n\n", "meta": {"author": "lexxx320", "repo": "PersonalProjects", "sha": "bc83fb250467b013d9db9fe535ff7bd314632d4c", "save_path": "github-repos/coq/lexxx320-PersonalProjects", "path": "github-repos/coq/lexxx320-PersonalProjects/PersonalProjects-bc83fb250467b013d9db9fe535ff7bd314632d4c/software_foundations/MoreProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867715, "lm_q2_score": 0.9324533036984185, "lm_q1q2_score": 0.8875680086214555}} {"text": "\n(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\n\nModule NatList. \n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as in this definition: *)\n\nInductive natprod : Type :=\n pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\n(** We can construct an element of [natprod] like this: *)\n\nCheck (pair 3 5).\n\n(** *** *)\n\n(** Here are two simple function definitions for extracting the\n first and second components of a pair. (The definitions also\n illustrate how to do pattern matching on two-argument\n constructors.) *)\n\nDefinition fst (p : natprod) : nat := \n match p with\n | pair x y => x\n end.\nDefinition snd (p : natprod) : nat := \n match p with\n | pair x y => y\n end.\n\nEval compute in (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** *** *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this notation is provided as part of the standard\n library): *)\n\nEval compute in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat := \n match p with\n | (x,y) => x\n end.\nDefinition snd' (p : natprod) : nat := \n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod := \n match p with\n | (x,y) => (y,x)\n end.\n\n(** *** *)\n\n(** Let's try and prove a few simple facts about pairs. If we\n state the lemmas in a particular (and slightly peculiar) way, we\n can prove them with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** Note that [reflexivity] is not enough if we state the lemma in a\n more natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** *** *)\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct].\n\n Notice that, unlike for [nat]s, [destruct] doesn't generate an\n extra subgoal here. That's because [natprod]s can only be\n constructed in one way. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros. destruct p as [m n]. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros. destruct p as [m n]. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n describe the type of _lists_ of numbers like this: \"A list is\n either the empty list or else a pair of a number and another\n list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n\n(** *** *)\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following two declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n but in case you are interested, here is roughly what's going on.\n\n The [right associativity] annotation tells Coq how to parenthesize\n expressions involving several uses of [::] so that, for example,\n the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\nNotation \"x + y\" := (plus x y) \n (at level 50, left associativity).\n The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (By the way, it's worth noting in passing that expressions like \"[1\n + 2 :: [3]]\" can be a little confusing when you read them in a .v\n file. The inner brackets, around 3, indicate a list, but the outer\n brackets, which are invisible in the HTML rendering, are there to\n instruct the \"coqdoc\" tool that the bracketed part should be\n displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(** *** Repeat *)\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist := \n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(** *** Length *)\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat := \n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(** *** Append *)\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist := \n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y) \n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\"). \n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\n(** *** Head (with default) and Tail *)\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil \n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | nil => nil\n | 0 :: t => nonzeros t\n | h :: t => h :: nonzeros t\n end.\n\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => match oddb h with\n | true => h :: oddmembers t\n | false => oddmembers t\n end\n end.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n match l with\n | nil => 0\n | h :: t => match oddb h with\n | true => 1 + countoddmembers t\n | false => countoddmembers t\n end\n end.\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers3: countoddmembers nil = 0.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h1 :: t1 => match l2 with\n | nil => l1\n | h2 :: t2 => h1 :: h2 :: (alternate t1 t2)\n end\n end.\n\n(* \nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h :: t => h :: alternate l2 t\n end.\n*)\n\n\nExample test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n (* FILL IN HERE *) Admitted.\nExample test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].\n (* FILL IN HERE *) Admitted.\nExample test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].\n (* FILL IN HERE *) Admitted.\nExample test_alternate4: alternate [] [20;30] = [20;30].\n (* FILL IN HERE *) Admitted. \n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n multiple times instead of just once. One reasonable\n implementation of bags is to represent a bag of numbers as a\n list. *)\n\nDefinition bag := natlist. \n\n(** **** Exercise: 3 stars (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat := \n match s with\n | nil => 0\n | h :: t => match beq_nat h v with\n | true => 1 + count v t\n | false => count v t\n end\n end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\n (* FILL IN HERE *) Admitted.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\n (* FILL IN HERE *) Admitted.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := v :: s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\n (* FILL IN HERE *) Admitted.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\n\nDefinition member (v:nat) (s:bag) : bool := negb (beq_nat 0 (count v s)).\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n (* When remove_one is applied to a bag without the number to remove,\n it should return the same bag unchanged. *)\n match s with\n | nil => nil\n | h :: t => match beq_nat h v with\n | true => t\n | false => h :: (remove_one v t)\n end\n end.\n\n\nExample test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one2: count 5 (remove_one 5 [2;1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_one3: count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n (* FILL IN HERE *) Admitted.\nExample test_remove_one4: count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n (* FILL IN HERE *) Admitted.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | h :: t => match beq_nat h v with\n | true => remove_all v t\n | false => h :: (remove_all v t)\n end\n end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n (* FILL IN HERE *) Admitted.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n match s1 with\n | nil => true\n | h :: t => andb (member h s2) (subset t (remove_one h s2))\n end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (bag_theorem) *)\n(** Write down an interesting theorem about bags involving the\n functions [count] and [add], and prove it. Note that, since this\n problem is somewhat open-ended, it's possible that you may come up\n with a theorem which is true, but whose proof requires techniques\n you haven't learned yet. Feel free to ask for help if you get\n stuck! *)\n\n(* FILL IN HERE *)\n\nLemma beq_n_n : \n forall (n : nat), beq_nat n n = true.\nProof.\n intros. induction n as [| n'].\n - reflexivity.\n - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem count_add_comm :\n forall (n : nat) (s : bag), count n (add n s) = 1 + count n s.\nProof.\n intros. destruct s.\n - simpl. rewrite -> beq_n_n. reflexivity.\n - simpl. rewrite -> beq_n_n. reflexivity.\nQed.\n\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match position\n in the definition of [app], allowing the match itself to be\n simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n l'\". \n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proofs will not get you very far! It is\n very important to work through the details of each one, using Coq\n and thinking about what each step of the proof achieves.\n Otherwise it is more or less guaranteed that the exercises will\n make no sense. *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n perhaps a little less familiar than standard natural number\n induction, but the basic idea is equally simple. Each [Inductive]\n declaration defines a set of data values that can be built up from\n the declared constructors: a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to a number; a\n list can be either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two things together establish the\n truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist, \n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3). \nProof.\n intros l1 l2 l3. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons n l1'\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n static written document -- it is easy to see what's going on if\n you are reading the proof in an interactive Coq session and you\n can see the current goal and context at each point, but this state\n is not visible in the written-down parts of the Coq proof. So a\n natural-language proof -- one written for human readers -- will\n need to include more explicit signposts; in particular, it will\n help the reader stay oriented if we remind them exactly what the\n induction hypothesis is in the second case. *)\n\n(** *** Informal version *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3], \n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n (the induction hypothesis). We must show\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]] \n By the definition of [++], this follows from\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n which is immediate from the induction hypothesis. []\n*)\n\n(** *** Another example *)\n(**\n Here is a similar example to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist, \n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n\n(** *** Reversing a list *)\n(** For a slightly more involved example of an inductive proof\n over lists, suppose we define a \"cons on the right\" function\n [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist := \n match l with\n | nil => [v]\n | h :: t => h :: (snoc t v)\n end.\n\n(** ... and use it to define a list-reversing function [rev]\n like this: *)\n\nFixpoint rev (l:natlist) : natlist := \n match l with\n | nil => nil\n | h :: t => snoc (rev t) h\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** *** Proofs about reverse *)\n(** Now let's prove some more list theorems using our newly\n defined [snoc] and [rev]. For something a little more challenging\n than the inductive proofs we've seen so far, let's prove that\n reversing a list does not change its length. Our first attempt at\n this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n :: l'\".\n (* This is the tricky case. Let's begin as usual \n by simplifying. *)\n simpl. \n (* Now we seem to be stuck: the goal is an equality \n involving [snoc], but we don't have any equations \n in either the immediate context or the global \n environment that have anything to do with [snoc]! \n\n We can make a little progress by using the IH to \n rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation about [snoc] that would have\n enabled us to make progress and prove it as a separate lemma. \n*)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n length (snoc l n) = S (length l).\nProof.\n intros n l. induction l as [| n' l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n' l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed. \n\n(**\n Note that we make the lemma as _general_ as possible: in particular,\n we quantify over _all_ [natlist]s, not just those that result\n from an application of [rev]. This should seem natural, \n because the truth of the goal clearly doesn't depend on \n the list having been reversed. Moreover, it is much easier\n to prove the more general property. \n*)\n \n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons\".\n simpl. rewrite -> length_snoc. \n rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems: \n\n _Theorem_: For all numbers [n] and lists [l],\n [length (snoc l n) = S (length l)].\n \n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (snoc [] n) = S (length []),\n which follows directly from the definitions of\n [length] and [snoc].\n\n - Next, suppose [l = n'::l'], with\n length (snoc l' n) = S (length l').\n We must show\n length (snoc (n' :: l') n) = S (length (n' :: l')).\n By the definitions of [length] and [snoc], this\n follows from\n S (length (snoc l' n)) = S (S (length l')),\n]] \n which is immediate from the induction hypothesis. [] *)\n \n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n \n _Proof_: By induction on [l]. \n\n - First, suppose [l = []]. We must show\n length (rev []) = length [],\n which follows directly from the definitions of [length] \n and [rev].\n \n - Next, suppose [l = n::l'], with\n length (rev l') = length l'.\n We must show\n length (rev (n :: l')) = length (n :: l').\n By the definition of [rev], this follows from\n length (snoc (rev l') n) = S (length l')\n which, by the previous lemma, is the same as\n S (length (rev l')) = S (length l').\n This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n and pedantic. After the first few, we might find it easier to\n follow proofs that give fewer details (since we can easily work\n them out in our own minds or on scratch paper if necessary) and\n just highlight the non-obvious steps. In this more compressed\n style, the above proof might look more like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that\n length (snoc l n) = S (length l)\n for any [l]. This follows by a straightforward induction on [l].\n The main property now follows by another straightforward\n induction on [l], using the observation together with the\n induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and on how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for\n present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, using [rewrite], and later we will see other ways\n of reusing previous theorems. But in order to refer to a theorem,\n we need to know its name, and remembering the names of all the\n theorems we might ever want to use can become quite difficult! It\n is often hard even to remember what theorems have been proven,\n much less what they are named.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following to\n see a list of theorems that we have proved about [rev]: *)\n\nSearchAbout rev. \n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the course; it can save you a lot of time! *)\n\n(** Also, if you are using ProofGeneral, you can run [SearchAbout]\n with [C-c C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist, \n l ++ [] = l. \nProof.\n intros. induction l as [| n l'].\n - reflexivity.\n - simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nLemma rev_snoc_cons : \n forall (l : natlist) (n : nat), rev (snoc l n) = n :: rev l.\nProof.\n intros. induction l as [| h t].\n - reflexivity.\n - simpl. rewrite -> IHt. reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros. induction l as [| h t].\n - reflexivity.\n - simpl. rewrite -> rev_snoc_cons. rewrite -> IHt. reflexivity.\nQed.\n\n(** There is a short solution to the next exercise. If you find\n yourself getting tangled up, step back and try to look for a\n simpler way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros. rewrite -> app_assoc. rewrite -> app_assoc. reflexivity.\nQed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n snoc l n = l ++ [n].\nProof.\n intros. induction l as [| h t].\n - reflexivity.\n - simpl. rewrite -> IHt. reflexivity.\nQed.\n\nLemma app_nil :\n forall (l : natlist), l ++ [] = l.\nProof.\n intros. induction l as [| h t].\n - reflexivity.\n - simpl. rewrite -> IHt. reflexivity.\nQed.\n\nTheorem distr_rev : forall l1 l2 : natlist,\n rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n intros. induction l1 as [| h t].\n - rewrite -> nil_app. simpl. rewrite -> app_nil. reflexivity.\n - simpl. rewrite -> IHt. \n rewrite -> snoc_append. rewrite -> snoc_append. \n rewrite -> app_assoc. reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros. induction l1 as [| h1 t1].\n - reflexivity.\n - simpl. destruct h1; rewrite IHt1; reflexivity.\nQed.\n \n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n match l1, l2 with\n | nil, nil => true\n | h1::t1, h2::t2 => andb (beq_nat h1 h2) (beq_natlist t1 t2)\n | _, _ => false\n end.\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\n (* FILL IN HERE *) Admitted.\nExample test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\nExample test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.\n (* FILL IN HERE *) Admitted.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\n intros. induction l as [| h t].\n - reflexivity.\n - simpl. rewrite <- IHt. rewrite <- beq_nat_refl. reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 2 stars (list_design) *)\n(** Design exercise: \n - Write down a non-trivial theorem involving [cons]\n ([::]), [snoc], and [app] ([++]). \n - Prove it. *) \n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n definitions about bags earlier in the file. *)\nTheorem count_member_nonzero : forall (s : bag),\n ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n intros. reflexivity. Qed.\n\n(** The following lemma about [ble_nat] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n ble_nat n (S n) = true.\nProof.\n intros n. induction n as [| n'].\n Case \"0\". \n simpl. reflexivity.\n Case \"S n'\".\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n intros. induction s as [| h t].\n - reflexivity.\n - simpl. destruct (beq_nat h 0) eqn:?.\n + rewrite -> ble_n_Sn. reflexivity.\n + simpl. rewrite -> Heqb. rewrite -> IHt. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *) \n(** Write down an interesting theorem about bags involving the\n functions [count] and [sum], and prove it.*)\n\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nThere is a hard way and an easy way to solve this exercise.\n*)\n\nTheorem rev_injective : \n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\nProof.\n intros. \n rewrite <- rev_involutive.\n rewrite <- H.\n rewrite -> rev_involutive.\n reflexivity.\nQed.\n\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n\n(** One use of [natoption] is as a way of returning \"error\n codes\" from functions. For example, suppose we want to write a\n function that returns the [n]th element of some list. If we give\n it type [nat -> natlist -> nat], then we'll have to return some\n number when the list is too short! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with \n | true => a \n | false => index_bad (pred n) l' \n end\n end.\n\n(** *** *)\n(** On the other hand, if we give it type [nat -> natlist ->\n natoption], then we can return [None] when the list is too short\n and [Some a] when the list has enough members and [a] appears at\n position [n]. *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption. \n\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => match beq_nat n O with \n | true => Some a\n | false => index (pred n) l' \n end\n end.\n\nExample test_index1 : index 0 [4;5;6;7] = Some 4.\nProof. reflexivity. Qed.\nExample test_index2 : index 3 [4;5;6;7] = Some 7.\nProof. reflexivity. Qed.\nExample test_index3 : index 10 [4;5;6;7] = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n small feature of Coq's programming language: conditional\n expressions... *)\n\n(** *** *)\n\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => if beq_nat n O then Some a else index' (pred n) l'\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_opt (l : natlist) : natoption :=\n match l with\n | nil => None\n | h :: t => Some h\n end.\n\nExample test_hd_opt1 : hd_opt [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_opt l).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Dictionaries *)\n\n(** As a final illustration of how fundamental data structures\n can be defined in Coq, here is the declaration of a simple\n [dictionary] data type, using numbers for both the keys and the\n values stored under these keys. (That is, a dictionary represents\n a finite map from numbers to numbers.) *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n | empty : dictionary \n | record : nat -> nat -> dictionary -> dictionary. \n\n(** This declaration can be read: \"There are two ways to construct a\n [dictionary]: either using the constructor [empty] to represent an\n empty dictionary, or by applying the constructor [record] to\n a key, a value, and an existing [dictionary] to construct a\n [dictionary] with an additional key to value mapping.\" *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n (record key value d).\n\n(** Here is a function [find] that searches a [dictionary] for a\n given key. It evaluates evaluates to [None] if the key was not\n found and [Some val] if the key was mapped to [val] in the\n dictionary. If the same key is mapped to multiple values, [find]\n will return the first one it finds. *)\n\nFixpoint find (key : nat) (d : dictionary) : natoption := \n match d with \n | empty => None\n | record k v d' => if (beq_nat key k) \n then (Some v) \n else (find key d')\n end.\n\n\n\n(** **** Exercise: 1 star (dictionary_invariant1) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n (find k (insert k v d)) = Some v.\nProof.\n intros. simpl. rewrite <- beq_nat_refl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),\n beq_nat m n = false -> find m d = find m (insert n o d).\nProof.\n intros. simpl. rewrite -> H. reflexivity. Qed.\n(** [] *)\n\n\n\nEnd Dictionary.\n\nEnd NatList.\n\n(* $Date: 2014-01-28 13:19:45 -0500 (Tue, 28 Jan 2014) $ *)\n\n", "meta": {"author": "dm0n3y", "repo": "sf", "sha": "bbc34446bf35bd9be29e545c617702c4411157f0", "save_path": "github-repos/coq/dm0n3y-sf", "path": "github-repos/coq/dm0n3y-sf/sf-bbc34446bf35bd9be29e545c617702c4411157f0/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092412, "lm_q2_score": 0.9362849999699592, "lm_q1q2_score": 0.8870186674093558}} {"text": "From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat.\n\n(*** Exercise 1 *)\n\n(** 1a. Define [orb_my] function implementing boolean disjunction *)\n\nDefinition orb_my (b1 b2:bool) : bool :=\n if b1 then true else b2.\n\n(** 1b. Figure out the implementation of [orb] function in the standard library\n using Coq's interactive query mechanism *)\n\nPrint orb.\n\n(** 1c. What's the difference between the standard implementation and\n the following one? *)\n\nDefinition orb_table (b c : bool) : bool :=\n match b, c with\n | true, true => true\n | true, false => true\n | false, true => true\n | false, false => false\n end.\n\n(** Note: the above translates into nested pattern-matching, check this *)\n\nPrint orb_table.\nPrint orb_my.\n\n(** 1d. Define [addb_my] function implementing exclusive boolean disjunction.\n {The name [addb] comes from the fact this operation behaves like addition modulo 2}\n If you are already familiar with proofs in Coq, think of a prover friendly\n definition, if you are not -- experiment with how different implementations\n behave under symbolic execution. *)\n\nDefinition addb_my (a b : bool) : bool :=\n match a, b with\n | true, false => true\n | false, true => true\n | _, _ => false\n end.\n\nVariable x : bool.\n\nCompute addb_my x true.\nCompute addb_my true x.\n\n(*** Exercise 2 *)\n\n(** 2a. Implement power function of two arguments [x] and [n],\n raising [x] to the power of [n] *)\n\nFixpoint power (x n : nat) : nat :=\n match n with\n | O => S O\n | S p => muln x (power x p)\n end.\n\nCompute (power 2 2).\nCompute (power 2 3).\nCompute (power 2 4).\n\n(*** Exercise 3 *)\n\n(** 3a. Implement division on unary natural numbers *)\n\nCompute subn 4 1.\n\nFixpoint divn_my (a b : nat) : nat :=\n if b is b'.+1 then\n if subn a b' is n'.+1\n then S (divn_my n' b)\n else O\n else O.\n\nLemma div_my_n0 : forall x : nat, divn_my x 0 = 0. Proof. by case. Qed.\nLemma div_my_0n : forall x : nat, divn_my 0 x = 0. Proof. by case. Qed.\n\n(* Unit tests: *)\nCompute divn_my 0 0. (* = 0 *)\nCompute divn_my 1 0. (* = 0 *)\nCompute divn_my 0 3. (* = 0 *)\nCompute divn_my 1 3. (* = 0 *)\nCompute divn_my 2 3. (* = 0 *)\nCompute divn_my 3 3. (* = 1 *)\nCompute divn_my 8 3. (* = 2 *)\nCompute divn_my 42 1. (* = 42 *)\nCompute divn_my 42 2. (* = 21 *)\nCompute divn_my 42 3. (* = 14 *)\nCompute divn_my 42 4. (* = 10 *)\n\nFrom mathcomp Require Import div.\n\nCompute divn 42 4. (* = 10 *)\n\nTheorem div_eq_divn_my :\n forall x y : nat, divn_my x y = divn x y.\nProof.\n case.\n - by case; rewrite ?div0n ?divn0.\n - move => x y.\n elim: y => [| y' IHy'].\n + by rewrite divn0.\n\n (* Тут ничего не поможет из того, что мне на данный момент известно.\n Для доказательства понадобится сильная индукция\n (complete induction, course-of-values). *)\n\n (* div0n forall d : nat, 0 %/ d = 0 *)\n (* divn0 forall m : nat, m %/ 0 = 0 *)\nAdmitted.\n\n(** 3b. Provide several unit tests using [Compute] vernacular command *)\n\n\n(*** Exercise 4 *)\n\n(** Use the [applyn] function defined during the lecture\n (or better its Mathcomp sibling called [iter]) define\n\n 4a. addition on natural numbers\n\n 4b. multiplication on natural numbers\n\n Important: don't use recursion, i.e. no [Fixpoint] /\n [fix] should be in your solution.\n*)\n\n(** Here is out definition of [applyn]: *)\nDefinition applyn (f : nat -> nat) :=\n fix rec (n : nat) (x : nat) :=\n if n is n'.+1 then rec n' (f x)\n else x.\n\nPrint iter.\n\nDefinition addn' (x y : nat) : nat := applyn S x y.\n\nCompute (iter 5 S 0).\n\nDefinition addn'' (x y : nat) : nat := iter x S y.\n\nCompute addn' 5 4.\nCompute addn' 7 5.\n\nCompute addn'' 5 4.\nCompute addn'' 7 5.\n\nDefinition muln' (n x : nat) : nat :=\n iter (predn n) (fun v => addn' v x) x.\n\nCompute muln' 8 8.\n", "meta": {"author": "vyorkin", "repo": "coq-fv", "sha": "d65348888fc51722585d81f189fd1b71da7b8c3b", "save_path": "github-repos/coq/vyorkin-coq-fv", "path": "github-repos/coq/vyorkin-coq-fv/coq-fv-d65348888fc51722585d81f189fd1b71da7b8c3b/homework/hw01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191246389618, "lm_q2_score": 0.9284088015458667, "lm_q1q2_score": 0.886926683599905}} {"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\nModule NatList. \n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as in this definition: *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is one way to construct\n a pair of numbers: by applying the constructor [pair] to two\n arguments of type [nat].\" *)\n\n(** We can construct an element of [natprod] like this: *)\n\nCheck (pair 3 5).\n\n(** Here are two simple function definitions for extracting the\n first and second components of a pair. (The definitions also\n illustrate how to do pattern matching on two-argument\n constructors.) *)\n\nDefinition fst (p : natprod) : nat := \n match p with\n | pair x y => x\n end.\nDefinition snd (p : natprod) : nat := \n match p with\n | pair x y => y\n end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this notation is provided as part of the standard\n library): *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat := \n match p with\n | (x,y) => x\n end.\nDefinition snd' (p : natprod) : nat := \n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod := \n match p with\n | (x,y) => (y,x)\n end.\n\n(** Let's try and prove a few simple facts about pairs. If we\n state the lemmas in a particular (and slightly peculiar) way, we\n can prove them with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** Note that [reflexivity] is not enough if we state the lemma in a\n more natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct].\n\n Notice that, unlike for [nat]s, [destruct] doesn't generate an\n extra subgoal here. That's because [natprod]s can only be\n constructed in one way. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p. destruct p as [n m].\n simpl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros p. destruct p as [n m].\n simpl. reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n describe the type of _lists_ of numbers like this: \"A list is\n either the empty list or else a pair of a number and another\n list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following two declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n but in case you are interested, here is roughly what's going on.\n\n The [right associativity] annotation tells Coq how to parenthesize\n expressions involving several uses of [::] so that, for example,\n the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\nNotation \"x + y\" := (plus x y) \n (at level 50, left associativity).\n The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (By the way, it's worth noting in passing that expressions like \"[1\n + 2 :: [3]]\" can be a little confusing when you read them in a .v\n file. The inner brackets, around 3, indicate a list, but the outer\n brackets, which are invisible in the HTML rendering, are there to\n instruct the \"coqdoc\" tool that the bracketed part should be\n displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(** *** Repeat *)\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist := \n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(** *** Length *)\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat := \n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\nCompute (length [4;5;6;7]).\n\n(** *** Append *)\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist := \n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y) \n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\"). \n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\n(** *** Head (with default) and Tail *)\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil \n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | nil => nil \n | 0 :: t => (nonzeros t)\n | h :: t => h :: nonzeros t\n end.\n\n\nExample test_nonzeros:\n nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n Proof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => match oddb h with\n | true => h :: (oddmembers t)\n | false => oddmembers t\n end\nend.\n\nExample test_oddmembers:\n oddmembers [0;1;0;2;3;0;0] = [1;3].\n Proof. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat := \n match l with\n | nil => 0\n | h :: t => match oddb h with\n | false => countoddmembers t\n | true => S( countoddmembers t)\n end \nend.\n\nExample test_countoddmembers1:\n countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers2:\n countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers3:\n countoddmembers nil = 0.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h1 :: t1 => match l2 with\n | nil => l1\n | h2 :: t2 => h1 :: h2 :: (alternate t1 t2)\n end\nend.\n\n\nExample test_alternate1:\n alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n Proof. reflexivity. Qed.\n\nExample test_alternate2:\n alternate [1] [4;5;6] = [1;4;5;6].\n Proof. reflexivity. Qed.\n\nExample test_alternate3:\n alternate [1;2;3] [4] = [1;4;2;3].\n Proof. reflexivity. Qed.\n\nExample test_alternate4:\n alternate [] [20;30] = [20;30].\n Proof. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n multiple times instead of just once. One reasonable\n implementation of bags is to represent a bag of numbers as a\n list. *)\n\nDefinition bag := natlist. \n\n(** **** Exercise: 3 stars (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat := \n match s with \n | [] => 0\n | h :: t => match beq_nat v h with\n | true => S (count v t)\n | _ => (count v t)\n end\n end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\n Proof. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\n Proof. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := app.\n\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\n Proof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := \n match v with\n | O => sum [0] s\n | _ => sum [v] s\nend.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\n Proof. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\n Proof. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool := \n match count v s with\n | 0 => false\n | _ => true\nend.\n\nExample test_member1: member 1 [1;4;1] = true.\n Proof. reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\n Proof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | h :: t => match beq_nat v h with\n | true => t\n | false => h :: (remove_one v t)\n end\nend.\n\nExample test_remove_one1:\n count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n Proof. reflexivity. Qed.\n\nExample test_remove_one2:\n count 5 (remove_one 5 [2;1;4;1]) = 0.\n Proof. reflexivity. Qed.\n\nExample test_remove_one3:\n count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n Proof. reflexivity. Qed.\n\nExample test_remove_one4:\n count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n Proof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | h :: t => match beq_nat v h with\n | true => remove_all v t\n | false => h :: remove_all v t\n end\nend.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n Proof. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\n Proof. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n Proof. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n Proof. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n match s1 with\n | nil => true\n | h1 :: t1 => match count h1 s2 with\n | 0 => false\n | _ => subset t1 (remove_one h1 s2)\n end\nend.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\n Proof. reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\n Proof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (bag_theorem) *)\n(** Write down an interesting theorem [bag_theorem] about bags\n involving the functions [count] and [add], and prove it. For\n this, replace the [admit] command below with the statement of your\n theorem. Note that, since this problem is somewhat open-ended,\n it's possible that you may come up with a theorem which is true,\n but whose proof requires techniques you haven't learned yet. Feel\n free to ask for help if you get stuck! *)\n\n\nTheorem bag_theorem :\n forall (s1:bag), \n leb (count 0 s1) (length (add 1 s1)) = true.\nProof.\n intros s1.\n induction s1.\n -simpl. reflexivity.\n -induction n as [| n'].\n +simpl. simpl in IHs1. rewrite -> IHs1. reflexivity.\n +simpl. simpl in IHs1. \nAbort.\n\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match position\n in the definition of [app], allowing the match itself to be\n simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons n l' *)\n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n It is important to work through the details of each one, using Coq\n and thinking about what each step achieves. Otherwise it is more\n or less guaranteed that the exercises will make no sense. 'Nuff\n said. *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n perhaps a little less familiar than standard natural number\n induction, but the basic idea is equally simple. Each [Inductive]\n declaration defines a set of data values that can be built up from\n the declared constructors: a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to a number; a\n list can be either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two things together establish the\n truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist, \n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3). \nProof.\n intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons n l1' *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n [as...] clause provided to the [induction] tactic gives a name to\n the induction hypothesis corresponding to the smaller list [l1']\n in the [cons] case. Once again, this Coq proof is not especially\n illuminating as a static written document -- it is easy to see\n what's going on if you are reading the proof in an interactive Coq\n session and you can see the current goal and context at each\n point, but this state is not visible in the written-down parts of\n the Coq proof. So a natural-language proof -- one written for\n human readers -- will need to include more explicit signposts; in\n particular, it will help the reader stay oriented if we remind\n them exactly what the induction hypothesis is in the second case.\n *)\n\n(** *** Informal version *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3], \n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n (the induction hypothesis). We must show\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]] \n By the definition of [++], this follows from\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n which is immediate from the induction hypothesis. []\n*)\n\n(** *** Reversing a list *)\n(** For a slightly more involved example of an inductive proof\n over lists, suppose we use [app] to define a list-reversing\n function [rev] like this: *)\n\nFixpoint rev (l:natlist) : natlist := \n match l with\n | nil => nil\n | h :: t => rev t ++ [h]\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** *** Proofs about reverse *)\n\n(** Now let's prove some theorems about our newly defined [rev].\n For something a little more challenging than the inductive proofs\n we've seen so far, let's prove that reversing a list does not\n change its length. Our first attempt at this proof gets stuck in\n the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = [] *)\n reflexivity.\n - (* l = n :: l' *)\n (* This is the tricky case. Let's begin as usual \n by simplifying. *)\n simpl. \n (* Now we seem to be stuck: the goal is an equality \n involving [++], but we don't have any useful equations \n in either the immediate context or in the global \n environment! \n\n We can make a little progress by using the IH to \n rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n would have enabled us to make progress and prove it as a separate\n lemma.\n*)\n\nTheorem app_length : forall l1 l2 : natlist, \n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Note that we make the lemma as _general_ as possible: in\n particular, we quantify over _all_ [natlist]s, not just those that\n result from an application of [rev]. This should seem natural,\n because the truth of the goal clearly doesn't depend on the list\n having been reversed. Moreover, it is much easier to prove the\n more general property. *)\n \n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons *)\n simpl. rewrite -> app_length. rewrite -> plus_comm.\n rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems: \n\n _Theorem_: For all lists [l1] and [l2],\n [length (l1 ++ l2) = length l1 + length l2].\n \n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n length ([] ++ l2) = length [] + length l2,\n which follows directly from the definitions of\n [length] and [++].\n\n - Next, suppose [l1 = n::l1'], with\n length (l1' ++ l2) = length l1' + length l2.\n We must show\n length ((n::l1') ++ l2) = length (n::l1') + length l2).\n This follows directly from the definitions of [length] and [++]\n together with the induction hypothesis. [] *)\n \n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n \n _Proof_: By induction on [l]. \n\n - First, suppose [l = []]. We must show\n length (rev []) = length [],\n which follows directly from the definitions of [length] \n and [rev].\n \n - Next, suppose [l = n::l'], with\n length (rev l') = length l'.\n We must show\n length (rev (n :: l')) = length (n :: l').\n By the definition of [rev], this follows from\n length ((rev l') ++ [n]) = S (length l')\n which, by the previous lemma, is the same as\n length (rev l') + length [n] = S (length l').\n This follows directly from the induction hypothesis and the\n definition of [length]. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n and pedantic. After the first few, we might find it easier to\n follow proofs that give fewer details (since we can easily work\n them out in our own minds or on scratch paper if necessary) and\n just highlight the non-obvious steps. In this more compressed\n style, the above proof might look more like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that\n length (l ++ [n]) = S (length l)\n for any [l] (this follows by a straightforward induction on [l]).\n The main property now follows by induction on [l], using the\n observation together with the induction hypothesis in the case\n where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for our\n present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, using [rewrite], and later we will see other ways\n of reusing previous theorems. But in order to refer to a theorem,\n we need to know its name, and remembering the names of all the\n theorems we might ever want to use can become quite difficult! It\n is often hard even to remember what theorems have been proven,\n much less what they are named.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following to\n see a list of theorems that we have proved about [rev]: *)\n\n(* SearchAbout rev. *)\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the book; it can save you a lot of time! \n\n If you are using ProofGeneral, you can run [SearchAbout] with [C-c\n C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_r : forall l : natlist, \n l ++ [] = l. \nProof.\n intros l.\n induction l.\n -simpl. reflexivity.\n -simpl. rewrite->IHl. reflexivity.\nQed.\n\nTheorem rev_cons: forall l:natlist, forall n:nat,\n rev(l ++ [n]) = cons n (rev l).\nProof.\n intros l n.\n induction l.\n -simpl. reflexivity.\n -simpl. rewrite -> IHl. simpl. reflexivity.\nQed. \n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros l.\n induction l.\n -simpl. reflexivity.\n -simpl. rewrite -> rev_cons. rewrite -> IHl. reflexivity.\nQed.\n \n(** There is a short solution to the next exercise. If you find\n yourself getting tangled up, step back and try to look for a\n simpler way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros l1 l2 l3 l4.\n rewrite -> app_assoc. rewrite -> app_assoc. reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros l1 l2.\n induction l1.\n -simpl. reflexivity.\n -destruct n. \n +simpl. rewrite -> IHl1. reflexivity.\n +simpl. rewrite -> IHl1. reflexivity.\nQed. \n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n match l1 with\n | nil => match l2 with\n | nil => true\n | _ => false\n end\n | h1 :: t1 => match l2 with\n | nil => false\n | h2 :: t2 =>andb (beq_nat h1 h2) (beq_natlist t1 t2)\n end\nend. \n\nExample test_beq_natlist1 :\n (beq_natlist nil nil = true).\n Proof. reflexivity. Qed.\n\nExample test_beq_natlist2 :\n beq_natlist [1;2;3] [1;2;3] = true.\n Proof. reflexivity. Qed.\n\nExample test_beq_natlist3 :\n beq_natlist [1;2;3] [1;2;4] = false.\n Proof. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\n intros l.\n induction l.\n -simpl. reflexivity.\n - simpl. rewrite <-IHl. SearchAbout beq_nat. rewrite <- beq_nat_refl. reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n definitions about bags earlier in the file. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n leb 1 (count 1 (1 :: s)) = true.\nProof.\n intros s.\n simpl. reflexivity.\nQed.\n\n(** The following lemma about [leb] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n leb n (S n) = true.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* 0 *) \n simpl. reflexivity.\n - (* S n' *)\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n intros s.\n induction s.\n -simpl. reflexivity.\n -destruct n.\n +simpl. rewrite -> ble_n_Sn. reflexivity.\n +simpl. rewrite -> IHs. reflexivity.\nQed. \n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *) \n(** Write down an interesting theorem [bag_count_sum] about bags \n involving the functions [count] and [sum], and prove it.*)\n\n\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nThere is a hard way and an easy way to solve this exercise.\n*)\n\nTheorem rev_injective: forall (l1 l2 : natlist), \n rev l1 = rev l2 -> l1 = l2.\nProof.\n intros l1 l2.\n intros H.\n rewrite <- rev_involutive. rewrite <- H. rewrite-> rev_involutive. reflexivity.\nQed.\n(* FILL IN HERE *)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n\n(** Suppose we want to write a function that returns the [n]th\n element of some list. If we give it type [nat -> natlist -> nat],\n then we'll have to return some number when the list is too short!\n *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with \n | true => a \n | false => nth_bad l' (pred n)\n end\n end.\n\n(** This solution is far from optimal: If [nth_bad] returns\n [42], we can't tell whether that value actually appears on the\n input without further processing. A better alternative is to\n change the return type of [nth_bad] to include an error value as a\n possible outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption. \n\n(** We can then change the above definition of [nth_bad] to\n return [None] when the list is too short and [Some a] when the\n list has enough members and [a] appears at position [n]. We call\n this new function [nth_error] to indicate that it may result in an\n error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None \n | a :: l' => match beq_nat n O with \n | true => Some a\n | false => nth_error l' (pred n)\n end\n end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n small feature of Coq's programming language: conditional\n expressions... *)\n\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None \n | a :: l' => if beq_nat n O then Some a\n else nth_error' l' (pred n)\n end.\n\nFixpoint qe_zero(n:nat): bool:=\n if n then false else true.\n\nCompute qe_zero(0).\nCompute qe_zero(1).\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_error) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_error (l : natlist) : natoption :=\n match l with\n | nil => None\n | h :: t => Some h\nend.\n\nExample test_hd_error1 : hd_error [] = None.\n Proof. reflexivity. Qed. \n\nExample test_hd_error2 : hd_error [1] = Some 1.\n Proof. reflexivity. Qed. \n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\n Proof. reflexivity. Qed. \n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_error l).\nProof.\n intros l default.\n destruct l.\n - (*l = []*)reflexivity.\n - (*l = n::l *)simpl. reflexivity.\nQed.\n(** [] *)\n\nEnd NatList.\n\n(* ###################################################### *)\n(** * Partial Maps *)\n\n(** As a final illustration of how fundamental data structures can be\n defined in Coq, here is a simple _partial map_ data type,\n analogous to the \"dictionary\" data structures found in most\n programming languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n | Id : nat -> id.\n\n(** Internally, an [id] is just a number. Introducing a separate type\n that is \"isomorphic\" to [nat] but not interchangeable with it\n makes things more readable and gives us the flexibility to change\n representations later if we wish. \n\n We'll also need an equality test for [id]s: *)\n\nDefinition beq_id x1 x2 :=\n match x1, x2 with\n | Id n1, Id n2 => beq_nat n1 n2\n end.\n\n(** **** Exercise: 1 star (beq_id_refl) *)\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n intros x.\n destruct x. simpl. \n rewrite <- beq_nat_refl.\n reflexivity.\nQed.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nImport NatList.\n \nInductive partial_map : Type :=\n | empty : partial_map \n | record : id -> nat -> partial_map -> partial_map. \n\n(** This declaration can be read: \"There are two ways to construct a\n [partial_map]: either using the constructor [empty] to represent an\n empty partial map, or by applying the constructor [record] to\n a key, a value, and an existing [partial_map] to construct a\n [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n partial map (or adds a new entry if the given key is not already\n present). *)\nCheck empty.\nCheck record (Id 0) 5 empty.\nCheck record (Id 0) 6 ( record (Id 1) 5 empty ) .\nCheck record (Id 1) 6 ( record (Id 1) 5 empty ) .\n\nDefinition update (d : partial_map)\n (key : id) (value : nat)\n : partial_map :=\n record key value d.\n\nCheck update (record (Id 1) 5 empty) (Id 1) 6.\n\n(** Here is a function [find] that searches a [partial_map] for a\n given key. It evaluates to [None] if the key was not found and\n [Some val] if the key was mapped to [val]. If the same key is\n mapped to multiple values, [find] will return the first one it\n finds. *)\n\nFixpoint find (key : id) (d : partial_map) : natoption := \n match d with \n | empty => None\n | record k v d' => if beq_id key k\n then Some v\n else find key d'\n end.\n\n\n(** **** Exercise: 1 star (update_eq) *)\nTheorem update_eq :\n forall (d : partial_map) (k : id) (v: nat),\n find k (update d k v) = Some v.\nProof.\n intros d k v.\n SearchAbout beq_nat.\n induction k.\n simpl. rewrite <- beq_nat_refl. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star (update_neq) *)\nTheorem update_neq :\n forall (d : partial_map) (m n : id) (o: nat),\n beq_id m n = false -> find m (update d n o) = find m d.\nProof.\n intros n m d o.\n intros H.\nsimpl.\n rewrite H.\nreflexivity.\nQed.\n(** [] *)\n\nEnd PartialMap.\n\n(** **** Exercise: 2 stars (baz_num_elts) *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n | Baz1 : baz -> baz\n | Baz2 : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have? \n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** $Date: 2016-01-05 08:55:01 -0500 (Tue, 05 Jan 2016) $ *)\n\n", "meta": {"author": "YuduDu", "repo": "Formal-Engineering-Method---coq", "sha": "8285e24c727b8becb5eee8bfb6d08b7ee059361d", "save_path": "github-repos/coq/YuduDu-Formal-Engineering-Method---coq", "path": "github-repos/coq/YuduDu-Formal-Engineering-Method---coq/Formal-Engineering-Method---coq-8285e24c727b8becb5eee8bfb6d08b7ee059361d/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202038, "lm_q2_score": 0.9343951661947456, "lm_q1q2_score": 0.8859510100302873}} {"text": "\nRequire Import Arith.\n\nFixpoint fib (n:nat) : nat :=\n match n with\n | O => 1\n | S O => 1\n | S (S p as q) => fib p + fib q\n end.\n\n\nEval compute in (fib 10).\n\n\nLemma fib_SSn : forall n:nat, fib (S (S n)) = fib n + fib (S n).\nProof.\n simpl; auto.\nQed.\n\n\n\n(* This function computes the pair (fib n, fib (S n)) *)\n\nFixpoint fib_pair (n:nat) : nat * nat :=\n match n with\n | O => (1, 1)\n | S p => match fib_pair p with\n | (x, y) => (y, x + y)\n end\n end.\n\nDefinition linear_fib (n:nat) := fst (fib_pair n).\n\n\nLemma fib_pair_correct : forall n:nat, fib_pair n = (fib n, fib (S n)).\nProof.\n intro n; elim n; simpl.\n auto.\n intros n0 Hrec; rewrite Hrec; auto.\nQed.\n\nTheorem linear_fib_correct : forall n:nat, linear_fib n = fib n.\nProof. \n unfold linear_fib; intro n; rewrite fib_pair_correct; simpl; auto.\nQed.\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/progav/SRC/fib_intro1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.9263037363973295, "lm_q1q2_score": 0.8855290942347396}} {"text": "Require Import Setoid.\nRequire Import Psatz.\n\n(* https://people.cs.umass.edu/~arjun/courses/cs691pl-spring2014/assignments/groups.html *)\nModule Type Group.\n\n (* The set of the group. *)\n Parameter G : Type.\n\n (* The binary operator. *)\n Parameter f : G -> G -> G.\n \n (* The group identity. *)\n Parameter e : G.\n\n (* The inverse operator. *)\n Parameter inv : G -> G.\n\n (* For readability, we use infix <+> to stand for the binary operator. *)\n Infix \"<+>\" := f (at level 50, left associativity).\n\n (* The operator [f] is associative. *)\n Axiom assoc : forall a b c, a <+> b <+> c = a <+> (b <+> c).\n\n (* [e] is the right-identity for all elements [a] *)\n Axiom id_r : forall a, a <+> e = a.\n\n (* [i a] is the right-inverse of [a]. *)\n Axiom inv_r : forall a, a <+> inv a = e.\n\n (* Your task is to use the definitions above to prove all the theorems below: *)\n\n (* The identity [e] is unique. *)\n Lemma unique_id : forall a, a <+> a = a -> a = e.\n Proof.\n intros a H.\n rewrite <- (id_r a).\n rewrite <- (inv_r a).\n rewrite <- assoc.\n rewrite H. auto.\n Qed.\n \n \n (* [i a] is the left-inverse of [a]. *)\n Lemma inv_l : forall a, inv a <+> a = e.\n Proof.\n intros a.\n apply unique_id.\n rewrite assoc.\n assert ((a <+> (inv a <+> a)) = a <+> inv a <+> a).\n rewrite assoc. auto.\n rewrite H. rewrite (inv_r a).\n rewrite <- assoc.\n rewrite (id_r (inv a)). auto.\n Qed.\n \n \n (* [e] is the left-identity. *)\n Lemma id_l : forall a, e <+> a = a.\n Proof.\n intros a.\n rewrite <- (inv_r a).\n rewrite assoc. rewrite inv_l.\n rewrite id_r. auto.\n Qed.\n \n\n \n (* [x] can be cancelled on the right. *)\n Lemma cancel_r : forall a b x, a <+> x = b <+> x -> a = b. \n Proof.\n intros a b x H. \n rewrite <- (id_r a), <- (id_r b).\n rewrite <- (inv_r x).\n rewrite <- assoc, <- assoc.\n rewrite H. auto.\n Qed.\n \n \n (* [x] can be cancelled on the left. *)\n Lemma cancel_l: forall a b x, x <+> a = x <+> b -> a = b.\n Proof.\n intros a b x H.\n rewrite <- (id_l a), <- (id_l b).\n rewrite <- (inv_l x).\n rewrite assoc.\n rewrite H. rewrite assoc.\n auto.\n Qed.\n \n \n (* The left identity is unique. *)\n Lemma e_uniq_l : forall a p, p <+> a = a -> p = e.\n Proof.\n intros a p H.\n rewrite <- (id_r p).\n rewrite <- (inv_r a) at 1.\n rewrite <- (inv_r a).\n rewrite <- assoc. rewrite H.\n auto.\n Qed.\n \n (* The left inverse is unique. *)\n Lemma inv_uniq_l : forall a b, a <+> b = e -> a = inv b.\n Proof.\n intros a b H.\n rewrite <- (inv_l b) in H.\n apply cancel_r in H.\n auto. \n Qed.\n \n \n (* The left identity is unique. *)\n Lemma e_uniq_r : forall a p, a <+> p = a -> p = e.\n Proof.\n intros a p H.\n rewrite <- (id_l p).\n rewrite <- (inv_l a) at 1.\n rewrite assoc. rewrite H.\n rewrite (inv_l a). auto.\n Qed.\n \n \n (* The right inverse is unique. *)\n Lemma inv_uniq_r : forall a b, a <+> b = e -> b = inv a.\n Proof. \n intros a b H.\n rewrite <- (id_l b).\n rewrite <- (inv_l a) at 1.\n rewrite assoc. rewrite H.\n rewrite id_r. auto.\n Qed.\n \n \n (* The inverse operator distributes over the group operator. *)\n Lemma inv_distr : forall a b, inv (a <+> b) = inv b <+> inv a.\n Proof.\n intros a b. symmetry. \n apply inv_uniq_l.\n rewrite <- assoc.\n rewrite (assoc (inv b) (inv a) a).\n rewrite (inv_l a).\n rewrite (assoc (inv b) e b).\n rewrite (id_l b).\n rewrite (inv_l b). auto.\n Qed.\n \n \n (* The inverse of an inverse produces the original element. *)\n Lemma double_inv : forall a, inv (inv a) = a.\n Proof.\n intro a. symmetry.\n apply inv_uniq_r.\n rewrite (inv_l a). auto.\n Qed.\n \n (* The identity is its own inverse. *)\n Lemma id_inv : inv e = e.\n Proof.\n symmetry.\n apply inv_uniq_r.\n rewrite (id_l e).\n auto.\n Qed.\n \nEnd Group.\n\nRequire Import Coq.ZArith.ZArith.\nModule Z_Add_Zero (Grp : Group).\n Open Scope Z.\n\n Export Grp.\n (* The set of the group. *)\n Definition G := Z.\n\n (* The binary operator. *)\n Definition f := Z.add.\n Infix \"<+>\" := f (at level 50, left associativity).\n \n (* The group identity. *)\n Definition e := 0.\n\n (* The inverse operator. *)\n Definition inv := Z.sub e.\n\n Lemma assoc : forall a b c, a <+> b <+> c = a <+> (b <+> c).\n Proof.\n intros a b c; rewrite Z.add_assoc.\n auto.\n Qed.\n\n Lemma id_r : forall a, a <+> e = a.\n Proof.\n unfold f, e; intro a;\n lia.\n Qed.\n \n Lemma inv_r : forall a, a <+> inv a = e.\n Proof.\n intro a; unfold f, inv, e; \n rewrite Z.add_opp_diag_r; auto.\n Qed.\n\nEnd Z_Add_Zero.\n", "meta": {"author": "mukeshtiwari", "repo": "CoqUtility", "sha": "3a25343d0a77177adb7530a08b0c7854bb1ed02f", "save_path": "github-repos/coq/mukeshtiwari-CoqUtility", "path": "github-repos/coq/mukeshtiwari-CoqUtility/CoqUtility-3a25343d0a77177adb7530a08b0c7854bb1ed02f/Group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993889, "lm_q2_score": 0.9263037262250327, "lm_q1q2_score": 0.8855290903186556}} {"text": "Require Import Arith.\n\n(* We first want to prove that our definition of add satisfies commutativity. *)\n\nFixpoint add n m := \n match n with 0 => m | S p => add p (S m) end.\n\nLemma addnS : forall n m, add n (S m) = S (add n m).\nProof.\n induction n.\n intros m; simpl.\n reflexivity.\n intros m; simpl.\n apply IHn.\nQed.\n\n(* Q1. Prove the following two theorems: beware that you will probably need\n addnS. *)\nLemma addn0 : forall n, add n 0 = n.\nProof.\n induction n;simpl;auto.\n rewrite addnS.\n rewrite IHn;trivial.\nQed.\n\nLemma add_comm : forall n m, add n m = add m n.\nProof.\n induction n;simpl.\n intro;rewrite addn0;auto.\n intros;rewrite addnS.\n rewrite IHn;trivial.\n rewrite addnS.\n trivial.\nQed.\n\n\n(* Q2. Now state and prove the associativity of this function. *)\n\nLemma plus_assoc : forall n m p, add n (add m p)= add (add n m) p.\nProof.\n induction n.\n simpl;auto.\n intros.\n simpl.\n repeat rewrite <- addnS.\n rewrite IHn.\n repeat rewrite addnS.\n simpl.\n rewrite addnS.\n trivial.\nQed.\n\n \n(* Q3. Now state and prove a theorem that expresses that this add function\n returns the same result as plain addition (given by function plus) *)\n\nLemma add_plus : forall n p, add n p = n+p.\nProof.\n induction n; simpl; auto.\n intro; rewrite addnS.\n rewrite IHn;trivial.\nQed.\n\n(* Note that the theorems about commutativity and associativity could be\n consequences of add_plus. *)\n\n(* Programs about lists. *)\nRequire Import List ZArith.\n\n(* We re-use the permutation defined in course C2. *)\n\nFixpoint multiplicity (n:Z)(l:list Z) : nat := \n match l with \n nil => 0%nat \n | a::l' => if Zeq_bool n a then S (multiplicity n l') else multiplicity n l' \n end. \n\nDefinition is_perm (l l':list Z) := \n forall n, multiplicity n l = multiplicity n l'.\n\n(* Q4. Show the following theorem: *)\n\nLemma multiplicity_app : forall x l1 l2, multiplicity x (l1++l2) =\n multiplicity x l1 + multiplicity x l2.\nProof.\n induction l1;simpl;auto.\n case (Zeq_bool x a).\n intros;rewrite IHl1.\n simpl;auto.\n intros;rewrite IHl1.\n simpl;auto.\nQed.\n\n\n(* Q5. State and prove a theorem that expresses that element counts are\n preserved by reverse. *)\nRequire Import ArithRing.\n\nLemma multiplicity_rev : forall x l, multiplicity x (rev l) = multiplicity x l.\nProof.\n induction l;simpl;auto.\n rewrite multiplicity_app.\n simpl.\n case (Zeq_bool x a).\n rewrite IHl;auto with arith.\n ring.\n rewrite IHl;ring.\nQed.\n\n(* --------------------------------------------*)\n(* The following questions are more advanced and can be kept for later. *)\n\n(* Q6. Show the following theorem. You will probably have an occasion\n to use the ring tactic *)\n\nLemma is_perm_transpose :\n forall x y l1 l2 l3, is_perm (l1++x::l2++y::l3) (l1++y::l2++x::l3).\nProof.\n intros;unfold is_perm;intros.\n replace (l1 ++ x :: l2 ++ y :: l3) with (l1 ++ (x::nil) ++ l2 ++ (y::nil)++l3).\n 2:simpl;auto.\n replace (l1 ++ y:: l2 ++ x :: l3) with (l1 ++ (y::nil) ++ l2 ++ (x::nil)++l3).\n 2:simpl;auto.\n repeat rewrite multiplicity_app.\n ring.\nQed.\n\n(* Q5 : What does this function do? *)\nFixpoint mask (A : Type)(m : list bool)(s : list A) {struct m} :=\n match m, s with\n | b :: m', x :: s' => if b then x :: mask A m' s' else mask A m' s'\n | _, _ => nil\n end.\n\nImplicit Arguments mask.\n\n(* Q6 Prove that : *)\nLemma mask_cat A m1 (s1 : list A) :\n length m1 = length s1 ->\n forall m2 s2, mask (m1 ++ m2) (s1 ++ s2) = mask m1 s1 ++ mask m2 s2.\nProof.\nintros Hm1 m2 s2. \nrevert s1 Hm1.\ninduction m1 as [|b1 m1 IHm]; intros [|x1 s1]; trivial. \n now intros H; inversion H.\n now intros H; inversion H.\nintros Hm1; injection Hm1; intros Hm1'; simpl.\nnow rewrite (IHm _ Hm1'); case b1.\nQed.\n\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Asian-Pacific Summer School/solutions/solutions/solutions4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611631680358, "lm_q2_score": 0.9219218380728936, "lm_q1q2_score": 0.8853779287616976}} {"text": "Require Import List.\nRequire Import Relations.\nRequire Import list.\n\n(* inductive predicate expressing the fact that two lists are obtained from\neach other, by the permutation of two consecutive elements *)\nInductive Transpose {A:Type} : list A -> list A -> Prop :=\n | transp_refl : forall (l: list A), Transpose l l\n | transp_pair : forall(x y:A), Transpose (x::y::nil) (y::x::nil)\n | transp_gen : forall (l m l1 l2 : list A), \n Transpose l m -> Transpose (l1++l++l2) (l1++m++l2).\n\n(* one common issue with this sort of definition is that constructors of the\ninductive predicates are akin to 'axioms', and it is very easy to define the\nwrong thing, or things that are inconsistent, or incomplete etc *)\n\n(* Here is another way to go about it *)\nDefinition Transpose' {A:Type} (l: list A) (m:list A) : Prop := \n l = m \\/ (exists (l1 l2:list A) (x y:A), \n l = l1++(x::y::nil)++l2 /\\ m = l1++(y::x::nil)++l2).\n\n(* Transpose' is a reflexive relation on list A *)\nLemma Transpose_refl': forall (A:Type), reflexive (list A) Transpose'.\nProof.\n intros A. unfold reflexive. intros l. unfold Transpose'. left. reflexivity.\nQed. \n\n(* ideally, you want to check the equivalence between Transpose and Transpose' *)\nLemma Transpose_check: forall (A:Type), \n same_relation (list A) Transpose Transpose'.\nProof.\n intros A. unfold same_relation. split. \n unfold inclusion.\n intros l m. intro H. generalize H. elim H.\n clear H l m. intros l H. clear H. apply Transpose_refl'.\n clear H l m. intros x y H. clear H. unfold Transpose'. right.\n exists nil, nil, x, y. split; reflexivity.\n clear H l m. intros l m l1 l2 H0 H1 H2. clear H2.\n cut (Transpose' l m). clear H0 H1. intro H. \n unfold Transpose' in H. elim H.\n clear H. intro H. rewrite H. apply Transpose_refl'.\n clear H. intro H. elim H. \n clear H. intros l3 H. elim H.\n clear H. intros l4 H. elim H.\n clear H. intros x H. elim H.\n clear H. intros y H. unfold Transpose'. right.\n exists (l1++l3), (l4++l2), x, y. elim H.\n clear H. intros H0 H1. split.\n rewrite H0. set (k:= x::y::nil).\n rewrite <- app_assoc, <- app_assoc, <- app_assoc. reflexivity.\n rewrite H1. set (k:= y::x::nil). \n rewrite <- app_assoc, <- app_assoc, <- app_assoc. reflexivity.\n apply H1. exact H0.\n unfold inclusion.\n intros l m H. unfold Transpose' in H. elim H. \n clear H. intro H. rewrite H. apply transp_refl.\n clear H. intro H. elim H. \n clear H. intros l1 H. elim H. \n clear H. intros l2 H. elim H.\n clear H. intros x H. elim H.\n clear H. intros y H. elim H.\n clear H. intros Hl Hm. rewrite Hl, Hm.\n apply transp_gen. apply transp_pair.\nQed.\n\n(* This version of the lemma can be handy for rewrites *)\nLemma Transpose_check': forall (A:Type) (l m: list A),\n Transpose l m <-> Transpose' l m.\nProof.\n intros A l m. split. \n intro H. apply Transpose_check. exact H.\n intro H. apply Transpose_check. exact H.\nQed.\n\n(* Transpose is a reflexive relation on list A *)\nLemma Transpose_refl: forall (A:Type), reflexive (list A) Transpose.\nProof.\n intros A. unfold reflexive. intros l. apply transp_refl.\nQed.\n\n(* Transpose is a symmetric relation on list A *)\nLemma Transpose_sym: forall (A:Type), symmetric (list A) Transpose.\nProof.\n intros A. unfold symmetric. intros l m H. generalize H. elim H. \n clear H l m. intros. apply transp_refl.\n clear H l m. intros. apply transp_pair.\n clear H l m. intros l m l1 l2 H0 H1 H2. clear H2. \n apply transp_gen. apply H1. exact H0.\nQed.\n\n(* Two lists which are transpositions of one another have same length *)\nLemma Transpose_imp_eq_length: forall (A:Type)(l m:list A),\n Transpose l m -> length l = length m.\nProof.\n intros A l m H. generalize H. elim H.\n clear H l m. intros. simpl. reflexivity. \n clear H l m. intros. simpl. reflexivity.\n clear H l m. intros l m l1 l2 H0 H1 H2. clear H2.\n rewrite app_length, app_length, app_length, app_length.\n rewrite H1. reflexivity. exact H0.\nQed.\n\nLemma Transpose_l_nil: forall (A:Type)(l:list A),\n Transpose l nil -> l = nil.\nProof.\n intros A l H. apply length_zero_iff_nil. \n apply Transpose_imp_eq_length with (m:=nil). exact H.\nQed.\n\nLemma Transpose_cons: forall (A:Type)(l m:list A)(a: A),\n Transpose l m -> Transpose (a::l) (a::m).\nProof.\n intros A l m a H. \n cut (a::l = (a::nil) ++ l ++ nil).\n cut (a::m = (a::nil) ++ m ++ nil).\n intros Hm Hl. rewrite Hm, Hl. apply transp_gen. exact H.\n rewrite <- app_comm_cons. rewrite app_nil_l. rewrite app_nil_r. reflexivity.\n rewrite <- app_comm_cons. rewrite app_nil_l. rewrite app_nil_r. reflexivity.\nQed.\n\nLemma Transpose_cons_reverse: forall (A:Type)(l m:list A)(a:A),\n Transpose (a::l) (a::m) -> Transpose l m.\nProof.\n intros A l m a.\n cut (forall (l' m':list A), \n l' = a::l -> m' = a::m -> Transpose l' m' -> Transpose l m). eauto.\n intros l' m' Hl Hm H. generalize H Hl Hm. \n clear Hl Hm. generalize l m a. clear l m a. elim H. \n clear H l' m'. intros k l m a H0 H1 H2. clear H0. \n rewrite H1 in H2. clear H1. injection H2. intros H0.\n rewrite H0. apply Transpose_refl.\n clear H l' m'. intros x y l m a H0 H1 H2. clear H0.\n injection H1. clear H1. injection H2. clear H2.\n intros H0 H1 H2 H3. \n rewrite H3 in H0. clear H3. rewrite H1 in H2. clear H1.\n rewrite H2 in H0. clear H2. rewrite H0. apply Transpose_refl.\n clear H l' m'. intros l m l1 l2 H0 H1 l' m' a H2 H3 H4.\n generalize (destruct_list l1). intro H5. elim H5.\n clear H5. intro H5. elim H5. clear H5. intros x H5. elim H5.\n clear H5. intros k1 H5. rewrite H5 in H3. rewrite H5 in H4.\n rewrite <- app_comm_cons in H3. rewrite <- app_comm_cons in H4.\n injection H3. injection H4. clear H3 H4 H5. intros H3 H4. clear H4.\n intros H4 H5. clear H5. rewrite <- H3, <- H4. clear H3 H4.\n apply transp_gen. exact H0.\n clear H5. intro H5. rewrite H5 in H3. rewrite H5 in H4.\n rewrite app_nil_l in H3. rewrite app_nil_l in H4. clear H2 H5.\n generalize (destruct_list l). generalize (destruct_list m).\n intros H5 H6. elim H5.\n clear H5. intro H5. elim H5. clear H5. intros b H5. elim H5.\n clear H5. clear l1. intros l1 H5. rewrite H5 in H4.\n rewrite <- app_comm_cons in H4. injection H4. clear H4.\n intro H4. intro H7. rewrite H7 in H5. clear H7 b. elim H6.\n clear H6. intro H6. elim H6. clear H6. intros b H6. elim H6.\n clear H6. intros k1 H6. rewrite H6 in H3.\n rewrite <- app_comm_cons in H3. injection H3. clear H3.\n intro H3. intro H7. rewrite H7 in H6. clear H7 b. \n rewrite <- app_nil_l with (l:=k1++l2) in H3. rewrite <- H3. \n rewrite <- app_nil_l with (l:=l1++l2) in H4. rewrite <- H4.\n apply transp_gen. apply H1 with (a:=a). exact H0. \n exact H6. exact H5.\n clear H6. intro H6. rewrite H6 in H0. apply Transpose_sym in H0.\n apply Transpose_l_nil in H0. rewrite H0 in H5. discriminate H5.\n clear H5. intro H5. rewrite H5 in H0. apply Transpose_l_nil in H0.\n rewrite H0 in H3. rewrite app_nil_l in H3.\n rewrite H5 in H4. rewrite app_nil_l in H4. rewrite H3 in H4. \n injection H4. clear H4. intro H4. rewrite H4. apply Transpose_refl.\nQed.\n\n\n(* This inductive predicate expresses the fact that two \nlists are permutation of one another *)\nInductive Permute {A:Type} : list A -> list A -> Prop :=\n | perm_refl : forall l:list A, Permute l l\n | perm_next : forall l l' m: list A, \n Permute l l' -> Transpose l' m -> Permute l m. \n\n\n(* Permute is a reflexive relation on list A *)\nLemma Permute_refl : forall (A:Type), reflexive (list A) Permute.\nProof.\n intros A. unfold reflexive. intros l. apply perm_refl.\nQed.\n\n(* As defined, the Permute relation is such that if l1 is\n a permutation of l2 and l2 is a transposition of l3, then\n l1 is deemed a permutation of l3. In order to prove that \n the Permute relation is symmetric, we need to be able to \n argue the other way around, namely that if l1 is a \n transposition of l2 and l2 is a permutation of l3, then\n l1 is also a permutation of l3. This result is obvious \n once we have established the symmetry of both Transpose\n and Permute, but we are not there yet. *)\nLemma Transpose_first: forall (A:Type) (l l' m:list A),\n Transpose l l' -> Permute l' m -> Permute l m.\nProof.\n intros A l l' m H0 H1. generalize H0. clear H0. generalize H1 l. \n elim H1. clear H1 l l' m. intros m. intro H. clear H. intro l.\n intro H. apply perm_next with (l':=l). apply perm_refl. exact H.\n clear H1 l l' m. intros l l' m H0 H1 H3 H4 k H5.\n eapply perm_next. apply H1. exact H0. exact H5. exact H3.\n (* dont understand why normal 'apply ... with' was failing *)\nQed.\n\n(* We are now in a position to prove the symmetry of Permute *)\nLemma Permute_sym: forall (A:Type), symmetric (list A) Permute.\nProof.\n intro A. unfold symmetric.\n intros l m H. generalize H. elim H. auto. clear H m l.\n intros l l' m H0 H1 H2 H3. apply Transpose_first with (l':=l').\n apply Transpose_sym. exact H2. apply H1. exact H0.\nQed.\n\n(* Permute is also a transitive relation on list A *)\nLemma Permute_trans: forall (A:Type), transitive (list A) Permute.\nProof.\n intros A. unfold transitive.\n intros l m k H. generalize H k. clear k. elim H. auto.\n clear H l m. intros l l' m H0 H1 H2 H3 k H4.\n apply H1. exact H0. apply Transpose_first with (l':=m).\n exact H2. exact H4.\nQed.\n\n\n(* Two lists which are permutation of one another have same length *)\nLemma Permute_imp_eq_length: forall (A:Type)(l m:list A),\n Permute l m -> length l = length m.\nProof.\n intros A l m H. generalize H. elim H.\n clear H l m. intros. reflexivity. \n clear H l m. intros l l' m H0 H1 H2 H3. clear H3. \n apply eq_trans with (y:=length l').\n apply H1. exact H0. apply Transpose_imp_eq_length. exact H2.\nQed.\n\nLemma Permute_cons: forall (A:Type)(l m: list A)(a: A),\n Permute l m -> Permute (a::l) (a::m).\nProof.\n intros A l m a H. generalize H. generalize a. clear a. elim H.\n clear H l m. intros. apply perm_refl.\n clear H l m. intros l l' m H0 H1 H2 a H3.\n apply (Permute_trans A (a::l) (a::l') (a::m)). apply H1. exact H0.\n apply (perm_next (a::l') (a::l') (a::m)). apply perm_refl.\n apply Transpose_cons. exact H2.\nQed.\n\n\nDefinition SubSet {A:Type}(l m:list A) : Prop :=\n forall (x:A), In x l -> In x m.\n\nDefinition EqSet {A:Type}(l m: list A) : Prop :=\n SubSet l m /\\ SubSet m l.\n\nLemma SubSet_refl: forall (A:Type), reflexive (list A) SubSet.\nProof.\n intros A. unfold reflexive. intro l. unfold SubSet. auto.\nQed.\n\nLemma SubSet_trans: forall (A: Type), transitive (list A) SubSet.\nProof.\n intros A. unfold transitive.\n intros l m k H0 H1. unfold SubSet. intros x H2.\n apply H1. apply H0. exact H2.\nQed.\n\n\nLemma Transpose_imp_SubSet: forall (A:Type), \n inclusion (list A) Transpose SubSet.\nProof.\n intros A. unfold inclusion.\n intros l m H. generalize H. elim H.\n clear H l m. intros. apply SubSet_refl.\n clear H l m. intros x y H0. clear H0. unfold SubSet.\n intros z H0. simpl. simpl in H0. elim H0.\n clear H0. intro H0. right. left. exact H0.\n clear H0. intro H0. elim H0. clear H0. intro H0. left. exact H0.\n apply False_ind.\n clear H l m. intros l m l1 l2 H0 H1 H2. clear H2. unfold SubSet.\n intros x H2. simpl. rewrite in_app_iff, in_app_iff.\n rewrite in_app_iff, in_app_iff in H2. elim H2.\n clear H2. intro H2. left. exact H2.\n clear H2. intro H2. elim H2. clear H2. intro H2. right. left.\n apply H1. exact H0. exact H2.\n clear H2. intro H2. right. right. exact H2.\nQed.\n\nLemma Transpose_imp_EqSet: forall (A:Type),\n inclusion (list A) Transpose EqSet.\nProof.\n intros A. unfold inclusion.\n intros l m H. unfold EqSet. split. \n apply Transpose_imp_SubSet. exact H.\n apply Transpose_imp_SubSet. apply Transpose_sym. exact H.\nQed.\n\nLemma Permute_imp_SubSet: forall (A:Type), \n inclusion (list A) Permute SubSet.\nProof.\n intros A. unfold inclusion.\n intros l m H. generalize H. elim H.\n clear H l m. intros. apply SubSet_refl.\n clear H l m. intros l l' m H0 H1 H2 H3. clear H3.\n apply (SubSet_trans A l l' m). apply H1. exact H0.\n apply Transpose_imp_SubSet. exact H2.\nQed.\n\nLemma Permute_imp_EqSet: forall (A:Type),\n inclusion (list A) Permute EqSet.\nProof.\n intros A. unfold inclusion.\n intros l m H. unfold EqSet. split.\n apply Permute_imp_SubSet. exact H.\n apply Permute_imp_SubSet. apply Permute_sym. exact H.\nQed.\n\n\nLemma Permute_cons_reverse: forall (A:Type)(l m:list A)(a:A),\n Permute (a::l) (a::m) -> Permute l m.\nProof.\n intros A l m a.\n cut (forall (l' m':list A), \n l' = a::l -> m' = a::m -> Permute l' m' -> Permute l m). eauto.\n intros l' m' Hl Hm H. generalize H Hl Hm.\n clear Hl Hm. generalize l m a. clear l m a. elim H.\n clear H l' m'. intros l m' m a H0 H1 H2. clear H0. \n rewrite H2 in H1. clear H2. injection H1. clear H1. \n intro H0. rewrite H0. apply perm_refl.\n clear H l' m'. intros l' k' m' H0 H1 H3 l m a H4 H5 H6.\n\n\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/permute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.9334308179739307, "lm_q1q2_score": 0.8828400546879321}} {"text": "Require Import Bool Arith ZArith List.\n\nImport ListNotations.\n\n(* EXAMPLES *) \n(* The following function takes two arguments a and b\nwhich are numbers of type nat and returns b + 2 * (a + b) *)\nDefinition f_ex (a b : nat) := b + 2 * (a + b).\n\n(* When p is a pair, you can access its components by the \"pattern-matching\"\n construct illustrated in the following function. *)\nDefinition add_pair_components (p : nat * nat) :=\n match p with (a, b) => a + b end.\n\n(* f_ex is a function with two arguments. add_pair_components is a\n function with one argument, which is a pair. *)\n\n(* END OF EXAMPLES *)\n\n(* 1/ Define a function that takes two numbers as arguments and returns\n the sum of the squares of these numbers. *)\nDefinition sumsq (a b : nat) := a * a + b * b.\n\n(* 2/ Define a function that takes 5 arguments a b c d e, which are all\n numbers and returns the sum of all these numbers. *)\nDefinition sum5 (a b c d e : nat) := a + b + c + d + e.\n\n(* 3/ Define a function named add5 that takes a number as argument and returns\n this number plus 5. *)\nDefinition add5 := Nat.add 5.\n\n(* The following should return 8 *)\nCompute add5 3.\n\n(* The following commands make it possible to find pre-defined functions\nSearch nat.\nSearch bool.\n *)\n\n(* 4/ Write a function swap of type list nat -> list nat such that\n swap (a::b::l) = (b::a::l) and\n swap l' = l' if l' has less than 2 elements. *)\nDefinition swap (ns : list nat) : list nat\n := match ns with\n | [] | [_] => ns\n | n1 :: n2 :: ns' => n2 :: n1 :: ns'\n end.\n\nTheorem swap_long (a b : nat) (l : list nat) : swap (a::b::l) = (b::a::l).\nProof. reflexivity. Qed.\n\nTheorem swap_short (ns : list nat) : length ns < 2 -> swap ns = ns.\nProof.\n intro H.\n destruct ns; try reflexivity.\n destruct ns; try reflexivity.\n repeat apply lt_S_n in H.\n now apply Nat.nlt_0_r in H.\nQed.\n\n(* 5/ Write a function proc2 of type list nat -> nat, such that\n proc2 (a::b::l) = (b + 3) and\n proc2 l' = 0 if l' has less than 2 elements.\n\n In other words, proc2 only processes the 2nd argument of the list and\n returns that number plus 3. If there is no second argument to the list,\n proc2 returns 0. *)\nDefinition proc2 (ns : list nat) : nat\n := match ns with\n | [] | [_] => 0\n | n1 :: n2 :: _ => n2 + 3\n end.\n\n(* 6/ Write a function ms of type list nat -> list nat such that\n ms (a::b::...::nil) = a+2::b+2::...::nil\n For instance\n ms (2::3::5::nil) = (4::5::7::nil) *)\nFixpoint ms (ns : list nat) : list nat\n := match ns with\n | [] => []\n | n :: ns' => (n + 2) :: (ms ns')\n end.\n\nExample ms_ex : ms (2::3::5::nil) = (4::5::7::nil).\nProof. reflexivity. Qed.\n\n(* 7/ Write a function sorted of type list nat -> bool, such that\n sorted l = true exactly when the natural numbers in\n l are in increasing order. *)\nDefinition sorted (ns : list nat) : bool\n := let fix iter (n : nat) (ns : list nat)\n := match ns with\n | [] => true\n | n' :: ns' => (n <=? n') && iter n' ns'\n end\n in match ns with\n | [] => true\n | n :: ns' => iter n ns'\n end.\n\nExample sorted_ex : sorted [1; 3; 3; 5] = true.\nProof. reflexivity. Qed.\n\nExample sorted_ex2 : sorted [1; 3; 2; 3; 5] = false.\nProof. reflexivity. Qed.\n\nInductive sorted_p : list nat -> Prop\n := sorted0 : sorted_p []\n | sorted1 (n : nat) : sorted_p [n]\n | sorted_n (n0 n1 : nat) (ns : list nat) :\n n0 <= n1\n -> sorted_p (n1 :: ns)\n -> sorted_p (n0 :: n1 :: ns).\n\nExample sorted_p_ex : sorted_p [1; 3; 3; 5].\nProof. auto using sorted_p with arith. Qed.\n\nExample sorted_p_ex2 : ~ sorted_p [1; 3; 2; 3; 5].\nProof.\n intro H. inversion H. inversion H4.\n now apply Nat.nle_succ_diag_l in H7.\nQed.\n\nTheorem iff_true_r (A : Prop) : A -> (A <-> True).\nProof. firstorder. Qed.\n\nTheorem iff_true_l (A : Prop) : A -> (True <-> A).\nProof. firstorder. Qed.\n\nTheorem proven_iff (A B : Prop) : A -> B -> (A <-> B).\nProof. firstorder. Qed.\n\nTheorem sorted_correct (ns : list nat) : sorted ns = true <-> sorted_p ns.\nProof.\n induction ns as [| n0 ns0 IH]; try destruct ns0 as [| n1 ns1];\n try ( apply proven_iff; try reflexivity; constructor ).\n split; intro H; inversion H.\n - apply andb_prop in H1 as [H1 H2].\n apply Nat.leb_le in H1 as H1'.\n apply sorted_n; try assumption.\n apply IH. assumption.\n - subst n2 n3 ns. apply Nat.leb_le in H2 as H2'.\n assert (sorted (n1 :: ns1) = true) as Hs.\n { apply IH. assumption. }\n simpl. apply andb_true_intro; split; assumption.\nQed.\n\n(* 8/ Write a function p2 of type nat -> nat such that\n p2 n = 2 ^ n *)\nFixpoint p2 (n : nat) : nat\n := match n with\n | O => 1\n | S n' => 2 * (p2 n')\n end.\n\nExample p2_ex : p2 3 = 8.\nProof. reflexivity. Qed.\n\nTheorem p2_correct (n : nat) : Nat.pow 2 n = p2 n.\nProof.\n induction n as [| n' IH]; try reflexivity.\n simpl. rewrite <- IH. ring.\nQed.\n\n(* 9/ Write a function salt of type nat -> nat -> nat such that\n salt x n = x^n - x^(n-1) + x^(n-2) .... + 1 or -1, if x <> 0,\n depending on the parity of n, thus\n salt x 3 = x^3 - x^2 + x - 1\n salt x 4 = x^4 - x^3 + x^2 - x + 1\n salt 2 3 = 5\n\n You may have to define auxiliary functions. *)\nFixpoint salt0 (x n : nat) : nat\n := match n with\n | O => 1\n | S n' => x^n - (salt0 x n')\n end.\nExample salt0_is_wrong_ex : salt0 0 2 <> 1.\nProof. simpl. apply O_S. Qed.\n\nFixpoint salt (x n : nat) : nat\n := match n with\n | O => 1\n | 1 => x - 1\n | S (S n') => x^n - x^(S n') + (salt x n')\n end.\n\nExample salt_ex1 (x : nat) : salt x 3 = x^3 - x^2 + x - 1.\nProof.\n cbv beta delta [salt] iota.\n pose (gt_0_eq x) as H.\n destruct H as [neq | eq]; try ( subst x; reflexivity ).\n apply gt_le_S in neq.\n rewrite Nat.add_sub_assoc; try assumption.\n reflexivity.\nQed.\n\nExample salt_ex2 (x : nat) : salt x 4 = x^4 - x^3 + x^2 - x + 1.\nProof.\n cbv beta delta [salt] iota.\n pose (gt_0_eq x) as H.\n destruct H as [neq | eq]; try ( subst x; reflexivity ).\n rewrite Nat.add_assoc. rewrite Nat.pow_1_r.\n rewrite Nat.add_sub_assoc; try reflexivity.\n rewrite Nat.pow_2_r. rewrite <- Nat.mul_1_l at 1.\n apply Nat.mul_le_mono_r. apply gt_le_S. assumption.\nQed.\n\nExample salt_ex3 : salt 2 3 = 5.\nProof. reflexivity. Qed.\n\nFixpoint salt2_aux (x m acc : nat) (p : bool) : nat\n := match m with\n | O => if p then acc + 1 else acc - 1\n | S m' => let s := x^m in\n let acc' := if p then (acc + s) else (acc - s)\n in salt2_aux x m' acc' (negb p)\n end.\n\nDefinition salt2 (x n : nat) : nat\n := salt2_aux x n 0 true.\n\nExample salt2_ex1 (x : nat) : salt2 x 3 = x^3 - x^2 + x - 1.\nProof.\n unfold salt2. simpl. rewrite Nat.mul_1_r. reflexivity.\nQed.\n\nExample salt2_ex2 (x : nat) : salt2 x 4 = x^4 - x^3 + x^2 - x + 1.\nProof.\n unfold salt2. simpl. rewrite Nat.mul_1_r. reflexivity.\nQed.\n\nExample salt2_ex3 : salt2 2 3 = 5.\nProof. reflexivity. Qed.\n\nDefinition salt_eq (x n : nat) := salt x n = salt2 x n.\nDefinition salt2_aux_eq (x m : nat)\n := forall acc : nat,\n salt2_aux x m acc true = acc + salt2_aux x m 0 true.\n\nLemma salt2_aux_acc_lem (x m : nat)\n : 0 < x\n -> (forall m' : nat, m' < m -> salt2_aux_eq x m')\n -> salt2_aux_eq x m.\nProof.\n intros xneq IH.\n destruct m as [| m0]; unfold salt2_aux_eq; try reflexivity.\n intro acc. simpl.\n destruct m0 as [| m1].\n - simpl. repeat rewrite Nat.mul_1_r.\n rewrite Nat.add_sub_assoc; try reflexivity.\n apply lt_le_S. assumption.\n - simpl. rewrite IH; try auto with arith.\n symmetry. rewrite IH; try auto with arith.\n rewrite Nat.add_assoc, Nat.add_sub_assoc; try reflexivity.\n apply Nat.mul_le_mono_l. rewrite <- Nat.mul_1_l at 1.\n apply Nat.mul_le_mono_r. apply lt_le_S. assumption.\nQed.\n\nLemma salt2_aux_acc (x m : nat) : 0 < x -> salt2_aux_eq x m.\nProof.\n intro xneq. apply (lt_wf_ind m (salt2_aux_eq x)).\n intros m' H. apply salt2_aux_acc_lem; assumption.\nQed.\n\nLemma salt2_SS (x n : nat)\n : 0 < x -> salt2 x (S (S n)) = x^(S (S n)) - x^(S n) + salt2 x n.\nProof.\n intro xneq. unfold salt2. simpl.\n rewrite salt2_aux_acc; try assumption.\n reflexivity.\nQed.\n\nLemma salt_eq_lem (x n : nat)\n : (forall m, m < n -> salt_eq x m) -> salt_eq x n.\nProof.\n intro IH.\n destruct n as [| n0]; try reflexivity.\n destruct n0 as [| n1].\n - unfold salt_eq, salt2. simpl. auto with arith.\n - unfold salt_eq.\n pose (zerop x) as Hx. destruct Hx as [eq | neq].\n + (* x = 0 *) subst x. unfold salt2. simpl.\n apply IH. auto with arith.\n + (* 0 < x *)\n replace (salt x (S (S n1)))\n with (x^(S (S n1)) - x^(S n1) + salt x n1);\n try reflexivity.\n replace (salt2 x (S (S n1)))\n with (x^(S (S n1)) - x^(S n1) + salt2 x n1).\n * rewrite Nat.add_cancel_l. apply IH.\n auto with arith.\n * unfold salt2. simpl.\n symmetry. rewrite salt2_aux_acc; try assumption.\n reflexivity.\nQed.\n\nTheorem salt_is_salt2 (x n : nat) : salt_eq x n.\nProof.\n apply (lt_wf_ind n (salt_eq x)).\n apply (salt_eq_lem x).\nQed.\n\n(* 10/ Consider the following definition *)\n\nInductive btree : Type\n := leaf | bnode (n : nat) (t1 t2 : btree).\n\n(* write a function that list the labels of a tree by infix order *)\n(** you may use the concatenation function app on lists\n (also written l1 ++ l2 ) *)\n\nFixpoint list_btns (t : btree) : list nat\n := match t with\n | leaf => []\n | bnode n t1 t2 => list_btns t1 ++ (n :: list_btns t2)\n end.\n\nExample btree_ex\n := let t3 := bnode 3 (bnode 4 leaf leaf) leaf\n in let t5 := bnode 5 leaf (bnode 6 leaf leaf)\n in let t2 := bnode 2 t3 t5\n in bnode 1 leaf t2.\nExample list_btns_ex : list_btns btree_ex = [1; 4; 3; 2; 5; 6].\nProof. unfold btree_ex. reflexivity. Qed.\n\n(* write a boolean function that checks whether a tree is a binary\nsearch tree *)\nFixpoint rightmost (t : btree) : option nat\n := match t with\n | leaf => None\n | bnode n _ leaf => Some n\n | bnode n _ t2 => rightmost t2\n end.\n\nLemma rightmost_is_none_on_leaf_only (t : btree)\n : rightmost t = None <-> t = leaf.\nProof.\n induction t as [| n t1 _ t2 IH]; try easy.\n simpl. destruct t2 as [| n2 t21 t22]; try easy.\n rewrite IH. easy.\nQed.\n\nFixpoint leftmost (t : btree) : option nat\n := match t with\n | leaf => None\n | bnode n leaf _ => Some n\n | bnode n t1 _ => leftmost t1\n end.\n\nLemma leftmost_is_none_on_leaf_only (t : btree)\n : leftmost t = None <-> t = leaf.\nProof.\n induction t as [| n t1 IH t2 _]; try easy.\n simpl. destruct t1 as [| n1 t11 t12]; try easy.\n rewrite IH. easy.\nQed.\n\nFixpoint is_bst (t : btree) : bool\n := match t with\n | leaf => true\n | bnode n t1 t2 => is_bst t1 && is_bst t2\n && match rightmost t1 with\n | None => true\n | Some n1 => n1 true\n | Some n2 => n x\n end.\n\nDefinition snd (p : natprod) : nat :=\n match p with\n | pair x y => y\n end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs will be used heavily, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new pair notation can be used both in expressions and in\n pattern matches. *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n match p with\n | (x,y) => x\n end.\n\nDefinition snd' (p : natprod) : nat :=\n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n match p with\n | (x,y) => (y,x)\n end.\n\n(** Note that pattern-matching on a pair (with parentheses: [(x, y)])\n is not to be confused with the \"multiple pattern\" syntax\n (with no parentheses: [x, y]) that we have seen previously.\n\n The above examples illustrate pattern matching on a pair with\n elements [x] and [y], whereas [minus] below (taken from\n [Basics]) performs pattern matching on the values [n]\n and [m].\n\n Fixpoint minus (n m : nat) : nat :=\n match n, m with\n | O , _ => O why?\n | S _ , O => n or m ? \n | S n', S m' => minus n' m'\n end.\n\n The distinction is minor, but it is worth knowing that they\n are not the same. For instance, the following definitions are\n ill-formed:\n\n (* Can't match on a pair with multiple patterns: *)\n\n Definition bad_fst (p : natprod) : nat :=\n match p with\n | x, y => x missing paranthesis around x,y\n end.\n\n (* Can't match on multiple values with pair patterns: *)\n\n Definition bad_minus (n m : nat) : nat := \n match n, m with having unnecessary paranthesis\n | (O , _ ) => O\n | (S _ , O ) => n or m\n | (S n', S m') => bad_minus n' m'\n end.\n*)\n\n(** Let's try to prove a few simple facts about pairs.\n\n If we state things in a slightly peculiar way, we can complete\n proofs with just reflexivity (and its built-in simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** Notice that, unlike its behavior with [nat]s, where it\n generates two subgoals, [destruct] generates just one subgoal\n here. That's because [natprod]s can only be constructed in one\n way. *)\n\n(** **** Exercise: 1 star, standard (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n(** [] *)\n\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n type of _lists_ of numbers like this: \"A list is either the empty\n list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n | nil\n | cons (n : nat) (l : natlist).\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n declarations, but here is roughly what's going on in case you are\n interested. The [right associativity] annotation tells Coq how to\n parenthesize expressions involving multiple uses of [::] so that,\n for example, the next three declarations mean exactly the same\n thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\n\n Notation \"x + y\" := (plus x y)\n (at level 50, left associativity).\n\n the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than\n [1 + (2 :: [3])].\n\n (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n you read them in a [.v] file. The inner brackets, around 3, indicate\n a list, but the outer brackets, which are invisible in the HTML\n rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n part should be displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Since [app] will be used extensively in what follows, it is\n again convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head (With Default) and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first element (the\n \"tail\"). Since the empty list has no first element, we must pass\n a default value to be returned in that case. *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, standard, recommended (list_funs) \n\n Complete the definitions of [nonzeros], [oddmembers], and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n nil => nil\n |h::t => \n match h with\n | 0 => nonzeros (t)\n | _ => h :: nonzeros (t)\n end\n end.\n\nExample test_nonzeros:\n nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n Proof. reflexivity. Qed.\n\nFixpoint iseven (n:nat) : bool :=\n match n with \n | O => true\n | S O => false\n | S (S n') => iseven (n')\nend.\n\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n nil => nil\n |h::t => \n match iseven(h) with\n |true => oddmembers (t)\n |false => h :: oddmembers (t)\n end\n end.\n\nExample test_oddmembers:\n oddmembers [0;1;0;2;3;0;0] = [1;3].\n Proof. reflexivity. Qed.\n\nFixpoint countmembers (l:natlist) : nat :=\n match l with\n | [] => 0\n | h::t => 1 + countmembers(t)\n end.\n\n\nDefinition countoddmembers (l:natlist) : nat :=\n countmembers(oddmembers(l)).\n \nExample test_countoddmembers1:\n countoddmembers [1;0;3;1;4;5] = 4.\n Proof. reflexivity. Qed.\n\nExample test_countoddmembers2:\n countoddmembers [0;2;4] = 0.\n Proof. reflexivity. Qed.\n\nExample test_countoddmembers3:\n countoddmembers nil = 0.\n Proof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) \n\n Complete the definition of [alternate], which interleaves two\n lists into one, alternating between elements taken from the first\n list and elements from the second. See the tests below for more\n specific examples.\n\n (Note: one natural and elegant way of writing [alternate] will\n fail to satisfy Coq's requirement that all [Fixpoint] definitions\n be \"obviously terminating.\" If you find yourself in this rut,\n look for a slightly more verbose solution that considers elements\n of both lists at the same time. One possible solution involves\n defining a new kind of pairs, but this is not the only way.) *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l1 with\n | [] => l2\n | h1::t1 => match l2 with\n | [] => l1\n | h2::t2 => (app [h1;h2] (alternate t1 t2))\n end\n end.\n\nExample test_alternate1:\n alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n Proof. reflexivity. Qed.\n\nExample test_alternate2:\n alternate [1] [4;5;6] = [1;4;5;6].\n Proof. reflexivity. Qed.\n\nExample test_alternate3:\n alternate [1;2;3] [4] = [1;4;2;3].\n Proof. reflexivity. Qed.\n\nExample test_alternate4:\n alternate [] [20;30] = [20;30].\n Proof. reflexivity. Qed.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n can appear multiple times rather than just once. One possible\n representation for a bag of numbers is as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, standard, recommended (bag_functions) \n\n Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\n\n\nFixpoint count (v:nat) (s:bag) : nat :=\n match s with\n | [] => 0\n | h::t => match v =? h with\n | true => 1 + (count v t)\n | false => (count v t)\n end\n end.\n\n\n\n\n\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n the elements of [a] and of [b]. (Mathematicians usually define\n [union] on multisets a little bit differently -- using max instead\n of sum -- which is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag :=\n app.\n (* app: bag->bag->bag also works *)\n\n \n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\n Proof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag:= \n (app ([v]:bag) (s) :bag). \n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\n Proof. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\n Proof. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n match (count v s) =? 0 with\n | true => false\n | false => true\n end.\n\nExample test_member1: member 1 [1;4;1] = true.\n Proof. reflexivity. Qed.\n\nExample test_member2: member 2 [1;4;1] = false.\n Proof. reflexivity. Qed.\n(** [] *)\n\n\n\n(** **** Exercise: 2 stars, standard, recommended (bag_theorem) \n\n Write down an interesting theorem [bag_theorem] about bags\n involving the functions [count] and [add], and prove it. Note\n that, since this problem is somewhat open-ended, it's possible\n that you may come up with a theorem which is true, but whose proof\n requires techniques you haven't learned yet. Feel free to ask for\n help if you get stuck! *)\n\nPrint bin_to_nat.\n\nTheorem bag_theorem: forall v:nat, forall s:bag,\n count v (add v s) = 1 + (count v s).\n \n Proof.\n intros v s. induction s.\n -(* s = [] *) simpl. rewrite <- n_eqb_n. reflexivity.\n -(* s = s' *) simpl. rewrite <- n_eqb_n. reflexivity. \n Qed.\n \n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_bag_theorem : option (nat*string) := None.\n(* Note to instructors: For silly technical reasons, in this\n file (only) you will need to write [Some (Datatypes.pair 3 \"\"%string)]\n rather than [Some (3,\"\"%string)] to enter your grade and comments. \n\n [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As for numbers, simple facts about list-processing functions\n can sometimes be proved entirely by simplification. For example,\n the simplification performed by [reflexivity] is enough for this\n theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ...because the [[]] is substituted into the\n \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n the match) in the definition of [app], allowing the match itself\n to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons n l' *)\n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Micro-Sermon *)\n\n(** Simply _reading_ proof scripts will not get you very far! It is\n important to step through the details of each one using Coq and\n think about what each step achieves. Otherwise it is more or less\n guaranteed that the exercises will make no sense when you get to\n them. 'Nuff said. *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n little less familiar than standard natural number induction, but\n the idea is equally simple. Each [Inductive] declaration defines\n a set of data values that can be built up using the declared\n constructors: a boolean can be either [true] or [false]; a number\n can be either [O] or [S] applied to another number; a list can be\n either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two arguments together establish\n the truth of [P] for all lists [l]. Here's a concrete example: *)\n\n\n\n\n\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n intros l1 l2 l3. induction l1 as [| n l1' IHl1']. (* <---- WHAT? *)\n (* and if induction must\n be done on n+1, why n::l'\n *)\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons n l1' *)\n simpl. rewrite -> IHl1'. reflexivity. \nQed.\n\n\n\n\n\n\n(** Notice that, as when doing induction on natural numbers, the\n [as...] clause provided to the [induction] tactic gives a name to\n the induction hypothesis corresponding to the smaller list [l1']\n in the [cons] case. Once again, this Coq proof is not especially\n illuminating as a static document -- it is easy to see what's\n going on if you are reading the proof in an interactive Coq\n session and you can see the current goal and context at each\n point, but this state is not visible in the written-down parts of\n the Coq proof. So a natural-language proof -- one written for\n human readers -- will need to include more explicit signposts; in\n particular, it will help the reader stay oriented if we remind\n them exactly what the induction hypothesis is in the second\n case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n (the induction hypothesis). We must show\n\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n By the definition of [++], this follows from\n\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n which is immediate from the induction hypothesis. [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n lists, suppose we use [app] to define a list-reversing function\n [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => rev t ++ [h]\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Properties of [rev] *)\n\n(** Now, for something a bit more challenging than the proofs\n we've seen so far, let's prove that reversing a list does not\n change its length. Our first attempt gets stuck in the successor\n case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = [] *)\n reflexivity.\n - (* l = n :: l' *)\n (* This is the tricky case. Let's begin as usual\n by simplifying. *)\n simpl.\n (* Now we seem to be stuck: the goal is an equality\n involving [++], but we don't have any useful equations\n in either the immediate context or in the global\n environment! We can make a little progress by using\n the IH to rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n would have enabled us to make progress and state it as a separate\n lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons *)\n simpl. rewrite -> IHl1'. reflexivity. \nQed.\n\n(** Note that, to make the lemma (Theorem?) as general as possible, we\n quantify over _all_ [natlist]s, not just those that result from an\n application of [rev]. This should seem natural, because the truth\n of the goal clearly doesn't depend on the list having been\n reversed. Moreover, it is easier to prove the more general\n property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons *)\n simpl. rewrite -> app_length, plus_comm.\n simpl. rewrite -> IHl'. reflexivity.\nQed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n _Theorem_: For all lists [l1] and [l2],\n [length (l1 ++ l2) = length l1 + length l2].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n length ([] ++ l2) = length [] + length l2,\n\n which follows directly from the definitions of\n [length] and [++].\n\n\n\n (* need explanation ^^ *)\n\n\n\n - Next, suppose [l1 = n::l1'], with\n\n length (l1' ++ l2) = length l1' + length l2.\n\n We must show\n\n length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n This follows directly from the definitions of [length] and [++]\n together with the induction hypothesis. [] *)\n\n\n\n (* need explanation ^^ *)\n\n\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n\n length (rev []) = length [],\n\n which follows directly from the definitions of [length]\n and [rev].\n\n - Next, suppose [l = n::l'], with\n\n length (rev l') = length l'.\n\n We must show\n\n length (rev (n :: l')) = length (n :: l').\n\n By the definition of [rev], this follows from\n\n length ((rev l') ++ [n]) = S (length l')\n\n which, by the previous lemma (Theoram?), is the same as\n\n length (rev l') + length [n] = S (length l').\n\n This follows directly from the induction hypothesis and the\n definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic (concerned \nwith minor detals).\n After the first few, we might find it easier to follow proofs that\n give fewer details (which we can easily work out in our own minds or\n on scratch paper if necessary) and just highlight the non-obvious\n steps. In this more compressed style, the above proof might look\n like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n for any [l] (this follows by a straightforward induction on [l]).\n The main property again follows by induction on [l], using the\n observation together with the induction hypothesis in the case\n where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for our\n present purposes. *)\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, e.g., using [rewrite]. But in order to refer to a\n theorem, we need to know its name! Indeed, it is often hard even\n to remember what theorems have been proven, much less what they\n are called.\n\n Coq's [Search] command is quite helpful with this. Typing [Search\n foo] into your .v file and evaluating this line will cause Coq to\n display a list of all theorems involving [foo]. For example, try\n uncommenting the following line to see a list of theorems that we\n have proved about [rev]: *)\n\n\n(** Keep [Search] in mind as you do the following exercises and\n throughout the rest of the book; it can save you a lot of time!\n\n If you are using ProofGeneral, you can run [Search] with\n [C-c C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars, standard (list_exercises) \n\n More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n l ++ [] = l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l=[] *) simpl. reflexivity.\n - (* l = n::l' *) simpl. rewrite IHl'. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n rev (l1 ++ l2) = rev l2 ++ rev l1.\n\nProof.\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n -(* l1 = [] *) simpl. rewrite app_nil_r. reflexivity.\n -(* l1 = n :: l1'*) simpl. rewrite -> IHl1'. \n rewrite app_assoc. (* right associative by default*)\n reflexivity.\nQed.\n\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros l. induction l as [| n l' IHl']. \n - (*l=[]*) simpl. reflexivity.\n - (* l = n::l' *) simpl. rewrite rev_app_distr. rewrite IHl'. simpl. reflexivity.\nQed.\n\n(** There is a short solution to the next one. If you find yourself\n getting tangled up, step back and try to look for a simpler\n way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros l1 l2 l3 l4. induction l1 as [| n l1 IHl1'].\n - (* l1=[] *) simpl. rewrite app_assoc. reflexivity.\n - (* l1 = n::l1' *) simpl. rewrite IHl1'. reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\n\n\n\n(* ********************************************** *)\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros l1 l2. induction l1.\n - (* l1=[] *) simpl. reflexivity.\n - (* l1 = n::l1' *) simpl. rewrite IHl1.\n destruct n. \n -- (*n=0*)reflexivity. \n -- (* n = S n' *) simpl. reflexivity.\nQed.\n(* ********************************************** *)\n\n\n\n\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (eqblist) \n\n Fill in the definition of [eqblist], which compares\n lists of numbers for equality. Prove that [eqblist l l]\n yields [true] for every list [l]. *)\n\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n match l1 with\n | [] => match l2 with\n | [] => true\n | _ => false\n end\n | h::t => match l2 with\n | [] => false\n | h1 :: t1 => match h =? h1 with\n | true => (eqblist t t1)\n | false => false \n end\n end\n end.\n\nExample test_eqblist1 :\n (eqblist nil nil = true).\n Proof. reflexivity. Qed.\n\nExample test_eqblist2 :\n eqblist [1;2;3] [1;2;3] = true.\n Proof. reflexivity. Qed.\n\n\nExample test_eqblist3 :\n eqblist [1;2;3] [1;2;4] = false.\n Proof. reflexivity. Qed.\n\n\nTheorem eqblist_refl : forall l:natlist,\n true = eqblist l l.\nProof.\n intros l. \n induction l as [| n l' IHl'].\n - (* l = [] *) simpl. reflexivity.\n - (* l = n l' *) simpl. rewrite <- IHl'. rewrite <- n_eqb_n. reflexivity.\nQed.\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** Here are a couple of little theorems to prove about your\n definitions about bags above. *)\n\n(** **** Exercise: 1 star, standard (count_member_nonzero) *)\nTheorem count_member_nonzero : forall (s : bag),\n 1 <=? (count 1 (1 :: s)) = true.\nProof.\n intros s. induction s as [| n s' IHl'].\n - (* s=[] *) simpl. reflexivity.\n - (* s = h::t *) simpl. reflexivity.\n Qed.\n(** [] *)\n\n(** The following lemma about [leb] might help you in the next exercise. *)\n\nTheorem leb_n_Sn : forall n,\n n <=? (S n) = true.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* 0 *)\n simpl. reflexivity.\n - (* S n' *)\n simpl. rewrite IHn'. reflexivity. \nQed.\n\n(** Before doing the next exercise, make sure you've filled in the\n definition of [remove_one] above. *)\n(** **** Exercise: 3 stars, advanced (remove_does_not_increase_count) *)\n\n\n(** **** Exercise: 3 stars, standard, optional (bag_more_functions) \n\n Here are some more [bag] functions for you to practice with. *)\n\n(** When [remove_one] is applied to a bag without the number to\n remove, it should return the same bag unchanged. (This exercise\n is optional, but students following the advanced track will need\n to fill in the definition of [remove_one] for a later\n exercise.) *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n match s with\n | [] => []\n | h::t => match h =? v with\n | true => t\n | false => h :: (remove_one v t)\n end\n end.\n\nExample test_remove_one1:\n count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n Proof. reflexivity. Qed.\n\nExample test_remove_one2:\n count 5 (remove_one 5 [2;1;4;1]) = 0.\n Proof. reflexivity. Qed.\n\nExample test_remove_one3:\n count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n Proof. reflexivity. Qed.\n\nExample test_remove_one4:\n count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n Proof. reflexivity. Qed.\n\n\n\n\n (* ################################################################# \n\n\nTheorem remove_does_not_increase_count: forall (s : bag),\n (count 0 (remove_one 0 s)) <=? (count 0 s) = true.\nProof.\n intros s. induction s as [| n s' IHs'].\n - (* s = [] *) simpl. reflexivity. \n - (* s = n s' *) \nQed.\n \n\n ################################################################# *)\n\n(** [] *)\n\n\n(** **** Exercise: 4 stars, advanced (rev_injective) \n\n Prove that the [rev] function is injective -- that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\n (There is a hard way and an easy way to do this.) *)\n\n(* ################################################################# *) \n(* ###################### HELP ####################### *)\n \nTheorem rev_injective :\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nProof.\n intros. \n\n\n assert ( H1 : rev (rev l1) = rev (rev l2)).\n {f_equal. rewrite H. reflexivity. }\n\nrewrite rev_involutive in H1.\nrewrite rev_involutive in H1.\napply H1.\n\nQed.\n\n \n(* ################################################################# *)\n\n\n\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_rev_injective : option (nat*string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n element of some list. If we give it type [nat -> natlist -> nat],\n then we'll have to choose some number to return when the list is\n too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match n =? O with\n | true => a\n | false => nth_bad l' (pred n)\n end\n end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n can't tell whether that value actually appears on the input\n without further processing. A better alternative is to change the\n return type of [nth_bad] to include an error value as a possible\n outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n | Some (n : nat)\n | None.\n\n(** We can then change the above definition of [nth_bad] to\n return [None] when the list is too short and [Some a] when the\n list has enough members and [a] appears at position [n]. We call\n this new function [nth_error] to indicate that it may result in an\n error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => match n =? O with\n | true => Some a\n | false => nth_error l' (pred n)\n end\n end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n examples are elided. Click on a box if you want to see one.)\n\n This example is also an opportunity to introduce one more small\n feature of Coq's programming language: conditional\n expressions... *)\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => if n =? O then Some a\n else nth_error' l' (pred n)\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually supports conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars, standard (hd_error) \n\n Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_error (l : natlist) : natoption :=\n match l with\n |nil => None\n |h::t => Some h\n end.\n\nExample test_hd_error1 : hd_error [] = None.\n Proof. reflexivity. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\n Proof. reflexivity. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\n Proof. reflexivity. Qed.\n(** [] *)\n\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n Coq, here is a simple _partial map_ data type, analogous to the\n map or dictionary data structures found in most programming\n languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n | Id (n : nat).\n\n(** Internally, an [id] is just a number. Introducing a separate type\n by wrapping each nat with the tag [Id] makes definitions more\n readable and gives us the flexibility to change representations\n later if we wish. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition eqb_id (x1 x2 : id) :=\n match x1, x2 with\n | Id n1, Id n2 => n1 =? n2\n end.\n\n(** **** Exercise: 1 star, standard (eqb_id_refl) *)\nTheorem eqb_id_refl : forall x, true = eqb_id x x.\nProof.\n intros x. destruct x. simpl. rewrite <- n_eqb_n. reflexivity.\nQed.\n\n\n\n\n\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n \nInductive partial_map : Type :=\n | empty\n | record (i : id) (v : nat) (m : partial_map).\n\n(** This declaration can be read: \"There are two ways to construct a\n [partial_map]: either using the constructor [empty] to represent an\n empty partial map, or by applying the constructor [record] to\n a key, a value, and an existing [partial_map] to construct a\n [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n partial map by shadowing it with a new one (or simply adds a new\n entry if the given key is not already present). *)\n\nDefinition update (d : partial_map)\n (x : id) (value : nat)\n : partial_map :=\n record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n key. It returns [None] if the key was not found and [Some val] if\n the key was associated with [val]. If the same key is mapped to\n multiple values, [find] will return the first one it\n encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n match d with\n | empty => None\n | record y v d' => if eqb_id x y\n then Some v\n else find x d'\n end.\n\n(** **** Exercise: 1 star, standard (update_eq) *)\nTheorem update_eq :\n forall (d : partial_map) (x : id) (v: nat),\n find x (update d x v) = Some v.\nProof.\n intros. destruct x. simpl. rewrite <- n_eqb_n. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (update_neq) *)\nTheorem update_neq :\n forall (d : partial_map) (x y : id) (o: nat),\n eqb_id x y = false -> find x (update d y o) = find x d.\nProof.\n\nintros. unfold update. simpl. rewrite H. reflexivity.\nQed.\n\n\n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 stars, standard (baz_num_elts) \n\n Consider the following inductive definition: *)\n\nInductive baz : Type :=\n | Baz1 (x : baz)\n | Baz2 (y : baz) (b : bool).\n\n(** How _many_ elements does the type [baz] have? (Explain in words,\n in a comment.) type baz has infinitely many elements because each Baz2 can take \n a Baz2 as a passing argument *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_baz_num_elts : option (nat*string) := None.\n(** [] *)\n\n(* Wed Jan 9 12:02:44 EST 2019 *)\n", "meta": {"author": "Ryeca10", "repo": "Coq_uillage", "sha": "3db06269a26239272ae1f827b52132a59c728fdd", "save_path": "github-repos/coq/Ryeca10-Coq_uillage", "path": "github-repos/coq/Ryeca10-Coq_uillage/Coq_uillage-3db06269a26239272ae1f827b52132a59c728fdd/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541659378681, "lm_q2_score": 0.9372107962258134, "lm_q1q2_score": 0.8825284506279836}} {"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\n\nModule NatList. \n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as in this definition: *)\n\nInductive natprod : Type :=\n pair : nat -> nat -> natprod.\n\n(** Two numbers, nat -> nat, gives a natprod*)\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\n(** We can construct an element of [natprod] like this: *)\n\nCheck (pair 3 5).\nCheck pair.\nCheck pair 3.\n\n(** *** *)\n\n(** Here are two simple function definitions for extracting the\n first and second components of a pair. (The definitions also\n illustrate how to do pattern matching on two-argument\n constructors.) *)\n\nDefinition fst (p : natprod) : nat := \n match p with\n | pair x y => x\n end.\nDefinition snd (p : natprod) : nat := \n match p with\n | pair x y => y\n end.\n\nEval compute in (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** *** *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this notation is provided as part of the standard\n library): *)\n\nEval compute in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat := \n match p with\n | (x,y) => x\n end.\nDefinition snd' (p : natprod) : nat := \n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod := \n match p with\n | (x,y) => (y,x)\n end.\n\n(** *** *)\n\n(** Let's try and prove a few simple facts about pairs. If we\n state the lemmas in a particular (and slightly peculiar) way, we\n can prove them with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** Note that [reflexivity] is not enough if we state the lemma in a\n more natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** *** *)\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct].\n\n Notice that, unlike for [nat]s, [destruct] doesn't generate an\n extra subgoal here. That's because [natprod]s can only be\n constructed in one way. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\nintros p.\ndestruct p as [n m].\nsimpl.\nreflexivity.\nQed.\n\n\n\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\nintros p.\ndestruct p as [n m].\nsimpl.\nreflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n describe the type of _lists_ of numbers like this: \"A list is\n either the empty list or else a pair of a number and another\n list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n\n(** *** *)\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following two declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n but in case you are interested, here is roughly what's going on.\n\n The [right associativity] annotation tells Coq how to parenthesize\n expressions involving several uses of [::] so that, for example,\n the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\nNotation \"x + y\" := (plus x y) \n (at level 50, left associativity).\n The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (By the way, it's worth noting in passing that expressions like \"[1\n + 2 :: [3]]\" can be a little confusing when you read them in a .v\n file. The inner brackets, around 3, indicate a list, but the outer\n brackets, which are invisible in the HTML rendering, are there to\n instruct the \"coqdoc\" tool that the bracketed part should be\n displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(** *** Repeat *)\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist := \n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(** *** Length *)\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat := \n match l with\n | nil => O\n | h :: t => S(length t) (** Can also do length t +1 *)\n end.\n\n(** *** Append *)\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist := \n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y) \n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\"). \n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\n(** *** Head (with default) and Tail *)\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil \n | h :: t => t\n end.\n\nFixpoint lastele (l:natlist) : nat :=\nmatch l with\n|nil => O\n|h::nil => h\n|h :: t => lastele t\nend.\nExample test_last1: lastele [1;2;3] = 3.\nProof. reflexivity. Qed.\nExample test_last2: lastele [] = 0.\nProof. reflexivity. Qed.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\nmatch l with\n| nil => nil\n| h :: t => match h with\n | 0 => nonzeros(t)\n | _ => h :: nonzeros(t)\n end\nend.\n\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. simpl. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\nmatch l with\n| nil => nil\n| h :: t => if(oddb(h))\n then h :: oddmembers(t)\n else oddmembers(t)\nend.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\n Proof. simpl. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n match l with\n |nil => 0\n |h :: t => if oddb(h)\n then S (countoddmembers(t))\n else countoddmembers(t)\nend.\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\n Proof. simpl. reflexivity. Qed.\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\n Proof. simpl. reflexivity. Qed.\nExample test_countoddmembers3: countoddmembers nil = 0.\n Proof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\n\n(** Function definition that violates the decreasing arugument condition of coq.\n\nFixpoint alternate (l1:natlist) (l2 : natlist) : natlist :=\n match l1,l2 with\n |nil, nil => nil\n |nil, _ => l2\n |_, nil => l1\n |h1 :: t1, _ => h1 :: (alternate l2 t1)\nend.\n*)\n\nFixpoint alternate (l1:natlist) (l2 : natlist) : natlist :=\n match l1,l2 with\n |nil, nil => nil\n |nil, _ => l2\n |_, nil => l1\n |h1 :: t1, h2 :: t2 => h1 :: h2:: (alternate t1 t2)\nend.\n\nExample test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. simpl. reflexivity. Qed.\nExample test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].\nProof. simpl. reflexivity. Qed.\nExample test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].\nProof. simpl. reflexivity. Qed.\nExample test_alternate4: alternate [] [20;30] = [20;30].\nProof. simpl. reflexivity. Qed. \n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n multiple times instead of just once. One reasonable\n implementation of bags is to represent a bag of numbers as a\n list. *)\n\nDefinition bag := natlist. \n\n(** **** Exercise: 3 stars (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat := \n match s with\n |nil => 0\n |h :: t =>if (beq_nat v h)\n then S(count v t)\n else (count v t)\n end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. simpl. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. simpl. reflexivity. Qed. \n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := \n match s with\n | nil => v :: s\n | h :: t => v :: s\n end.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool := \n match (count v s) with\n | 0 => false\n | S n=> true\n end.\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. simpl. reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | h :: t => if (beq_nat h v)\n then t\n else h :: (remove_one v t)\n end.\n\nExample test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_one2: count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_one3: count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\nExample test_remove_one4: count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. simpl. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | h :: t => if (beq_nat h v)\n then (remove_all v t)\n else h :: (remove_all v t)\n end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. simpl. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n match s1 with\n |nil =>true\n |h :: t => if (member h s2)\n then (subset t (remove_one h s2))\n else false\n end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. simpl. reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (bag_theorem) *)\n(** Write down an interesting theorem [bag_theorem] about bags involving\n the functions [count] and [add], and prove it. Note that, since this\n problem is somewhat open-ended, it's possible that you may come up\n with a theorem which is true, but whose proof requires techniques\n you haven't learned yet. Feel free to ask for help if you get\n stuck! *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match position\n in the definition of [app], allowing the match itself to be\n simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n l'\". \n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n It is very important to work through the details of each one,\n using Coq and thinking about what each step achieves. Otherwise\n it is more or less guaranteed that the exercises will make no\n sense... *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n perhaps a little less familiar than standard natural number\n induction, but the basic idea is equally simple. Each [Inductive]\n declaration defines a set of data values that can be built up from\n the declared constructors: a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to a number; a\n list can be either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two things together establish the\n truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist, \n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3). \nProof.\n intros l1 l2 l3. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons n l1'\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n static written document -- it is easy to see what's going on if\n you are reading the proof in an interactive Coq session and you\n can see the current goal and context at each point, but this state\n is not visible in the written-down parts of the Coq proof. So a\n natural-language proof -- one written for human readers -- will\n need to include more explicit signposts; in particular, it will\n help the reader stay oriented if we remind them exactly what the\n induction hypothesis is in the second case. *)\n\n(** *** Informal version *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3], \n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n (the induction hypothesis). We must show\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]] \n By the definition of [++], this follows from\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n which is immediate from the induction hypothesis. []\n*)\n\n(** *** Another example *)\n(**\n Here is a similar example to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist, \n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n\n(** *** Reversing a list *)\n(** For a slightly more involved example of an inductive proof\n over lists, suppose we define a \"cons on the right\" function\n [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist := \n match l with\n | nil => [v]\n | h :: t => h :: (snoc t v)\n end.\n\n(** ... and use it to define a list-reversing function [rev]\n like this: *)\n\nFixpoint rev (l:natlist) : natlist := \n match l with\n | nil => nil\n | h :: t => snoc (rev t) h\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** *** Proofs about reverse *)\n(** Now let's prove some more list theorems using our newly\n defined [snoc] and [rev]. For something a little more challenging\n than the inductive proofs we've seen so far, let's prove that\n reversing a list does not change its length. Our first attempt at\n this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n :: l'\".\n (* This is the tricky case. Let's begin as usual \n by simplifying. *)\n simpl. \n (* Now we seem to be stuck: the goal is an equality \n involving [snoc], but we don't have any equations \n in either the immediate context or the global \n environment that have anything to do with [snoc]! \n\n We can make a little progress by using the IH to \n rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation about [snoc] that would have\n enabled us to make progress and prove it as a separate lemma. \n*)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n length (snoc l n) = S (length l).\nProof.\n intros n l. induction l as [| n' l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n' l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed. \n\n(**\n Note that we make the lemma as _general_ as possible: in particular,\n we quantify over _all_ [natlist]s, not just those that result\n from an application of [rev]. This should seem natural, \n because the truth of the goal clearly doesn't depend on \n the list having been reversed. Moreover, it is much easier\n to prove the more general property. \n*)\n \n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons\".\n simpl. rewrite -> length_snoc. \n rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems: \n\n _Theorem_: For all numbers [n] and lists [l],\n [length (snoc l n) = S (length l)].\n \n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (snoc [] n) = S (length []),\n which follows directly from the definitions of\n [length] and [snoc].\n\n - Next, suppose [l = n'::l'], with\n length (snoc l' n) = S (length l').\n We must show\n length (snoc (n' :: l') n) = S (length (n' :: l')).\n By the definitions of [length] and [snoc], this\n follows from\n S (length (snoc l' n)) = S (S (length l')),\n]] \n which is immediate from the induction hypothesis. [] *)\n \n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n \n _Proof_: By induction on [l]. \n\n - First, suppose [l = []]. We must show\n length (rev []) = length [],\n which follows directly from the definitions of [length] \n and [rev].\n \n - Next, suppose [l = n::l'], with\n length (rev l') = length l'.\n We must show\n length (rev (n :: l')) = length (n :: l').\n By the definition of [rev], this follows from\n length (snoc (rev l') n) = S (length l')\n which, by the previous lemma, is the same as\n S (length (rev l')) = S (length l').\n This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n and pedantic. After the first few, we might find it easier to\n follow proofs that give fewer details (since we can easily work\n them out in our own minds or on scratch paper if necessary) and\n just highlight the non-obvious steps. In this more compressed\n style, the above proof might look more like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that\n length (snoc l n) = S (length l)\n for any [l]. This follows by a straightforward induction on [l].\n The main property now follows by another straightforward\n induction on [l], using the observation together with the\n induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and on how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for\n present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, using [rewrite], and later we will see other ways\n of reusing previous theorems. But in order to refer to a theorem,\n we need to know its name, and remembering the names of all the\n theorems we might ever want to use can become quite difficult! It\n is often hard even to remember what theorems have been proven,\n much less what they are named.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following to\n see a list of theorems that we have proved about [rev]: *)\n\n SearchAbout rev.\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the course; it can save you a lot of time! *)\n\n(** Also, if you are using ProofGeneral, you can run [SearchAbout]\n with [C-c C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist, \n l ++ [] = l. \nProof.\nintros l.\ninduction l as [|l'].\nCase \"l=nil\".\nsimpl.\nreflexivity.\nCase \"l=cons\".\nsimpl.\nrewrite -> IHl.\nreflexivity.\nQed.\n\nLemma rev_snoc : forall l :natlist, forall n:nat,\nrev (snoc l n) = n :: rev l.\nProof.\nintros l n.\ninduction l as [|l'].\nCase \"l=nil\".\nsimpl. reflexivity.\nCase \"l=cons\".\nsimpl.\nrewrite -> IHl.\nsimpl.\nreflexivity.\nAdmitted.\n\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\nintros l.\ninduction l as [|l'].\nCase \"l=nil\".\nsimpl.\nreflexivity.\nCase \"l=cons\".\nsimpl.\nrewrite ->rev_snoc.\nrewrite -> IHl.\nreflexivity.\nQed.\n\n(** There is a short solution to the next exercise. If you find\n yourself getting tangled up, step back and try to look for a\n simpler way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\nintros.\nrewrite ->app_assoc.\nrewrite -> app_assoc.\nreflexivity.\nQed.\n\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n snoc l n = l ++ [n].\nProof.\nintros.\ninduction l as [|l'].\nCase \"l=nil\".\nsimpl.\nreflexivity.\nCase \"l=l'\".\nsimpl.\nrewrite ->IHl.\nreflexivity.\nQed.\n\n\nTheorem distr_rev : forall l1 l2 : natlist,\n rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\nintros.\ninduction l1 as [|l'].\nCase \"l=nil\".\nsimpl.\nrewrite ->app_nil_end.\nreflexivity.\nCase \"l1=l'\".\nsimpl.\nrewrite -> IHl1.\nrewrite -> ?snoc_append.\nrewrite -> app_assoc.\nreflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\nintros.\ninduction l1 as [|l'].\nCase \"l=nil\".\nsimpl.\nreflexivity.\nCase \"l1=l'\".\ndestruct l' as [|n].\nsimpl.\nrewrite -> IHl1.\nreflexivity.\nsimpl.\nrewrite -> IHl1.\nreflexivity.\nQed.\n\n\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\nmatch l1,l2 with\n|nil, nil =>true\n|nil, _ =>false\n|_, nil => false\n|h1 :: t1, h2::t2 => if(beq_nat h1 h2)\n then (beq_natlist t1 t2)\n else false\nend.\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\nProof. simpl. reflexivity. Qed.\nExample test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\nProof. simpl. reflexivity. Qed.\nExample test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.\nProof. simpl. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\nintros.\ninduction l as [|l'].\nCase \"l=nil\".\nsimpl.\nreflexivity.\nCase \"l=l'\".\nsimpl.\nrewrite <- IHl.\nassert (H: beq_nat l' l' = true).\ninduction l'.\nreflexivity.\nsimpl.\nrewrite -> IHl'.\nreflexivity.\nrewrite -> H.\nreflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 2 stars (list_design) *)\n(** Design exercise: \n - Write down a non-trivial theorem [cons_snoc_app]\n involving [cons] ([::]), [snoc], and [app] ([++]). \n - Prove it. *) \n\n(* FILL IN HERE *)\nTheorem cons_snoc_app: forall (l1 l2 :natlist) (n:nat),\n(snoc l1 n) ++ l2= l1 ++ (n :: l2).\nProof.\nintros.\ninduction l1 as [|l'].\nsimpl.\nreflexivity.\nsimpl.\nrewrite ->snoc_append.\nrewrite -> app_assoc.\nreflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n definitions about bags earlier in the file. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\n(** The following lemma about [ble_nat] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n ble_nat n (S n) = true.\nProof.\n intros n. induction n as [| n'].\n Case \"0\". \n simpl. reflexivity.\n Case \"S n'\".\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\nintros.\ninduction s as [|s'].\nsimpl.\nreflexivity.\ndestruct s' as [|n].\nsimpl.\ngeneralize (count 0 s).\nintros n.\nrewrite -> ble_n_Sn.\nreflexivity.\nsimpl.\nrewrite -> IHs.\nreflexivity.\nQed.\n\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *) \n(** Write down an interesting theorem [bag_count_sum] about bags \n involving the functions [count] and [sum], and prove it.*)\n\n(* FILL IN HERE *)\n\nTheorem bag_count_sum: forall (s1 s2:bag) (n:nat),\ncount n (sum s1 s2) = (count n s1) + (count n s2).\nProof.\nintros.\ninduction s1 as [|s'].\nsimpl.\nreflexivity.\nsimpl.\ndestruct (beq_nat n s') eqn:B.\nsimpl.\napply f_equal.\nassumption.\nassumption.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nThere is a hard way and an easy way to solve this exercise.\n*)\n\n(* FILL IN HERE *)\nTheorem rev_injective: forall (l1 l2 : natlist), \nrev l1 = rev l2 -> l1 = l2.\nProof.\nintros.\nSearchAbout rev.\nrewrite <- rev_involutive.\nrewrite <- H.\nrewrite -> rev_involutive.\nreflexivity.\nQed.\n\n\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n\n(** One use of [natoption] is as a way of returning \"error\n codes\" from functions. For example, suppose we want to write a\n function that returns the [n]th element of some list. If we give\n it type [nat -> natlist -> nat], then we'll have to return some\n number when the list is too short! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with \n | true => a \n | false => index_bad (pred n) l' \n end\n end.\n\n(** *** *)\n(** On the other hand, if we give it type [nat -> natlist ->\n natoption], then we can return [None] when the list is too short\n and [Some a] when the list has enough members and [a] appears at\n position [n]. *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption. \n\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => match beq_nat n O with \n | true => Some a\n | false => index (pred n) l' \n end\n end.\n\nExample test_index1 : index 0 [4;5;6;7] = Some 4.\nProof. reflexivity. Qed.\nExample test_index2 : index 3 [4;5;6;7] = Some 7.\nProof. reflexivity. Qed.\nExample test_index3 : index 10 [4;5;6;7] = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n small feature of Coq's programming language: conditional\n expressions... *)\n\n(** *** *)\n\nFixpoint last (l:natlist) : natoption :=\nmatch l with\n| nil => None\n| [x] => Some x\n| h :: t => last (t)\nend.\n\nDefinition last' (l:natlist) : natoption :=\nmatch (rev l) with\n| nil => None\n| h :: t => Some h\nend.\n\nExample l1 : last [1;2;3;4] = Some 4.\nProof. simpl. reflexivity. Qed.\n\nExample l2 : last' [1;2;3;4] = Some 4.\nProof. simpl. reflexivity. Qed.\n\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => if beq_nat n O then Some a else index' (pred n) l'\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_opt (l : natlist) : natoption :=\nmatch l with\n| nil => None\n| h :: t => Some h\nend.\n\nExample test_hd_opt1 : hd_opt [] = None.\nProof. simpl. reflexivity. Qed.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\nProof. simpl. reflexivity. Qed.\n\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_opt l).\nProof.\nintros.\ndestruct l.\nsimpl.\nreflexivity.\nsimpl.\nreflexivity.\nQed.\n\n(** [] *)\n\n(* ###################################################### *)\n(** * Dictionaries *)\n\n(** As a final illustration of how fundamental data structures\n can be defined in Coq, here is the declaration of a simple\n [dictionary] data type, using numbers for both the keys and the\n values stored under these keys. (That is, a dictionary represents\n a finite map from numbers to numbers.) *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n | empty : dictionary \n | record : nat -> nat -> dictionary -> dictionary. \n\n(** This declaration can be read: \"There are two ways to construct a\n [dictionary]: either using the constructor [empty] to represent an\n empty dictionary, or by applying the constructor [record] to\n a key, a value, and an existing [dictionary] to construct a\n [dictionary] with an additional key to value mapping.\" *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n (record key value d).\n\n(** Here is a function [find] that searches a [dictionary] for a\n given key. It evaluates evaluates to [None] if the key was not\n found and [Some val] if the key was mapped to [val] in the\n dictionary. If the same key is mapped to multiple values, [find]\n will return the first one it finds. *)\n\nFixpoint find (key : nat) (d : dictionary) : natoption := \n match d with \n | empty => None\n | record k v d' => if (beq_nat key k) \n then (Some v) \n else (find key d')\n end.\n\n\n\n(** **** Exercise: 1 star (dictionary_invariant1) *)\n(** Complete the following proof. *)\n\nLemma same_number_equal: forall k:nat,\nbeq_nat k k =true.\nProof.\nintros.\ninduction k.\nreflexivity.\nsimpl.\nrewrite -> IHk.\nreflexivity.\nQed.\n\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n (find k (insert k v d)) = Some v.\nProof.\nintros.\ndestruct d.\nsimpl.\nrewrite ->same_number_equal.\nreflexivity.\nsimpl.\nrewrite -> same_number_equal.\nreflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),\n beq_nat m n = false -> find m d = find m (insert n o d).\nProof.\nintros.\nsimpl.\nrewrite -> H.\nreflexivity.\nQed.\n(** [] *)\n\n\n\nEnd Dictionary.\n\nEnd NatList.\n\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)\n\n", "meta": {"author": "SumithraSriram", "repo": "Software-Foundations", "sha": "e3d8739ca9f399266450c8a859e6f615e3eb352b", "save_path": "github-repos/coq/SumithraSriram-Software-Foundations", "path": "github-repos/coq/SumithraSriram-Software-Foundations/Software-Foundations-e3d8739ca9f399266450c8a859e6f615e3eb352b/sf/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801267121407, "lm_q2_score": 0.9324533112067128, "lm_q1q2_score": 0.8819155232708606}} {"text": "(** * MoreProp: More about Propositions and Evidence *)\n\nRequire Export \"Prop\".\n\n\n(* ####################################################### *)\n(** * Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n [beautiful]) can be thought of as a _property_ -- i.e., it defines\n a subset of [nat], namely those numbers for which the proposition\n is provable. In the same way, a two-argument proposition can be\n thought of as a _relation_ -- i.e., it defines a set of pairs for\n which the proposition is provable. *)\n\nModule LeModule. \n\n\n(** One useful example is the \"less than or equal to\"\n relation on numbers. *)\n\n(** The following definition should be fairly intuitive. It\n says that there are two ways to give evidence that one number is\n less than or equal to another: either observe that they are the\n same number, or give evidence that the first is less than or equal\n to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n | le_n : forall n, le n n\n | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n [le_S] follow the same patterns as proofs about properties, like\n [ev] in chapter [Prop]. We can [apply] the constructors to prove [<=]\n goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n tactics like [inversion] to extract information from [<=]\n hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** Here are some sanity checks on the definition. (Notice that,\n although these are the same kind of simple \"unit tests\" as we gave\n for the testing functions we wrote in the first few lectures, we\n must construct their proofs explicitly -- [simpl] and\n [reflexivity] don't do the job, because the proofs aren't just a\n matter of simplifying computations.) *)\n\nTheorem test_le1 :\n 3 <= 3.\nProof.\n (* WORKED IN CLASS *)\n apply le_n. Qed.\n\nTheorem test_le2 :\n 3 <= 6.\nProof.\n (* WORKED IN CLASS *)\n apply le_S. apply le_S. apply le_S. apply le_n. Qed.\n\nTheorem test_le3 :\n (2 <= 1) -> 2 + 2 = 5.\nProof. \n (* WORKED IN CLASS *)\n intros H. inversion H. inversion H2. Qed.\n\n(** The \"strictly less than\" relation [n < m] can now be defined\n in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n | nn : next_nat n (S n).\n\nInductive next_even (n:nat) : nat -> Prop :=\n | ne_1 : ev (S n) -> next_even n (S n)\n | ne_2 : ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation) *)\n(** Define an inductive binary relation [total_relation] that holds\n between every pair of natural numbers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n that never holds. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\n(** Here are a number of facts about the [<=] and [<] relations that\n we are going to need later in the course. The proofs make good\n practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem O_le_n : forall n,\n 0 <= n.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n n <= m -> S n <= S m.\nProof. \n (* FILL IN HERE *) Admitted.\n\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n S n <= S m -> n <= m.\nProof. \n (* FILL IN HERE *) Admitted.\n\n\nTheorem le_plus_l : forall a b,\n a <= a + b.\nProof. \n (* FILL IN HERE *) Admitted.\n\nTheorem plus_lt : forall n1 n2 m,\n n1 + n2 < m ->\n n1 < m /\\ n2 < m.\nProof. \n unfold lt. \n (* FILL IN HERE *) Admitted.\n\nTheorem lt_S : forall n m,\n n < m ->\n n < S m.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true : forall n m,\n ble_nat n m = true -> n <= m.\nProof. \n (* FILL IN HERE *) Admitted.\n\nTheorem le_ble_nat : forall n m,\n n <= m ->\n ble_nat n m = true.\nProof.\n (* Hint: This may be easiest to prove by induction on [m]. *)\n (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true_trans : forall n m o,\n ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true. \nProof.\n (* Hint: This theorem can be easily proved without using [induction]. *)\n (* FILL IN HERE *) Admitted.\n\n\n(** **** Exercise: 3 stars (R_provability) *)\nModule R.\n(** We can define three-place relations, four-place relations,\n etc., in just the same way as binary relations. For example,\n consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n | c1 : R 0 0 0 \n | c2 : forall m n o, R m n o -> R (S m) n (S o)\n | c3 : forall m n o, R m n o -> R m (S n) (S o)\n | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n - [R 1 1 2]\n - [R 2 2 6]\n\n - If we dropped constructor [c5] from the definition of [R],\n would the set of provable propositions change? Briefly (1\n sentence) explain your answer.\n \n - If we dropped constructor [c4] from the definition of [R],\n would the set of provable propositions change? Briefly (1\n sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact) *) \n(** Relation [R] actually encodes a familiar function. State and prove two\n theorems that formally connects the relation and the function. \n That is, if [R m n o] is true, what can we say about [m],\n [n], and [o], and vice versa?\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd R.\n\n\n(* ##################################################### *)\n(** * Programming with Propositions *)\n\n(** A _proposition_ is a statement expressing a factual claim,\n like \"two plus two equals four.\" In Coq, propositions are written\n as expressions of type [Prop]. Although we haven't discussed this\n explicitly, we have already seen numerous examples. *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** Both provable and unprovable claims are perfectly good\n propositions. Simply _being_ a proposition is one thing; being\n _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n of type [Prop]. *)\n\n(** We've mainly seen one place that propositions can appear in Coq: in\n [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 : \n 2 + 2 = 4.\nProof. reflexivity. Qed.\n\n(** But they can be used in many other ways. For example, we have also seen that\n we can give a name to a proposition using a [Definition], just as we have\n given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop := 2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true : \n plus_fact.\nProof. reflexivity. Qed.\n\n(** We've seen several ways of constructing propositions. \n\n - We can define a new proposition primitively using [Inductive].\n\n - Given two expressions [e1] and [e2] of the same type, we can\n form the proposition [e1 = e2], which states that their\n values are equal.\n\n - We can combine propositions using implication and\n quantification. *)\n\n(** We have also seen _parameterized propositions_, such as [even] and\n [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even. \n(* ===> even : nat -> Prop *)\n\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n three equivalent ways: (1) \"[even] is a _function_ from numbers to\n propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n by a number [n],\" or (3) \"[even] is a _property_ of numbers.\" *)\n\n(** Propositions -- including parameterized propositions -- are\n first-class citizens in Coq. For example, we can define functions\n from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n P 0.\n\n(** Here are two more examples of passing parameterized propositions\n as arguments to a function. \n\n The first function, [true_for_all_numbers], takes a proposition\n [P] as argument and builds the proposition that [P] is true for\n all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n that, if [P] is true for some natural number [n'], then it is also\n true by the successor of [n'] -- i.e. that [P] is _preserved by\n successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n forall n', P n' -> P (S n').\n\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n forall (P:nat->Prop),\n true_for_zero P ->\n preserved_by_S P -> \n true_for_all_numbers P. \n\n\n\n(** **** Exercise: 3 stars (combine_odd_even) *)\n(** Complete the definition of the [combine_odd_even] function\n below. It takes as arguments two properties of numbers [Podd] and\n [Peven]. As its result, it should return a new property [P] such\n that [P n] is equivalent to [Podd n] when [n] is odd, and\n equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n (* FILL IN HERE *) admit.\n\n(** To test your definition, see whether you can prove the following\n facts: *)\n\nTheorem combine_odd_even_intro : \n forall (Podd Peven : nat -> Prop) (n : nat),\n (oddb n = true -> Podd n) ->\n (oddb n = false -> Peven n) ->\n combine_odd_even Podd Peven n.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_odd :\n forall (Podd Peven : nat -> Prop) (n : nat),\n combine_odd_even Podd Peven n ->\n oddb n = true ->\n Podd n.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_even :\n forall (Podd Peven : nat -> Prop) (n : nat),\n combine_odd_even Podd Peven n ->\n oddb n = false ->\n Peven n.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n parameterized propositions using [Definition], then can we also\n define them using [Fixpoint]? Of course we can! However, this\n kind of \"recursive parameterization\" doesn't correspond to\n anything very familiar from everyday mathematics. The following\n exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)\n(** Define a recursive function\n [true_upto_n__true_everywhere] that makes\n [true_upto_n_example] work. *)\n\n(* \nFixpoint true_upto_n__true_everywhere\n(* FILL IN HERE *)\n\nExample true_upto_n_example :\n (true_upto_n__true_everywhere 3 (fun n => even n))\n = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity. Qed.\n*)\n(** [] *)\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n\n", "meta": {"author": "Javran", "repo": "Thinking-dumps", "sha": "bfb0639c81078602e4b57d9dd89abd17fce0491f", "save_path": "github-repos/coq/Javran-Thinking-dumps", "path": "github-repos/coq/Javran-Thinking-dumps/Thinking-dumps-bfb0639c81078602e4b57d9dd89abd17fce0491f/software-foundations/old/MoreProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661028358093, "lm_q2_score": 0.9241418184118163, "lm_q1q2_score": 0.8815999689779186}} {"text": "(** **** KE DING 8318 *)\n\n(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\n\nModule NatList. \n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as in this definition: *)\n\nInductive natprod : Type :=\n pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\n(** We can construct an element of [natprod] like this: *)\n\nCheck (pair 3 5).\n\n(** Here are two simple function definitions for extracting the\n first and second components of a pair. (The definitions also\n illustrate how to do pattern matching on two-argument\n constructors.) *)\n\nDefinition fst (p : natprod) : nat := \n match p with\n | pair x y => x\n end.\nDefinition snd (p : natprod) : nat := \n match p with\n | pair x y => y\n end.\n\nEval simpl in (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this notation is provided as part of the standard\n library): *)\n\nEval simpl in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat := \n match p with\n | (x,y) => x\n end.\nDefinition snd' (p : natprod) : nat := \n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod := \n match p with\n | (x,y) => (y,x)\n end.\n\n(** Let's try and prove a few simple facts about pairs. If we\n state the lemmas in a particular (and slightly peculiar) way, we\n can prove them with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** Note that [reflexivity] is not enough if we state the lemma in a\n more natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAdmitted.\n\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct].\n\n Notice that, unlike for [nat]s, [destruct] doesn't generate an\n extra subgoal here. That's because [natprod]s can only be\n constructed in one way. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as (n,m). simpl. reflexivity. Qed.\n\n(** Notice that Coq allows us to use the notation we introduced\n for pairs in the \"[as]...\" pattern that tells it what variables to\n bind. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p.\n destruct p as (x,y).\n reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros p.\n destruct p as (x, y).\n reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n describe the type of _lists_ of numbers like this: \"A list is\n either the empty list or else a pair of a number and another\n list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following two declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n but in case you are interested, here is roughly what's going on.\n\n The [right associativity] annotation tells Coq how to parenthesize\n expressions involving several uses of [::] so that, for example,\n the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1,2,3].\n\nEval simpl in (mylist).\nEval simpl in (mylist1).\nEval simpl in (mylist2).\nEval simpl in (mylist3).\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\nNotation \"x + y\" := (plus x y) \n (at level 50, left associativity).\n The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (By the way, it's worth noting in passing that expressions like \"[1\n + 2 :: [3]]\" can be a little confusing when you read them in a .v\n file. The inner brackets, around 3, indicate a list, but the outer\n brackets, which are invisible in the HTML rendering, are there to\n instruct the \"coqdoc\" tool that the bracketed part should be\n displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist := \n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat := \n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist := \n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y) \n (right associativity, at level 60).\n\nExample test_app1: [1,2,3] ++ [4,5] = [1,2,3,4,5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4,5] = [4,5].\nProof. reflexivity. Qed.\nExample test_app3: [1,2,3] ++ nil = [1,2,3].\nProof. reflexivity. Qed.\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tail] returns everything but the first\n element. Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tail (l:natlist) : natlist :=\n match l with\n | nil => nil \n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1,2,3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tail: tail [1,2,3] = [2,3].\nProof. reflexivity. Qed.\nExample test_tail2: tail [] = [].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => match h with\n | O => nonzeros t\n | _ => h :: nonzeros t\n end\n end. \n\n\nExample test_nonzeros: nonzeros [0,1,0,2,3,0,0] = [1,2,3].\nProof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => match evenb h with\n | true => oddmembers t\n | false => h :: oddmembers t\n end\n end. \n\nExample test_oddmembers: oddmembers [0,1,0,2,3,0,0] = [1,3].\nProof. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n match l with\n | nil => 0\n | h :: t => match evenb h with\n | true => countoddmembers t\n | false => S (countoddmembers t)\n end\n end.\n\nExample test_countoddmembers1: countoddmembers [1,0,3,1,4,5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers2: countoddmembers [0,2,4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers3: countoddmembers nil = 0.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l1, l2 with\n | nil, _ => l2\n | _ , nil => l1\n | h1 :: t1, h2 :: t2 => h1 :: h2 :: (alternate t1 t2)\n end.\n\n\nExample test_alternate1: alternate [1,2,3] [4,5,6] = [1,4,2,5,3,6].\nProof. reflexivity. Qed.\nExample test_alternate2: alternate [1] [4,5,6] = [1,4,5,6].\nProof. reflexivity. Qed.\nExample test_alternate3: alternate [1,2,3] [4] = [1,4,2,3].\nProof. reflexivity. Qed.\nExample test_alternate4: alternate [] [20,30] = [20,30].\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n multiple times instead of just once. One reasonable\n implementation of bags is to represent a bag of numbers as a\n list. *)\n\nDefinition bag := natlist. \n\n(** **** Exercise: 3 stars (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat := \n match s with\n | nil => 0\n | h :: t => match beq_nat h v with\n | true => S (count v t)\n | false => count v t\n end\n end.\n\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1,2,3,1,4,1] = 3.\nProof. reflexivity. Qed.\nExample test_count2: count 6 [1,2,3,1,4,1] = 0.\nProof. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := \napp.\n\nCheck sum.\n\nExample test_sum1: count 1 (sum [1,2,3] [1,4,1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := \n cons v s.\n\nExample test_add1: count 1 (add 1 [1,4,1]) = 3.\nProof. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1,4,1]) = 0.\nProof. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool := \nmatch count v s with\n | O => false\n | _ => true\nend.\n\nExample test_member1: member 1 [1,4,1] = true.\nProof. reflexivity. Qed.\nExample test_member2: member 2 [1,4,1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n (* When remove_one is applied to a bag without the number to remove,\n it should return the same bag unchanged. *)\nmatch s with\n | nil => nil\n | h::t => match beq_nat v h with\n | true => t\n | false => h :: (remove_one v t)\n end\n end.\n\nExample test_remove_one1: count 5 (remove_one 5 [2,1,5,4,1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one2: count 5 (remove_one 5 [2,1,4,1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one3: count 4 (remove_one 5 [2,1,4,5,1,4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_one4: \n count 5 (remove_one 5 [2,1,5,4,5,1,4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\nmatch s with\n | nil => nil\n | h::t => match beq_nat v h with\n | true => remove_all v t\n | false => h :: (remove_all v t)\n end\n end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2,1,5,4,1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2,1,4,1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2,1,4,5,1,4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2,1,5,4,5,1,4,5,1,4]) = 0.\nProof. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n match s1 with\n | nil => true\n | h :: t => match member h s2 with\n | true => subset t (remove_one h s2)\n | false => false\n end\n end. \n\nExample test_subset1: subset [1,2] [2,1,4,1] = true.\nProof. reflexivity. Qed.\nExample test_subset2: subset [1,2,2] [2,1,4,1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (bag_theorem) *)\n(** Write down an interesting theorem about bags involving the\n functions [count] and [add], and prove it. Note that, since this\n problem is somewhat open-ended, it's possible that you may come up\n with a theorem which is true, but whose proof requires techniques\n you haven't learned yet. Feel free to ask for help if you get\n stuck! *)\nLemma beq_nat_ref : forall n:nat,\n beq_nat n n = true.\nProof.\n intros n.\n induction n.\n reflexivity.\n simpl. \n rewrite -> IHn.\n reflexivity. Qed.\n \nTheorem list_plus : forall l:bag, forall v:nat,\n count v (add v l) = S (count v l).\nProof.\n intros l v.\n simpl.\n rewrite -> beq_nat_ref.\n reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match position\n in the definition of [app], allowing the match itself to be\n simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tail l).\nProof.\n intros l. destruct l as [| n l'].\n Case \"l = nil\".\n simpl.\n reflexivity.\n Case \"l = cons n l'\".\n simpl. \n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tail nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proofs will not get you very far! It is\n very important to work through the details of each one, using Coq\n and thinking about what each step of the proof achieves.\n Otherwise it is more or less guaranteed that the exercises will\n make no sense. *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n perhaps a little less familiar than standard natural number\n induction, but the basic idea is equally simple. Each [Inductive]\n declaration defines a set of data values that can be built up from\n the declared constructors: a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to a number; a\n list can be either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two things together establish the\n truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_ass : forall l1 l2 l3 : natlist, \n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3). \nProof.\n intros l1 l2 l3. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons n l1'\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n static written document -- it is easy to see what's going on if\n you are reading the proof in an interactive Coq session and you\n can see the current goal and context at each point, but this state\n is not visible in the written-down parts of the Coq proof. So a\n natural-language proof -- one written for human readers -- will\n need to include more explicit signposts; in particular, it will\n help the reader stay oriented if we remind them exactly what the\n induction hypothesis is in the second case. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3], \n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n (the induction hypothesis). We must show\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]] \n By the definition of [++], this follows from\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n which is immediate from the induction hypothesis. []\n\n Here is a similar example to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist, \n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** For a slightly more involved example of an inductive proof\n over lists, suppose we define a \"cons on the right\" function\n [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist := \n match l with\n | nil => [v]\n | h :: t => h :: (snoc t v)\n end.\n\n(** ... and use it to define a list-reversing function [rev]\n like this: *)\n\nFixpoint rev (l:natlist) : natlist := \n match l with\n | nil => nil\n | h :: t => snoc (rev t) h\n end.\n\nExample test_rev1: rev [1,2,3] = [3,2,1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** Now let's prove some more list theorems using our newly\n defined [snoc] and [rev]. For something a little more challenging\n than the inductive proofs we've seen so far, let's prove that\n reversing a list does not change its length. Our first attempt at\n this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n :: l'\".\n (* This is the tricky case. Let's begin as usual \n by simplifying. *)\n simpl. \n (* Now we seem to be stuck: the goal is an equality \n involving [snoc], but we don't have any equations \n in either the immediate context or the global \n environment that have anything to do with [snoc]! \n\n We can make a little progress by using the IH to \n rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAdmitted.\n\n(** So let's take the equation about [snoc] that would have\n enabled us to make progress and prove it as a separate lemma. *)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n length (snoc l n) = S (length l).\nProof.\n intros n l. induction l as [| n' l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n' l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed. \n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons\".\n simpl. rewrite -> length_snoc. \n rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems: \n\n _Theorem_: For all numbers [n] and lists [l],\n [length (snoc l n) = S (length l)].\n \n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (snoc [] n) = S (length []),\n which follows directly from the definitions of\n [length] and [snoc].\n\n - Next, suppose [l = n'::l'], with\n length (snoc l' n) = S (length l').\n We must show\n length (snoc (n' :: l') n) = S (length (n' :: l')).\n By the definitions of [length] and [snoc], this\n follows from\n S (length (snoc l' n)) = S (S (length l')),\n]] \n which is immediate from the induction hypothesis. [] *)\n \n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n \n _Proof_: By induction on [l]. \n\n - First, suppose [l = []]. We must show\n length (rev []) = length [],\n which follows directly from the definitions of [length] \n and [rev].\n \n - Next, suppose [l = n::l'], with\n length (rev l') = length l'.\n We must show\n length (rev (n :: l')) = length (n :: l').\n By the definition of [rev], this follows from\n length (snoc (rev l') n) = S (length l')\n which, by the previous lemma, is the same as\n S (length (rev l')) = S (length l').\n This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n and pedantic. After the first few, we might find it easier to\n follow proofs that give fewer details (since we can easily work\n them out in our own minds or on scratch paper if necessary) and\n just highlight the non-obvious steps. In this more compressed\n style, the above proof might look more like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that\n length (snoc l n) = S (length l)\n for any [l]. This follows by a straightforward induction on [l].\n The main property now follows by another straightforward\n induction on [l], using the observation together with the\n induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and on how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for\n present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, using [rewrite], and later we will see other ways\n of reusing previous theorems. But in order to refer to a theorem,\n we need to know its name, and remembering the names of all the\n theorems we might ever want to use can become quite difficult! It\n is often hard even to remember what theorems have been proven,\n much less what they are named.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following to\n see a list of theorems that we have proved about [rev]: *)\n\nSearchAbout rev.\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the course; it can save you a lot of time! *)\n \n(** Also, if you are using ProofGeneral, you can run [SearchAbout]\n with [C-c C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist, \n l ++ [] = l. \nProof.\n intros l.\n induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n::l'\".\n simpl.\n rewrite -> IHl'.\n reflexivity. Qed.\n\nLemma rev_snoc_involutive : forall n : nat, forall l : natlist,\n rev (snoc l n) = n :: (rev l).\nProof.\n intros n l.\n induction l as [| n' l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n' :: l'\".\n simpl.\n rewrite -> IHl'.\n reflexivity. Qed.\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros l.\n induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n::l'\".\n simpl.\n rewrite -> rev_snoc_involutive.\n rewrite -> IHl'.\n reflexivity. Qed.\n\n(** There is a short solution to the next exercise. If you find\n yourself getting tangled up, step back and try to look for a\n simpler way. *)\n\nTheorem app_ass4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros l1 l2 l3 l4.\n rewrite -> app_ass.\n rewrite -> app_ass with (l3:= l3 ++ l4).\n reflexivity. Qed.\n \n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n snoc l n = l ++ [n].\nProof.\n intros l n.\n induction l as [| n' l'].\n Case \"l = []\".\n reflexivity.\n Case \"l= n' :: l'\".\n simpl.\n rewrite -> IHl'.\n reflexivity. Qed.\n\nTheorem distr_rev : forall l1 l2 : natlist,\n rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n intros l1 l2.\n induction l1 as [| n1 l1'].\n Case \"l1 = []\".\n simpl.\n rewrite -> app_nil_end.\n reflexivity.\n Case \"l1 = n1::l1'\".\n simpl.\n rewrite -> IHl1'.\n rewrite -> snoc_append.\n rewrite -> snoc_append.\n rewrite -> app_ass.\n reflexivity. Qed.\n \n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros l1 l2.\n induction l1 as [|n l1'].\n Case \"l1 = []\".\n simpl.\n reflexivity.\n Case \"l1 = n::l1'\".\n simpl.\n rewrite -> IHl1'.\n destruct n as [| S n'].\n SCase \"n = 0\".\n reflexivity.\n SCase \"n = S n'\".\n reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 2 stars (list_design) *)\n(** Design exercise: \n - Write down a non-trivial theorem involving [cons]\n ([::]), [snoc], and [app] ([++]). \n - Prove it. *) \n(*n :: k :: snoc (l' ++ k :: l') m = n :: k :: l' ++ k :: snoc l' m*)\nLemma list_eq_cons : forall n : nat, forall l1 l2 : natlist,\n l1 = l2 -> n::l1 = n::l2.\nProof.\n intros n l1 l2 H.\n destruct l1.\n rewrite -> H.\n reflexivity.\n rewrite -> H.\n reflexivity. Qed.\n\nLemma append_head_list : forall n : nat, forall l1 l2: natlist,\n n::(l1 ++ l2) = (n::l1) ++ l2.\nProof.\n intros n l1 l2.\n destruct l1 as [|m l1'].\n Case \"l1 = []\".\n reflexivity.\n Case \"l1 = m::l1'\".\n reflexivity. Qed.\n\nLemma append_tail_list : forall n : nat, forall l1 l2 : natlist,\n snoc (l1 ++ l2) n = l1 ++ (snoc l2 n).\nProof.\n intros n l1 l2.\n induction l1 as [|m l1'].\n Case \"l1 = []\".\n reflexivity.\n Case \"l1 = m::l1'\".\n simpl.\n rewrite -> IHl1'.\n reflexivity. Qed.\n \nTheorem append_head_tail_list : forall n m : nat, forall l1 l2 : natlist,\n snoc (n::(l1++l2)) m = (n::l1) ++ (snoc l2 m).\nProof.\n intros n m l1 l2.\n induction l1 as [| k l1'].\n Case \"l1 = []\".\n reflexivity.\n Case \"l1 = k::l1'\".\n simpl.\n rewrite -> append_tail_list.\n reflexivity. Qed.\n\nFixpoint loop_list (n : nat) (l : natlist) : natlist :=\n match n with\n | O => l\n | S n' => loop_list n' (snoc (tail l) (hd 0 l))\n end.\n\nEval simpl in (loop_list 5 [5, 1, 2, 3, 4, 1, 2, 3, 4, 5]).\n\nLemma app_nil : forall l : natlist,\n l ++ [] = l.\nProof.\n induction l as [|n l'].\n SCase \"l = []\".\n reflexivity.\n SCase \"l = n::l'\".\n simpl.\n rewrite -> IHl'.\n reflexivity. Qed.\n\nLemma empty_list : forall l : natlist,\n length l = 0 -> l = nil.\nAdmitted.\n\nLemma roll_list_snoc : forall l: natlist,forall x n : nat,\n n = length l -> loop_list n (snoc l x) = x :: l.\nProof. \n induction l as [|x' l'].\n Case \"l = []\".\n intros x n.\n intros H.\n rewrite -> H.\n reflexivity.\n Case \"l = x' :: l'\".\n destruct n as [|n'].\n SCase \"n = 0\".\n simpl.\n intros H.\n inversion H.\n SCase \"n = S n'\".\n simpl.\n intros H.\n inversion H.\n rewrite <- H1.\n rewrite -> snoc_append.\n rewrite -> snoc_append.\n Admitted.\n\nLemma roll_list_ref : forall l : natlist, forall n : nat,\n n = length l -> loop_list n l = l.\nProof.\n induction l as [|x l'].\n Case \"l = []\".\n intros n H.\n rewrite -> H.\n reflexivity.\n Case \"l = x::l'\".\n destruct n as [|n'].\n SCase \"n = 0\".\n intros H.\n inversion H.\n SCase \"n = S n'\".\n intros H.\n inversion H.\n simpl.\n rewrite <- H1.\n apply (roll_list_snoc l' x n' H1).\nQed.\n\nTheorem roll_lists_length : forall l1 l2 : natlist, forall n : nat,\n n = length l1 -> loop_list n (l1 ++ l2) = l2 ++ l1.\nProof.\n induction l1 as [|n1 l1'].\n Case \"l1 = []\".\n simpl.\n intros l2 n H.\n rewrite -> H.\n symmetry.\n apply app_nil.\n Case \"l1 = n1::l1'\".\n simpl.\n destruct n as [|n'].\n SCase \"n = 0\".\n intros H.\n inversion H.\n SCase \"n = S n'\".\n simpl.\n intros H.\n inversion H.\n rewrite <- H1.\n apply (IHl1' l2 n') in H1.\nAdmitted.\n\nTheorem roll_lists_ref : forall l : natlist, forall x n : nat,\n n = length (x::l) -> loop_list n ((x :: l) ++ (snoc l x)) = (snoc l x) ++ (x :: l).\nProof.\n intros l x n.\n apply roll_lists_length.\n Qed.\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\ndefinitions about bags in the previous problem. *)\n\nPrint count.\n\nTheorem count_member_nonzero : forall (s : bag),\n ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n reflexivity. Qed.\n\n(** The following lemma about [ble_nat] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n ble_nat n (S n) = true.\nProof.\n intros n. induction n as [| n'].\n Case \"0\". \n simpl. reflexivity.\n Case \"S n'\".\n simpl. rewrite IHn'. reflexivity. Qed.\n\nLemma ble_Sn : forall n : nat,\n ble_nat n (S n) = true.\nProof.\n induction n as [|n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n simpl. \n rewrite -> IHn'. \n reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag), \n ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n intros s.\n induction s as [|n s'].\n Case \"s = []\".\n reflexivity.\n Case \"s = n::s'\".\n destruct n as [| S n'].\n SCase \"n = 0\".\n simpl.\n rewrite -> ble_Sn.\n reflexivity.\n SCase \"n = S n'\".\n simpl.\n rewrite -> IHs'.\n reflexivity. Qed.\n \n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *) \n(** Write down an interesting theorem about bags involving the\n functions [count] and [sum], and prove it.*)\nCheck sum.\nTheorem bag_count_sum : forall (l1 l2 : natlist), forall (n : nat),\n count n (sum l1 l2) = count n l1 + count n l2.\nProof.\n intros l1 l2 n.\n induction l1 as [|m l1'].\n Case \"l1 = []\".\n reflexivity.\n Case \"l1 = m::l1'\".\n simpl.\n rewrite -> IHl1'.\n destruct (beq_nat m n).\n SCase \"m = n\".\n rewrite -> plus_comm.\n rewrite -> plus_n_Sm.\n rewrite -> plus_comm.\n reflexivity.\n SCase \"m != n\".\n reflexivity. Qed.\n \n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nThere is a hard way and an easy way to solve this exercise.\n*)\nTheorem rev_injective_rev : forall (l1 l2 : natlist), \n l1 = l2 -> rev l1 = rev l2.\nProof.\n intros l1 l2 H.\n destruct l1 as [|m l1'].\n Case \"l1 = []\".\n rewrite -> H.\n reflexivity.\n Case \"l1 = m::l1'\".\n rewrite -> H.\n reflexivity. Qed.\n\nSearchAbout rev.\n\nTheorem rev_injective : forall (l1 l2 : natlist), \n rev l1 = rev l2 -> l1 = l2.\nProof.\n intros l1 l2 H.\n assert (double_rev: rev (rev l1) = rev (rev l2)).\n Case \"Proof of assert\".\n rewrite -> H.\n reflexivity.\n rewrite -> rev_involutive in double_rev.\n rewrite -> rev_involutive in double_rev.\n rewrite -> double_rev.\n reflexivity. Qed.\n \n(* FILL IN HERE *)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n(** Here is another type definition that is often useful in\n day-to-day programming: *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption. \n\n(** One use of [natoption] is as a way of returning \"error\n codes\" from functions. For example, suppose we want to write a\n function that returns the [n]th element of some list. If we give\n it type [nat -> natlist -> nat], then we'll have to return some\n number when the list is too short! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with \n | true => a \n | false => index_bad (pred n) l' \n end\n end.\n\n(** On the other hand, if we give it type [nat -> natlist ->\n natoption], then we can return [None] when the list is too short\n and [Some a] when the list has enough members and [a] appears at\n position [n]. *)\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => match beq_nat n O with \n | true => Some a\n | false => index (pred n) l' \n end\n end.\n\nExample test_index1 : index 0 [4,5,6,7] = Some 4.\nProof. reflexivity. Qed.\nExample test_index2 : index 3 [4,5,6,7] = Some 7.\nProof. reflexivity. Qed.\nExample test_index3 : index 10 [4,5,6,7] = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n small feature of Coq's programming language: conditional\n expressions... *)\n\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => if beq_nat n O then Some a else index' (pred n) l'\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_opt (l : natlist) : natoption :=\n match l with\n | nil => None\n | h :: t => Some h\n end.\n\nExample test_hd_opt1 : hd_opt [] = None.\n reflexivity. Qed.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\n reflexivity. Qed.\n\nExample test_hd_opt3 : hd_opt [5,6] = Some 5.\n reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_opt l).\nProof.\n intros l default.\n destruct l.\n Case \"l = []\".\n simpl. reflexivity.\n Case \"l = m::l'\".\n simpl. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n match l1, l2 with\n | nil, nil => true\n | nil, m::l2' => false\n | n::l1', nil => false\n | n::l1', m::l2' => if (beq_nat n m)\n then (beq_natlist l1' l2')\n else false\n end.\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\n reflexivity. Qed.\nExample test_beq_natlist2 : beq_natlist [1,2,3] [1,2,3] = true.\n reflexivity. Qed.\nExample test_beq_natlist3 : beq_natlist [1,2,3] [1,2,4] = false.\n reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\n intros l.\n induction l.\n reflexivity.\n simpl.\n rewrite -> beq_nat_ref.\n rewrite -> IHl.\n reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Dictionaries *)\n\n(** As a final illustration of how fundamental data structures\n can be defined in Coq, here is the declaration of a simple\n [dictionary] data type, using numbers for both the keys and the\n values stored under these keys. (That is, a dictionary represents\n a finite map from numbers to numbers.) *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n | empty : dictionary \n | record : nat -> nat -> dictionary -> dictionary. \n\n(** This declaration can be read: \"There are two ways to construct a\n [dictionary]: either using the constructor [empty] to represent an\n empty dictionary, or by applying the constructor [record] to\n a key, a value, and an existing [dictionary] to construct a\n [dictionary] with an additional key to value mapping.\" *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n (record key value d).\n\n(** Here is a function [find] that searches a [dictionary] for a\n given key. It evaluates evaluates to [None] if the key was not\n found and [Some val] if the key was mapped to [val] in the\n dictionary. If the same key is mapped to multiple values, [find]\n will return the first one it finds. *)\n\nFixpoint find (key : nat) (d : dictionary) : natoption := \n match d with \n | empty => None\n | record k v d' => if (beq_nat key k) \n then (Some v) \n else (find key d')\n end.\n\n\n(** **** Exercise: 1 star (dictionary_invariant1) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n (find k (insert k v d)) = Some v.\nProof.\n intros d k v.\n simpl.\n rewrite -> beq_nat_ref.\n reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),\n (beq_nat m n) = false -> (find m d) = (find m (insert n o d)).\nProof.\n intros d m n o H.\n simpl.\n rewrite -> H.\n reflexivity. Qed.\n \n(** [] *)\nEnd Dictionary.\n\nEnd NatList.\n\n(* $Date: 2013-02-02 10:26:41 -0500 (Sat, 02 Feb 2013) $ *)\n\n(** **** KE DING 8318 *)\n", "meta": {"author": "gf4t47", "repo": "coq", "sha": "420c6322eb340e0a0299f5ac07a2a6f495ffc72d", "save_path": "github-repos/coq/gf4t47-coq", "path": "github-repos/coq/gf4t47-coq/coq-420c6322eb340e0a0299f5ac07a2a6f495ffc72d/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.9362850030812307, "lm_q1q2_score": 0.8808473379465227}} {"text": "(** * More Logic *)\n\nRequire Export \"Prop\".\n\n(* ############################################################ *)\n(** * Existential Quantification *)\n\n(** Another critical logical connective is _existential\n quantification_. We can express it with the following\n definition: *)\n\nInductive ex (X:Type) (P : X->Prop) : Prop :=\n ex_intro : forall (witness:X), P witness -> ex X P.\n\n(** That is, [ex] is a family of propositions indexed by a type [X]\n and a property [P] over [X]. In order to give evidence for the\n assertion \"there exists an [x] for which the property [P] holds\"\n we must actually name a _witness_ -- a specific value [x] -- and\n then give evidence for [P x], i.e., evidence that [x] has the\n property [P]. \n\n*)\n\n\n(** *** *)\n(** Coq's [Notation] facility can be used to introduce more\n familiar notation for writing existentially quantified\n propositions, exactly parallel to the built-in syntax for\n universally quantified propositions. Instead of writing [ex nat\n ev] to express the proposition that there exists some number that\n is even, for example, we can write [exists x:nat, ev x]. (It is\n not necessary to understand exactly how the [Notation] definition\n works.) *)\n\nNotation \"'exists' x , p\" := (ex _ (fun x => p))\n (at level 200, x ident, right associativity) : type_scope.\nNotation \"'exists' x : X , p\" := (ex _ (fun x:X => p))\n (at level 200, x ident, right associativity) : type_scope.\n\n(** *** *)\n(** We can use the usual set of tactics for\n manipulating existentials. For example, to prove an\n existential, we can [apply] the constructor [ex_intro]. Since the\n premise of [ex_intro] involves a variable ([witness]) that does\n not appear in its conclusion, we need to explicitly give its value\n when we use [apply]. *)\n\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof.\n apply ex_intro with (witness:=2). \n reflexivity. Qed.\n\n(** Note that we have to explicitly give the witness. *)\n\n(** *** *)\n(** Or, instead of writing [apply ex_intro with (witness:=e)] all the\n time, we can use the convenient shorthand [exists e], which means\n the same thing. *)\n\nExample exists_example_1' : exists n, n + (n * n) = 6.\nProof.\n exists 2. \n reflexivity. Qed.\n\n(** *** *)\n(** Conversely, if we have an existential hypothesis in the\n context, we can eliminate it with [inversion]. Note the use\n of the [as...] pattern to name the variable that Coq\n introduces to name the witness value and get evidence that\n the hypothesis holds for the witness. (If we don't\n explicitly choose one, Coq will just call it [witness], which\n makes proofs confusing.) *)\n \nTheorem exists_example_2 : forall n,\n (exists m, n = 4 + m) ->\n (exists o, n = 2 + o).\nProof.\n intros n H.\n inversion H as [m Hm]. \n exists (2 + m). \n apply Hm. Qed. \n\n\n(** Here is another example of how to work with existentials. *)\nLemma exists_example_3 : \n exists (n:nat), even n /\\ beautiful n.\nProof.\n(* WORKED IN CLASS *)\n exists 8.\n split.\n unfold even. simpl. reflexivity.\n apply b_sum with (n:=3) (m:=5).\n apply b_3. apply b_5.\nQed.\n\n(** **** Exercise: 1 star, optional (english_exists) *)\n(** In English, what does the proposition \n ex nat (fun n => beautiful (S n))\n]] \n mean? *)\n\n(* FILL IN HERE *)\n\n(*\n*)\n(** **** Exercise: 1 star (dist_not_exists) *)\n(** Prove that \"[P] holds for all [x]\" implies \"there is no [x] for\n which [P] does not hold.\" *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n (forall x, P x) -> ~ (exists x, ~ P x).\nProof. \n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (not_exists_dist) *)\n(** (The other direction of this theorem requires the classical \"law\n of the excluded middle\".) *)\n\nTheorem not_exists_dist :\n excluded_middle ->\n forall (X:Type) (P : X -> Prop),\n ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (dist_exists_or) *)\n(** Prove that existential quantification distributes over\n disjunction. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Evidence-carrying booleans. *)\n\n(** So far we've seen two different forms of equality predicates:\n[eq], which produces a [Prop], and\nthe type-specific forms, like [beq_nat], that produce [boolean]\nvalues. The former are more convenient to reason about, but\nwe've relied on the latter to let us use equality tests \nin _computations_. While it is straightforward to write lemmas\n(e.g. [beq_nat_true] and [beq_nat_false]) that connect the two forms,\nusing these lemmas quickly gets tedious. \n*)\n\n(** *** *)\n(** \nIt turns out that we can get the benefits of both forms at once \nby using a construct called [sumbool]. *)\n\nInductive sumbool (A B : Prop) : Set :=\n | left : A -> sumbool A B \n | right : B -> sumbool A B.\n\nNotation \"{ A } + { B }\" := (sumbool A B) : type_scope.\n\n(** Think of [sumbool] as being like the [boolean] type, but instead\nof its values being just [true] and [false], they carry _evidence_\nof truth or falsity. This means that when we [destruct] them, we\nare left with the relevant evidence as a hypothesis -- just as with [or].\n(In fact, the definition of [sumbool] is almost the same as for [or].\nThe only difference is that values of [sumbool] are declared to be in\n[Set] rather than in [Prop]; this is a technical distinction \nthat allows us to compute with them.) *) \n\n(** *** *)\n\n(** Here's how we can define a [sumbool] for equality on [nat]s *)\n\nTheorem eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.\nProof.\n (* WORKED IN CLASS *)\n intros n.\n induction n as [|n'].\n Case \"n = 0\".\n intros m.\n destruct m as [|m'].\n SCase \"m = 0\".\n left. reflexivity.\n SCase \"m = S m'\".\n right. intros contra. inversion contra.\n Case \"n = S n'\".\n intros m.\n destruct m as [|m'].\n SCase \"m = 0\".\n right. intros contra. inversion contra.\n SCase \"m = S m'\". \n destruct IHn' with (m := m') as [eq | neq].\n left. apply f_equal. apply eq.\n right. intros Heq. inversion Heq as [Heq']. apply neq. apply Heq'.\nDefined. \n \n(** Read as a theorem, this says that equality on [nat]s is decidable:\nthat is, given two [nat] values, we can always produce either \nevidence that they are equal or evidence that they are not.\nRead computationally, [eq_nat_dec] takes two [nat] values and returns\na [sumbool] constructed with [left] if they are equal and [right] \nif they are not; this result can be tested with a [match] or, better,\nwith an [if-then-else], just like a regular [boolean]. \n(Notice that we ended this proof with [Defined] rather than [Qed]. \nThe only difference this makes is that the proof becomes _transparent_,\nmeaning that its definition is available when Coq tries to do reductions,\nwhich is important for the computational interpretation.)\n*) \n\n(** *** *)\n(** \nHere's a simple example illustrating the advantages of the [sumbool] form. *)\n\nDefinition override' {X: Type} (f: nat->X) (k:nat) (x:X) : nat->X:=\n fun (k':nat) => if eq_nat_dec k k' then x else f k'.\n\nTheorem override_same' : forall (X:Type) x1 k1 k2 (f : nat->X),\n f k1 = x1 -> \n (override' f k1 x1) k2 = f k2.\nProof.\n intros X x1 k1 k2 f. intros Hx1.\n unfold override'.\n destruct (eq_nat_dec k1 k2). (* observe what appears as a hypothesis *)\n Case \"k1 = k2\".\n rewrite <- e.\n symmetry. apply Hx1.\n Case \"k1 <> k2\". \n reflexivity. Qed.\n\n(** Compare this to the more laborious proof (in MoreCoq.v) for the \n version of [override] defined using [beq_nat], where we had to\n use the auxiliary lemma [beq_nat_true] to convert a fact about booleans\n to a Prop. *)\n\n\n(** **** Exercise: 1 star (override_shadow') *)\nTheorem override_shadow' : forall (X:Type) x1 x2 k1 k2 (f : nat->X),\n (override' (override' f k1 x2) k1 x1) k2 = (override' f k1 x1) k2.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (all_forallb) *)\n(** Inductively define a property [all] of lists, parameterized by a\n type [X] and a property [P : X -> Prop], such that [all X P l]\n asserts that [P] is true for every element of the list [l]. *)\n\nInductive all (X : Type) (P : X -> Prop) : list X -> Prop :=\n (* FILL IN HERE *)\n.\n\n(** Recall the function [forallb], from the exercise\n [forall_exists_challenge] in chapter [Poly]: *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n match l with\n | [] => true\n | x :: l' => andb (test x) (forallb test l')\n end.\n\n(** Using the property [all], write down a specification for [forallb],\n and prove that it satisfies the specification. Try to make your \n specification as precise as possible.\n\n Are there any important properties of the function [forallb] which\n are not captured by your specification? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (filter_challenge) *)\n(** One of the main purposes of Coq is to prove that programs match\n their specifications. To this end, let's prove that our\n definition of [filter] matches a specification. Here is the\n specification, written out informally in English.\n\n Suppose we have a set [X], a function [test: X->bool], and a list\n [l] of type [list X]. Suppose further that [l] is an \"in-order\n merge\" of two lists, [l1] and [l2], such that every item in [l1]\n satisfies [test] and no item in [l2] satisfies test. Then [filter\n test l = l1].\n\n A list [l] is an \"in-order merge\" of [l1] and [l2] if it contains\n all the same elements as [l1] and [l2], in the same order as [l1]\n and [l2], but possibly interleaved. For example, \n [1,4,6,2,3]\n is an in-order merge of\n [1,6,2]\n and\n [4,3].\n Your job is to translate this specification into a Coq theorem and\n prove it. (Hint: You'll need to begin by defining what it means\n for one list to be a merge of two others. Do this with an\n inductive relation, not a [Fixpoint].) *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced, optional (filter_challenge_2) *)\n(** A different way to formally characterize the behavior of [filter]\n goes like this: Among all subsequences of [l] with the property\n that [test] evaluates to [true] on all their members, [filter test\n l] is the longest. Express this claim formally and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (no_repeats) *)\n(** The following inductively defined proposition... *)\n\nInductive appears_in {X:Type} (a:X) : list X -> Prop :=\n | ai_here : forall l, appears_in a (a::l)\n | ai_later : forall b l, appears_in a l -> appears_in a (b::l).\n\n(** ...gives us a precise way of saying that a value [a] appears at\n least once as a member of a list [l]. \n\n Here's a pair of warm-ups about [appears_in].\n*)\n\nLemma appears_in_app : forall (X:Type) (xs ys : list X) (x:X), \n appears_in x (xs ++ ys) -> appears_in x xs \\/ appears_in x ys.\nProof.\n (* FILL IN HERE *) Admitted.\n\nLemma app_appears_in : forall (X:Type) (xs ys : list X) (x:X), \n appears_in x xs \\/ appears_in x ys -> appears_in x (xs ++ ys).\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** Now use [appears_in] to define a proposition [disjoint X l1 l2],\n which should be provable exactly when [l1] and [l2] are\n lists (with elements of type X) that have no elements in common. *)\n\n(* FILL IN HERE *)\n\n(** Next, use [appears_in] to define an inductive proposition\n [no_repeats X l], which should be provable exactly when [l] is a\n list (with elements of type [X]) where every member is different\n from every other. For example, [no_repeats nat [1,2,3,4]] and\n [no_repeats bool []] should be provable, while [no_repeats nat\n [1,2,1]] and [no_repeats bool [true,true]] should not be. *)\n\n(* FILL IN HERE *)\n\n(** Finally, state and prove one or more interesting theorems relating\n [disjoint], [no_repeats] and [++] (list append). *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** **** Exercise: 3 stars (nostutter) *)\n(** Formulating inductive definitions of predicates is an important\n skill you'll need in this course. Try to solve this exercise\n without any help at all (except from your study group partner, if\n you have one).\n\n We say that a list of numbers \"stutters\" if it repeats the same\n number consecutively. The predicate \"[nostutter mylist]\" means\n that [mylist] does not stutter. Formulate an inductive definition\n for [nostutter]. (This is different from the [no_repeats]\n predicate in the exercise above; the sequence [1,4,1] repeats but\n does not stutter.) *)\n\nInductive nostutter: list nat -> Prop :=\n (* FILL IN HERE *)\n.\n\n(** Make sure each of these tests succeeds, but you are free\n to change the proof if the given one doesn't work for you.\n Your definition might be different from mine and still correct,\n in which case the examples might need a different proof.\n \n The suggested proofs for the examples (in comments) use a number\n of tactics we haven't talked about, to try to make them robust\n with respect to different possible ways of defining [nostutter].\n You should be able to just uncomment and use them as-is, but if\n you prefer you can also prove each example with more basic\n tactics. *)\n\nExample test_nostutter_1: nostutter [3;1;4;1;5;6].\n(* FILL IN HERE *) Admitted.\n(* \n Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_2: nostutter [].\n(* FILL IN HERE *) Admitted.\n(* \n Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_3: nostutter [5].\n(* FILL IN HERE *) Admitted.\n(* \n Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_4: not (nostutter [3;1;1;4]).\n(* FILL IN HERE *) Admitted.\n(* \n Proof. intro.\n repeat match goal with \n h: nostutter _ |- _ => inversion h; clear h; subst \n end.\n contradiction H1; auto. Qed.\n*)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (pigeonhole principle) *)\n(** The \"pigeonhole principle\" states a basic fact about counting:\n if you distribute more than [n] items into [n] pigeonholes, some \n pigeonhole must contain at least two items. As is often the case,\n this apparently trivial fact about numbers requires non-trivial\n machinery to prove, but we now have enough... *)\n\n(** First a pair of useful lemmas (we already proved these for lists\n of naturals, but not for arbitrary lists). *)\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n length (l1 ++ l2) = length l1 + length l2. \nProof. \n (* FILL IN HERE *) Admitted.\n\nLemma appears_in_app_split : forall (X:Type) (x:X) (l:list X),\n appears_in x l -> \n exists l1, exists l2, l = l1 ++ (x::l2).\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** Now define a predicate [repeats] (analogous to [no_repeats] in the\n exercise above), such that [repeats X l] asserts that [l] contains\n at least one repeated element (of type [X]). *)\n\nInductive repeats {X:Type} : list X -> Prop :=\n (* FILL IN HERE *)\n.\n\n(** Now here's a way to formalize the pigeonhole principle. List [l2]\n represents a list of pigeonhole labels, and list [l1] represents\n the labels assigned to a list of items: if there are more items\n than labels, at least two items must have the same label. This\n proof is much easier if you use the [excluded_middle] hypothesis\n to show that [appears_in] is decidable, i.e. [forall x\n l, (appears_in x l) \\/ ~ (appears_in x l)]. However, it is also\n possible to make the proof go through _without_ assuming that\n [appears_in] is decidable; if you can manage to do this, you will\n not need the [excluded_middle] hypothesis. *)\n\nTheorem pigeonhole_principle: forall (X:Type) (l1 l2:list X), \n excluded_middle -> \n (forall x, appears_in x l1 -> appears_in x l2) -> \n length l2 < length l1 -> \n repeats l1. \nProof.\n intros X l1. induction l1 as [|x l1'].\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* FILL IN HERE *)\n\n\n(* $Date: 2014-02-22 09:43:41 -0500 (Sat, 22 Feb 2014) $ *)\n", "meta": {"author": "folone", "repo": "sf-building", "sha": "dda0f5a9a465b4fc9b879bc1e5ebeb460dca05b8", "save_path": "github-repos/coq/folone-sf-building", "path": "github-repos/coq/folone-sf-building/sf-building-dda0f5a9a465b4fc9b879bc1e5ebeb460dca05b8/MoreLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474246069457, "lm_q2_score": 0.9207896802383029, "lm_q1q2_score": 0.8790294968441489}} {"text": "Require Import SetoidClass.\n\nModule Type T.\nClass group (G: Set) `(Setoid G) (opG: G -> G -> G) (zeroG: G) (invG: G -> G) :=\n{\n g_assoc : forall {a b c}, opG (opG a b) c == opG a (opG b c);\n g_identity : forall {a}, opG zeroG a == a;\n g_inverse : forall {a}, opG (invG a) a == zeroG\n}.\nCheck group.\n\nClass abelian_group (G: Set) (sG: Setoid G) (opG: G -> G -> G) (zeroG: G) (invG: G -> G)\n (gG: (@group G sG opG zeroG invG)) :=\n{\n g_comm : forall {a b: G}, (opG a b) == (opG b a)\n}.\nCheck abelian_group.\n\n\nClass group_hom (G H: Set) (h: G -> H) (sG: Setoid G) (opG: G -> G -> G) (zeroG: G) (invG: G -> G)\n (sH: Setoid H) (opH: H -> H -> H) (zeroH: H) (invH: H -> H) \n `(@group G sG opG zeroG invG)\n `(@group H sH opH zeroH invH)\n:=\n{\n h1 : forall (a b: G), h (opG a b) == opH (h a) (h b);\n h2 : forall (a: G), h (invG a) == invH (h a)\n}.\nCheck group_hom.\n\n\nDefinition kernel (G H: Set) (h: G -> H) (sG: Setoid G) (opG: G -> G -> G) (zeroG: G) (invG: G -> G)\n (sH: Setoid H) (opH: H -> H -> H) (zeroH: H) (invH: H -> H)\n (gG: (@group G sG opG zeroG invG))\n (gH: (@group H sH opH zeroH invH))\n `(@group_hom G H h sG opG zeroG invG sH opH zeroH invH gG gH) := { u: G | h u == zeroH }.\nCheck kernel.\n\nDefinition image (G H: Set) (h: G -> H) (sG: Setoid G) (opG: G -> G -> G) (zeroG: G) (invG: G -> G)\n (sH: Setoid H) (opH: H -> H -> H) (zeroH: H) (invH: H -> H)\n (u: G)\n (gG: (@group G sG opG zeroG invG))\n (gH: (@group H sH opH zeroH invH))\n `(@group_hom G H h sG opG zeroG invG sH opH zeroH invH gG gH) := { hu: H | hu == h u}.\nCheck image.\n\n(** subgroups\nDefinition subgroup (G: Set) (sG: Setoid G) (opG: G -> G -> G) (zeroG: G) (invG: G -> G)\n (gG: (@group G sG opG zeroG invG))\n (P: G -> Prop)\n {sSG: Setoid { u: G | P u }} \n {opSG: { u: G | P u } -> { u: G | P u } -> { u: G | P u }} \n {zeroSG: { u: G | P u }} \n {invSG: { u: G | P u } -> { u: G | P u }} := (@group { u: G | P u } sSG opSG zeroSG invSG).\nCheck subgroup.\n**)\n\nRequire Import Psatz.\nRequire Import Nsatz.\nRequire Import ZArith.\nOpen Scope Z_scope.\n\nDefinition zadd (n m: Z) := n + m.\nDefinition zid := 0%Z.\nDefinition zinv (n: Z) := -n.\n\nProgram Instance Zeq_setoid : Setoid Z :=\n { equiv := eq ; setoid_equiv := eq_equivalence }.\n\n(** < Z, +, 0, ^{-1+} > as a group instance **)\nProgram Instance group_integers: (@group Z (Zeq_setoid) zadd zid zinv).\nObligation 1. unfold zadd. omega. Qed.\nNext Obligation. unfold zadd, zinv, zid. omega. Qed.\nCheck group_integers.\n\nProgram Instance abelian_group_integers: (@abelian_group Z (Zeq_setoid) zadd zid zinv group_integers).\nObligation 1. unfold zadd. omega. Qed.\nCheck abelian_group_integers.\n\nRequire Import QArith.\nOpen Scope Q_scope.\n\nDefinition qadd (n m: Q) := n + m.\nDefinition qid := 0%Q.\nDefinition qinv (n: Q) := -n.\n\nProgram Instance Qeq_setoid : Setoid Q :=\n { equiv := Qeq ; setoid_equiv := Q_Setoid}.\n\n(** < Q, +, 0, ^{-1+} > as a group instance **)\nProgram Instance group_rationals: (@group Q (Qeq_setoid) qadd qid qinv).\nObligation 1. unfold qadd. symmetry. apply Qplus_assoc. Qed.\nNext Obligation. unfold qadd, qid. apply Qplus_0_l. Qed.\nNext Obligation. unfold qadd, qid, qinv. specialize (@Qplus_opp_r (-a)). intros.\n rewrite Qopp_involutive in H. exact H. Qed.\nCheck group_rationals.\n\nRequire Import ZArith_base.\nRequire Import Rdefinitions.\nRequire Import Coq.Reals.Raxioms.\nLocal Open Scope R_scope.\n\nDefinition radd (n m: R) := n + m.\nDefinition rid := 0.\nDefinition rinv (n: R) := -n.\n\nProgram Instance Req_setoid : Setoid R :=\n { equiv := (eq(A:=R)) ; setoid_equiv := eq_equivalence}.\n\n(** < R, +, 0, ^{-1+} > as a group instance **)\nProgram Instance group_reals: (@group R (Req_setoid) radd rid rinv).\nObligation 1. unfold radd. apply Rplus_assoc. Qed.\nNext Obligation. unfold radd, rinv, rid. apply Rplus_0_l. Qed.\nNext Obligation. unfold radd, rinv, rid. specialize (@Rplus_opp_r a).\n intros. rewrite <- H. apply Rplus_comm. Qed.\nCheck group_reals.\n\nEnd T.", "meta": {"author": "ekiciburak", "repo": "algebraic-groups-rings-fields", "sha": "3f260eaf6f5069b594c8ad2e5fd0c38e972c50c1", "save_path": "github-repos/coq/ekiciburak-algebraic-groups-rings-fields", "path": "github-repos/coq/ekiciburak-algebraic-groups-rings-fields/algebraic-groups-rings-fields-3f260eaf6f5069b594c8ad2e5fd0c38e972c50c1/src/groups.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.9273632976542184, "lm_q1q2_score": 0.8785664088030913}} {"text": "\nInductive nat :=\n | zero : nat\n | S : nat -> nat.\n\n\nFixpoint plus (m n : nat) :=\n match n with\n | zero => m\n | S n' => S (plus m n')\n end.\n\n\nLemma n_plus_zero_is_n :\n forall n, plus n zero = n.\nProof.\n intros n0.\n simpl.\n reflexivity.\nQed.\n\nLemma zero_plus_n_is_n :\n forall n, plus zero n = n.\nProof.\n induction n.\n - simpl. reflexivity.\n - simpl. rewrite IHn.\n reflexivity.\nQed.\n\nLemma plus_comm:\n forall m n, plus m n = plus n m.\nProof.\n induction m.\n - intros.\n rewrite n_plus_zero_is_n.\n rewrite zero_plus_n_is_n.\n reflexivity.\n - induction n.\n -- simpl.\n rewrite zero_plus_n_is_n.\n reflexivity.\n -- simpl.\n rewrite IHn.\n rewrite <- IHm.\n simpl.\n rewrite IHm.\n reflexivity.\nQed.\n\n\n\n\nFixpoint mult (n m : nat) : nat :=\n match n with\n | zero => zero\n | S n' => plus m (mult n' m)\n end.\n\n\nFixpoint minus (n m:nat) : nat :=\n match n, m with\n | zero , _ => zero\n | S _ , zero => n\n | S n', S m' => minus n' m'\n end.\n\nNotation \"x + y\" := (plus x y)\n (at level 50, left associativity)\n : nat.\nNotation \"x - y\" := (minus x y)\n (at level 50, left associativity)\n : nat.\nNotation \"x * y\" := (mult x y)\n (at level 40, left associativity)\n : nat.\n\nCheck ((0 + 1) + 1).\n\n", "meta": {"author": "AlexDolhescu", "repo": "Coq", "sha": "81daf29eeef8d85797f6a96773da4bb8f6ec8476", "save_path": "github-repos/coq/AlexDolhescu-Coq", "path": "github-repos/coq/AlexDolhescu-Coq/Coq-81daf29eeef8d85797f6a96773da4bb8f6ec8476/SF I/nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995762509215, "lm_q2_score": 0.9073122282528899, "lm_q1q2_score": 0.8763724967967458}} {"text": "Require Export Basics.\n\nTheorem plus_n_O_secondtry' : forall n : nat,\n n = n + 0.\nProof.\n intros n. destruct n as [| n'].\n - (* n = 0 *)\n reflexivity. (* so far so good... *)\n - (* n = S n' *)\n simpl. (* ...but here we are stuck again *)\nAbort.\n\n\nTheorem plus_n_O: forall n: nat,\n n = n + 0 .\nProof.\n intros n.\n induction n as [| n' IHn'].\n (* 0 = 0 + 0 *)\n - reflexivity.\n (* S n' = S n' + 0 *)\n - simpl. rewrite <- IHn'. simpl. simpl. reflexivity.\nQed.\n\nTheorem minus_diag: forall n : nat,\n minus n n = 0 .\nProof.\n intros n.\n induction n as [| n' IHn'].\n - simpl. reflexivity.\n - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n(*Exercise: 2 stars, recommended (basic_induction) *)\n\nTheorem mult_0_r: forall n : nat,\n n * 0 = 0 .\nProof.\n intros n.\n induction n as [|n' IHn'].\n - simpl. reflexivity.\n - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n\nTheorem plus_n_Sm: forall n m : nat,\n S (n + m) = n + ( S m ) .\nProof.\n intros n m.\n induction n as [|n' IHn'].\n induction m as [|m' IHm'].\n (* S (0 + 0) = 0 + 1 *)\n - simpl. reflexivity.\n (* S (0 + S m') = 0 + S (S m') *)\n - simpl. reflexivity.\n (* S (S n' + m) = S n' + S m *)\n - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem plus_comm: forall n m : nat,\n n + m = m + n .\nProof.\n intros n m.\n induction n as [|n' IHn'].\n induction m as [|m' IHm'].\n (* 0 + 0 = 0 + 0 *)\n - simpl. reflexivity.\n (* 0 + S m' = S m' + 0 *)\n - simpl. rewrite <- IHm'. simpl. reflexivity.\n (* \n n', m: nat\n IHn': n' + m = m + n' \n S n' + m = m + S n' \n *)\n - simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.\nQed.\n\n (*\n 1/4\n 0 + (0 + 0) = 0 + 0 + 0\n 2/4\n 0 + (0 + S p') = 0 + 0 + S p'\n 3/4\n 0 + (S m' + p) = 0 + S m' + p\n 4/4\n S n' + (m + p) = S n' + m + p\n *)\nTheorem plus_assoc : forall n m p : nat,\n n + ( m + p) = (n + m) + p .\nProof.\n intros n m p.\n induction n as [|n' IHn'].\n induction m as [|m' IHm'].\n induction p as [|p' IHp'].\n - simpl. reflexivity.\n - simpl. reflexivity.\n - simpl. reflexivity.\n - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "xiongxin", "repo": "software-foundations", "sha": "b4b641f35ca3c7f3a68aba17708b638f4eb8521c", "save_path": "github-repos/coq/xiongxin-software-foundations", "path": "github-repos/coq/xiongxin-software-foundations/software-foundations-b4b641f35ca3c7f3a68aba17708b638f4eb8521c/Basics/IfCurrent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.9314625022115511, "lm_q1q2_score": 0.8763103785385191}} {"text": "From mathcomp Require Import ssreflect.\n\n(*| We continue working with our own definitions of Booleans and natural numbers |*)\n\nModule My.\n\nInductive bool : Type :=\n| true\n| false.\n\nDefinition negb :=\n fun (b : bool) =>\n match b with\n | true => false\n | false => true\n end.\n\n(** * Exercise 1 : boolean functions *)\n\n(*| 1a. Define `orb` function implementing boolean disjunction and test it\n_thoroughly_ using the command `Compute`. |*)\n\nDefinition orb (b c : bool) : bool :=\n match b with\n | true => true\n | false => c\n end. \n\nCompute orb true false. \nCompute orb false true. \nCompute orb true true. \nCompute orb false false. \n\n(*| 1b. Define `addb` function implementing _exclusive_ boolean disjunction.\nTry to come up with more than one definition (try to make it interesting\nand don't just swap the variables) and explore its reduction behavior\nin the presence of symbolic variables. |*)\n\nDefinition addb (b c : bool) : bool :=\n match b with\n | true => negb c\n | false => c\n end.\nVariable t : bool.\nCompute addb true false. \nCompute addb false true . \nCompute addb true true. \nCompute addb false false. \n\nCompute addb t false. \nCompute addb false t. \nCompute addb true t. \nCompute addb t true. \n\n(*| 1c. Define `eqb` function implementing equality on booleans, i.e. `eqb b c`\nmust return `true` if and only iff `b` is equal to `c`. Add unit tests. |*)\n\nDefinition eqb (b c : bool) : bool := negb (addb b c).\n\nCompute eqb true true.\nCompute eqb true false.\nCompute eqb false true.\nCompute eqb false false.\n\n\n(** * Exercise 2 : arithmetic *)\n\nInductive nat : Type :=\n| O\n| S of nat.\n\n\n(*| 2a. Define `dec2` function of type `nat -> nat` which takes a natural\nnumber and decrements it by 2, e.g. for the number `5` it must return `3`. Write\nsome unit tests for `dec2`. What should it return for `1` and `0`? |*)\n\nDefinition dec2 (n : nat) : nat :=\n match n with\n | O => O\n | S O => O\n | S (S p) => p\n end.\n\nDefinition pred (n : nat) : nat :=\n match n with\n | O => O\n | S p => p\n end.\n\nCompute dec2 O.\nCompute dec2 (S O).\nCompute dec2 (S (S O)).\nCompute dec2 (S (S (S O))).\n\n(*| 2b. Define `subn` function of type `nat -> nat -> nat` which takes two\nnatural numbers `m` and `n` and returns the result of subtracting `n` from `m`.\nE.g. `subn 5 3` returns `2`. Write some unit tests. |*)\n\nFixpoint subn (m n : nat) : nat :=\n match n with\n | O => m\n | S p => pred (subn m p)\n end.\n\nCompute subn (S (S (S O))) (S (S (S O))).\nCompute subn (S (S O)) (S (S (S O))).\nCompute subn (S (S (S O))) (S O).\n\n(*| 2c. Define an `muln` function of type `nat -> nat -> nat` which takes two\nnatural numbers `m` and `n` and returns the result of their multiplication.\nWrite some unit tests. |*)\n\nFixpoint muln (m n : nat) : nat := ...\n\nCompute muln ...\n...\nCompute muln ...\n\n(** 2d. Implement equality comparison function `eqn` on natural numbers of\ntype `nat -> nat -> bool`. It returns true if and only if the input numbers are\nequal. *)\n\nFixpoint eqn (m n : nat) : bool := ...\n\nCompute eqn ...\n...\nCompute eqn ...\n\n(** 2e. Implement less-or-equal comparison function `leq` on natural numbers of\ntype `nat -> nat -> bool`. `leq m n` returns `true` if and only if `m` is less\nthan or equal to `n`. Your solution must not use recursion but you may reuse any\nof the functions you defined in this module so far. *)\n\nDefinition leq (m n : nat) : bool := ...\n\nCompute leq ...\n...\nCompute leq ...\n\n\n(*| ---------------------------------------------------------------------------- |*)\n\n\n(*| EXTRA problems: feel free to skip these. If you need to get credit for this\nclass: extra exercises do not influence your grade negatively if you skip them.\n|*)\n\n(*| Ea: implement division (`divn`) on natural numbers and write some unit tests\nfor it. |*)\n\nEnd My.", "meta": {"author": "hardworkar", "repo": "learn-coq", "sha": "d25318e5c202bd1a99755f287a1b4c8dee576ddd", "save_path": "github-repos/coq/hardworkar-learn-coq", "path": "github-repos/coq/hardworkar-learn-coq/learn-coq-d25318e5c202bd1a99755f287a1b4c8dee576ddd/hw01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.9416541618444, "lm_q1q2_score": 0.876169890524434}} {"text": "(** * Lists: Working with Structured Data *)\n\n(*Require Export Induction.\n*)\nModule NatList. \n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as in this definition: *)\n\nInductive natprod : Type :=\n pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\n(** We can construct an element of [natprod] like this: *)\n\nCheck (pair 3 5).\n\n(** *** *)\n\n(** Here are two simple function definitions for extracting the\n first and second components of a pair. (The definitions also\n illustrate how to do pattern matching on two-argument\n constructors.) *)\n\nDefinition fst (p : natprod) : nat := \n match p with\n | pair x y => x\n end.\nDefinition snd (p : natprod) : nat := \n match p with\n | pair x y => y\n end.\n\nEval compute in (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** *** *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this notation is provided as part of the standard\n library): *)\n\nEval compute in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat := \n match p with\n | (x,y) => x\n end.\nDefinition snd' (p : natprod) : nat := \n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod := \n match p with\n | (x,y) => (y,x)\n end.\n\n(** *** *)\n\n(** Let's try and prove a few simple facts about pairs. If we\n state the lemmas in a particular (and slightly peculiar) way, we\n can prove them with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** Note that [reflexivity] is not enough if we state the lemma in a\n more natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** *** *)\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct].\n\n Notice that, unlike for [nat]s, [destruct] doesn't generate an\n extra subgoal here. That's because [natprod]s can only be\n constructed in one way. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. \nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n describe the type of _lists_ of numbers like this: \"A list is\n either the empty list or else a pair of a number and another\n list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n\n(** *** *)\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following two declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n but in case you are interested, here is roughly what's going on.\n\n The [right associativity] annotation tells Coq how to parenthesize\n expressions involving several uses of [::] so that, for example,\n the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\nNotation \"x + y\" := (plus x y) \n (at level 50, left associativity).\n The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (By the way, it's worth noting in passing that expressions like \"[1\n + 2 :: [3]]\" can be a little confusing when you read them in a .v\n file. The inner brackets, around 3, indicate a list, but the outer\n brackets, which are invisible in the HTML rendering, are there to\n instruct the \"coqdoc\" tool that the bracketed part should be\n displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(** *** Repeat *)\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist := \n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(** *** Length *)\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat := \n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(** *** Append *)\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist := \n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y) \n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\"). \n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\n(** *** Head (with default) and Tail *)\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil \n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => match h with\n | O => nonzeros t\n | S n => h :: (nonzeros t)\n end\n end.\n\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n simpl. reflexivity. Qed. \n\nFixpoint oddb (n:nat) : bool :=\n match n with\n | O => false\n | S O => true\n | S (S n') => oddb n'\n end.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => match oddb h with\n | true => h :: (oddmembers t)\n | false => oddmembers t\n end\n end.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\n simpl. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n match l with\n | nil => O\n | h :: t => match oddb h with\n | true => S (countoddmembers t)\n | flase => countoddmembers t\n end\n end.\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\n simpl. reflexivity. Qed.\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\n simpl. reflexivity. Qed.\nExample test_countoddmembers3: countoddmembers nil = 0.\n simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => match l2 with\n | nil => nil\n | h :: t => l2\n end\n | h :: t => match l2 with\n | nil => l1\n | h' :: t' => h :: h' :: (alternate t t')\n end\n end.\n\nExample test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n simpl. reflexivity. Qed.\nExample test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].\n simpl. reflexivity. Qed.\nExample test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].\n simpl. reflexivity. Qed.\nExample test_alternate4: alternate [] [20;30] = [20;30].\n simpl. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n multiple times instead of just once. One reasonable\n implementation of bags is to represent a bag of numbers as a\n list. *)\n\nDefinition bag := natlist. \n\n(** **** Exercise: 3 stars (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint eq_nat n m : bool :=\n match n, m with\n | O, O => true\n | O, S _ => false\n | S _, O => false\n | S n1, S m1 => eq_nat n1 m1\n end.\n\nFixpoint count (v:nat) (s:bag) : nat := \n match s with\n | nil => O\n | h :: t => match eq_nat h v with \n | true => S (count v t)\n | false => count v t\n end\n end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\n simpl. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\n simpl. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\n\nDefinition sum : bag -> bag -> bag := \n alternate.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\n simpl. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := \n v :: s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\n simpl. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\n simpl. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool := \n match count v s with \n | O => false\n | S n => true\n end.\n\nExample test_member1: member 1 [1;4;1] = true.\n reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\n reflexivity. Qed.\n(** [] *)\n\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n (* When remove_one is applied to a bag without the number to remove,\n it should return the same bag unchanged. *)\n match s with\n | nil => s\n | h :: t => match eq_nat v h with\n | true => t\n | false => h :: (remove_one v t)\n end\n end. \n\nExample test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n simpl. reflexivity. Qed.\nExample test_remove_one2: count 5 (remove_one 5 [2;1;4;1]) = 0.\n simpl. reflexivity. Qed.\nExample test_remove_one3: count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n simpl. reflexivity. Qed.\nExample test_remove_one4: count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n simpl. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with\n | nil => s\n | h :: t => match eq_nat v h with\n | true => remove_all v t\n | false => h :: (remove_all v t)\n end\n end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n simpl. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\n simpl. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n simpl. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n simpl. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n match s1 with\n | nil => true\n | h :: t => match count h s2 with\n | O => false\n | S n => (subset t (remove_one h s2))\n end\n end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\n simpl. reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\n simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (bag_theorem) *)\n(** Write down an interesting theorem [bag_theorem] about bags involving\n the functions [count] and [add], and prove it. Note that, since this\n problem is somewhat open-ended, it's possible that you may come up\n with a theorem which is true, but whose proof requires techniques\n you haven't learned yet. Feel free to ask for help if you get\n stuck! *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match position\n in the definition of [app], allowing the match itself to be\n simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n (*Case \"l = nil\".*)\n reflexivity.\n (*Case \"l = cons n l'\".*) \n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n It is very important to work through the details of each one,\n using Coq and thinking about what each step achieves. Otherwise\n it is more or less guaranteed that the exercises will make no\n sense... *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n perhaps a little less familiar than standard natural number\n induction, but the basic idea is equally simple. Each [Inductive]\n declaration defines a set of data values that can be built up from\n the declared constructors: a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to a number; a\n list can be either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two things together establish the\n truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist, \n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3). \nProof.\n intros l1 l2 l3. induction l1 as [| n l1'].\n (*Case \"l1 = nil\".*)\n reflexivity.\n (*Case \"l1 = cons n l1'\".*)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n static written document -- it is easy to see what's going on if\n you are reading the proof in an interactive Coq session and you\n can see the current goal and context at each point, but this state\n is not visible in the written-down parts of the Coq proof. So a\n natural-language proof -- one written for human readers -- will\n need to include more explicit signposts; in particular, it will\n help the reader stay oriented if we remind them exactly what the\n induction hypothesis is in the second case. *)\n\n(** *** Informal version *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3], \n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n (the induction hypothesis). We must show\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]] \n By the definition of [++], this follows from\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n which is immediate from the induction hypothesis. []\n*)\n\n(** *** Another example *)\n(**\n Here is a similar example to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist, \n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1'].\n (*Case \"l1 = nil\".*)\n reflexivity.\n (*Case \"l1 = cons\".*)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n\n(** *** Reversing a list *)\n(** For a slightly more involved example of an inductive proof\n over lists, suppose we define a \"cons on the right\" function\n [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist := \n match l with\n | nil => [v]\n | h :: t => h :: (snoc t v)\n end.\n\n(** ... and use it to define a list-reversing function [rev]\n like this: *)\n\nFixpoint rev (l:natlist) : natlist := \n match l with\n | nil => nil\n | h :: t => snoc (rev t) h\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** *** Proofs about reverse *)\n(** Now let's prove some more list theorems using our newly\n defined [snoc] and [rev]. For something a little more challenging\n than the inductive proofs we've seen so far, let's prove that\n reversing a list does not change its length. Our first attempt at\n this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n (*Case \"l = []\".*)\n reflexivity.\n (*Case \"l = n :: l'\".*)\n (* This is the tricky case. Let's begin as usual \n by simplifying. *)\n simpl. \n (* Now we seem to be stuck: the goal is an equality \n involving [snoc], but we don't have any equations \n in either the immediate context or the global \n environment that have anything to do with [snoc]! \n\n We can make a little progress by using the IH to \n rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation about [snoc] that would have\n enabled us to make progress and prove it as a separate lemma. \n*)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n length (snoc l n) = S (length l).\nProof.\n intros n l. induction l as [| n' l'].\n (*Case \"l = nil\".*)\n reflexivity.\n (*Case \"l = cons n' l'\".*)\n simpl. rewrite -> IHl'. reflexivity. Qed. \n\n(**\n Note that we make the lemma as _general_ as possible: in particular,\n we quantify over _all_ [natlist]s, not just those that result\n from an application of [rev]. This should seem natural, \n because the truth of the goal clearly doesn't depend on \n the list having been reversed. Moreover, it is much easier\n to prove the more general property. \n*)\n \n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n (*Case \"l = nil\".*)\n reflexivity.\n (*Case \"l = cons\".*)\n simpl. rewrite -> length_snoc. \n rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems: \n\n _Theorem_: For all numbers [n] and lists [l],\n [length (snoc l n) = S (length l)].\n \n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (snoc [] n) = S (length []),\n which follows directly from the definitions of\n [length] and [snoc].\n\n - Next, suppose [l = n'::l'], with\n length (snoc l' n) = S (length l').\n We must show\n length (snoc (n' :: l') n) = S (length (n' :: l')).\n By the definitions of [length] and [snoc], this\n follows from\n S (length (snoc l' n)) = S (S (length l')),\n]] \n which is immediate from the induction hypothesis. [] *)\n \n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n \n _Proof_: By induction on [l]. \n\n - First, suppose [l = []]. We must show\n length (rev []) = length [],\n which follows directly from the definitions of [length] \n and [rev].\n \n - Next, suppose [l = n::l'], with\n length (rev l') = length l'.\n We must show\n length (rev (n :: l')) = length (n :: l').\n By the definition of [rev], this follows from\n length (snoc (rev l') n) = S (length l')\n which, by the previous lemma, is the same as\n S (length (rev l')) = S (length l').\n This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n and pedantic. After the first few, we might find it easier to\n follow proofs that give fewer details (since we can easily work\n them out in our own minds or on scratch paper if necessary) and\n just highlight the non-obvious steps. In this more compressed\n style, the above proof might look more like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that\n length (snoc l n) = S (length l)\n for any [l]. This follows by a straightforward induction on [l].\n The main property now follows by another straightforward\n induction on [l], using the observation together with the\n induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and on how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for\n present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, using [rewrite], and later we will see other ways\n of reusing previous theorems. But in order to refer to a theorem,\n we need to know its name, and remembering the names of all the\n theorems we might ever want to use can become quite difficult! It\n is often hard even to remember what theorems have been proven,\n much less what they are named.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following to\n see a list of theorems that we have proved about [rev]: *)\n\n(* SearchAbout rev. *)\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the course; it can save you a lot of time! *)\n\n(** Also, if you are using ProofGeneral, you can run [SearchAbout]\n with [C-c C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist, \n l ++ [] = l. \nProof.\n intros. induction l as [|n l'].\n (*case l=nil*)\n simpl. auto.\n (*case l=n l'*)\n simpl. rewrite -> IHl'. auto.\nQed.\n\nLemma rev_snoc : forall l n,\n rev (snoc l n) = n :: (rev l).\nProof.\n intros. \n induction l as [|m l'].\n (*case l=nil*)\n simpl. reflexivity.\n (*case l=m l'*)\n simpl. rewrite -> IHl'.\n simpl. reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros. \n induction l as [|n l'].\n (*case l=nil*)\n simpl. reflexivity.\n (*case l=n l'*)\n simpl. rewrite -> rev_snoc.\n rewrite -> IHl'. reflexivity.\nQed.\n \n\n\n(** There is a short solution to the next exercise. If you find\n yourself getting tangled up, step back and try to look for a\n simpler way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros. \n rewrite -> app_assoc.\n rewrite -> app_assoc.\n reflexivity.\nQed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n snoc l n = l ++ [n].\nProof.\n intros. induction l as [|m l'].\n (*case l=nil*)\n simpl. reflexivity.\n (*case l=m l'*)\n simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nLemma snoc_asoc : forall l1 l2 n,\n snoc (l2 ++ l1) n = l2 ++ (snoc l1 n).\nProof.\n intros. induction l2 as [|m l2'].\n (*case l2=nil*)\n simpl. reflexivity.\n (*case l2=m l2'*)\n simpl. rewrite -> IHl2'. reflexivity.\nQed.\n\nTheorem distr_rev : forall l1 l2 : natlist,\n rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n intros. induction l1 as [|n l1'].\n (*case l1=nil*)\n simpl. rewrite -> app_nil_end. reflexivity.\n (*case l1=n l1'*)\n simpl. rewrite -> IHl1'.\n rewrite -> snoc_asoc. reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros. induction l1 as [|n l1'].\n (*case l1=nil*)\n simpl. reflexivity.\n (*case l1=n l1'*)\n destruct n as [|n'].\n (*case n=O*)\n simpl. rewrite -> IHl1'. reflexivity.\n (*case n=S n'*)\n simpl. rewrite -> IHl1'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_nat (n m : nat) : bool :=\n match n with\n | O => match m with\n | O => true\n | S m' => false\n end\n | S n' => match m with\n | O => false\n | S m' => beq_nat n' m'\n end\n end.\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n match l1 with\n | nil => match l2 with\n | nil => true\n | h :: t => false \n end\n | h :: t => match (beq_nat h (hd 0 l2)) with \n | true => beq_natlist t (tl l2)\n | false => false\n end\n end.\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\n simpl. reflexivity. Qed.\nExample test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\n simpl. reflexivity. Qed.\nExample test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.\n simpl. reflexivity. Qed.\n\nLemma beq_nat_refl : forall n:nat,\n beq_nat n n = true.\nProof.\n intros.\n induction n as [|n'].\n (*case n=O*)\n reflexivity.\n (*case n=S n'*)\n simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\n intros. induction l as [|n l'].\n (*case l=nil*)\n simpl. reflexivity.\n (*case l=n l'*)\n simpl. rewrite -> beq_nat_refl.\n rewrite <- IHl'.\n reflexivity.\nQed.\n\n(** [] *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 2 stars (list_design) *)\n(** Design exercise: \n - Write down a non-trivial theorem [cons_snoc_app]\n involving [cons] ([::]), [snoc], and [app] ([++]). \n - Prove it. *) \n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n definitions about bags earlier in the file. *)\n\nFixpoint ble_nat (n m : nat) : bool :=\n match n with\n | O => true\n | S n' =>\n match m with\n | O => false\n | S m' => ble_nat n' m'\n end\n end.\n\nTheorem count_member_nonzero : forall (s : bag),\n ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n intros. simpl. reflexivity.\nQed.\n\n(** The following lemma about [ble_nat] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n ble_nat n (S n) = true.\nProof.\n intros n. induction n as [| n'].\n (*Case \"0\".*) \n simpl. reflexivity.\n (*Case \"S n'\".*)\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n intros. induction s as [|n s'].\n (*s=nil*)\n simpl. reflexivity.\n (*s=n s'*)\n induction n as [| n'].\n (*n=0*)\n simpl. rewrite -> ble_n_Sn.\n reflexivity.\n (*n=S n'*)\n simpl. rewrite -> IHs'.\n reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *) \n(** Write down an interesting theorem [bag_count_sum] about bags \n involving the functions [count] and [sum], and prove it.*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,*)\n\n(*There is a hard way and an easy way to solve this exercise.\n*)\n\nTheorem rev_injective: forall (l1 l2 : natlist), \n rev l1 = rev l2 -> l1 = l2.\nProof.\n intros. rewrite <- rev_involutive. \n rewrite <- H. \n rewrite -> rev_involutive.\n reflexivity.\nQed.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n\n(** One use of [natoption] is as a way of returning \"error\n codes\" from functions. For example, suppose we want to write a\n function that returns the [n]th element of some list. If we give\n it type [nat -> natlist -> nat], then we'll have to return some\n number when the list is too short! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with \n | true => a \n | false => index_bad (pred n) l' \n end\n end.\n\n(** *** *)\n(** On the other hand, if we give it type [nat -> natlist ->\n natoption], then we can return [None] when the list is too short\n and [Some a] when the list has enough members and [a] appears at\n position [n]. *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption. \n\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => match beq_nat n O with \n | true => Some a\n | false => index (pred n) l' \n end\n end.\n\nExample test_index1 : index 0 [4;5;6;7] = Some 4.\nProof. reflexivity. Qed.\nExample test_index2 : index 3 [4;5;6;7] = Some 7.\nProof. reflexivity. Qed.\nExample test_index3 : index 10 [4;5;6;7] = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n small feature of Coq's programming language: conditional\n expressions... *)\n\n(** *** *)\n\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => if beq_nat n O then Some a else index' (pred n) l'\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_opt (l : natlist) : natoption :=\n match l with\n | nil => None\n | a :: l' => Some a\n end.\n\nExample test_hd_opt1 : hd_opt [] = None.\n Proof. reflexivity. Qed.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\n Proof. reflexivity. Qed.\n\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\n Proof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_opt l).\nProof.\n intros. destruct l as [|n l'].\n (*l=nil*)\n simpl. reflexivity.\n (*l=n l'*)\n simpl. reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Dictionaries *)\n\n(** As a final illustration of how fundamental data structures\n can be defined in Coq, here is the declaration of a simple\n [dictionary] data type, using numbers for both the keys and the\n values stored under these keys. (That is, a dictionary represents\n a finite map from numbers to numbers.) *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n | empty : dictionary \n | record : nat -> nat -> dictionary -> dictionary. \n\n(** This declaration can be read: \"There are two ways to construct a\n [dictionary]: either using the constructor [empty] to represent an\n empty dictionary, or by applying the constructor [record] to\n a key, a value, and an existing [dictionary] to construct a\n [dictionary] with an additional key to value mapping.\" *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n (record key value d).\n\n(** Here is a function [find] that searches a [dictionary] for a\n given key. It evaluates evaluates to [None] if the key was not\n found and [Some val] if the key was mapped to [val] in the\n dictionary. If the same key is mapped to multiple values, [find]\n will return the first one it finds. *)\n\nFixpoint find (key : nat) (d : dictionary) : natoption := \n match d with \n | empty => None\n | record k v d' => if (beq_nat key k) \n then (Some v) \n else (find key d')\n end.\n\n\n\n(** **** Exercise: 1 star (dictionary_invariant1) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n (find k (insert k v d)) = Some v.\nProof.\n intros. simpl.\n rewrite -> beq_nat_refl.\n reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),\n beq_nat m n = false -> find m d = find m (insert n o d).\nProof.\n intros. simpl. rewrite -> H. reflexivity.\nQed. \n(** [] *)\n\n\n\nEnd Dictionary.\n\nEnd NatList.\n\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)\n\n", "meta": {"author": "Sooram", "repo": "Software-Foundations", "sha": "9c668f5c8395919645406855cdc78a214afdafd1", "save_path": "github-repos/coq/Sooram-Software-Foundations", "path": "github-repos/coq/Sooram-Software-Foundations/Software-Foundations-9c668f5c8395919645406855cdc78a214afdafd1/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392797, "lm_q2_score": 0.936285000858894, "lm_q1q2_score": 0.8757509060829205}} {"text": "Require Export Nat.\n\n(* We will use the 'nat','bool' types here. *)\n\n(* Let's begin with an Example Theorem that we prove by Induction *)\nTheorem plus_n_O : forall n: nat,\nn = n + O.\nProof.\nintros n. induction n as [|n' IHn'].\n- reflexivity.\n- simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem minus_diag : forall n,\nminus n n = O.\nProof.\nintros n. induction n as [|n' IHn'].\n- simpl. reflexivity.\n- simpl. rewrite <- IHn'. reflexivity.\nQed.\n\n(* Exercise 1 : Basic Induction Exercises *)\nTheorem mult_O_r : forall n: nat,\nn * O = O.\nProof.\nintros n. induction n as [|n' IHn'].\n- simpl. reflexivity.\n- simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem plus_n_Sm : forall n m: nat,\nS (n + m) = n + (S m).\nProof.\nintros n m. induction n as [| n' IHn'].\n- simpl. reflexivity.\n- simpl. rewrite -> IHn'. simpl. reflexivity.\nQed.\n\nTheorem plus_comm : forall n m: nat,\nn + m = m + n.\nProof.\nintros n m. induction n as [| n' IHn'].\n- simpl. rewrite <- plus_n_O. reflexivity.\n- simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m o: nat,\nn + (m + o) = (n + m) + o.\nProof.\nintros n m o. induction n as [| n' IHn'].\n- simpl. reflexivity.\n- simpl. rewrite -> IHn'. simpl. reflexivity.\nQed.\n\n(* Exercise 2 : Induction on 'double_plus' *)\n\n(* The double function *)\nFixpoint double (n: nat) : nat :=\n match n with\n | O => O\n | S n' => S (S (double n'))\nend.\n\nLemma double_plus : forall n: nat,\ndouble n = n + n.\nProof.\nintros n. induction n as [|n' IHn'].\n- simpl. reflexivity.\n- simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. rewrite -> plus_comm. rewrite -> plus_n_Sm. reflexivity.\nQed.\n\n(* NOTE : 'destruct' enumerates *finite* possible values for a type *)\n(* NOTE : 'induction' sets up a proposition by having a base case proved, assuming the IH, and then proving a general statement *)\n\n(* Introductin of the 'assert' tactic : Refer to _local_ theorems in lexical-scope. *)\nTheorem mult_O_plus : forall n m: nat,\n(O + n) * m = n * m.\nProof.\nintros n m.\nassert (H: O + n = n). { reflexivity. }\nrewrite -> H.\nreflexivity.\nQed.\n\n(* Another use case of the 'assert' tactic is to allow flexible 'rewrite' by introducing hypotheses in a smarter way *)\nTheorem plus_rearrange : forall n m p q: nat,\n(n + m) + (p + q) = (m + n) + (p + q).\nProof.\nintros n m p q.\nassert (H: n + m = m + n). { rewrite -> plus_comm. reflexivity. }\nrewrite -> H.\nreflexivity.\nQed.\n\n(* Informal Proof : Commutativity of addition *)\n(* Goal : n + m = m + n *)\n(* Proof. *)\n(* intros n. induction n as [| n' IHn'] *)\n(* For n = O -> O + n = n + O -> {rewrite <- plus_n_O} -> O + n = n -> {simpl.} -> n = n -> {reflexivity.} *)\n(* For n = S n' -> S n' + m = m + S n' -> S(n' + m) = m + S n' -> {rewrite -> IHn'.} -> S(m + n') = m + S n' -> {rewrite -> plus_n_Sm} -> m + S n' = m + S n'-> {reflexivity.} *)\n(* Qed. *)\n\n(* Exercise 2 : More Exercises *)\n(* Main Theorem 1 *) \nTheorem plus_swap : forall n m p: nat,\nn + (m + p) = m + (n + p).\nProof.\nintros n m p.\nassert (H1: n + (m + p) = (n + m) + p). { rewrite -> plus_assoc. reflexivity. }\nassert (H2: m + (n + p) = (m + n) + p). { rewrite -> plus_assoc. reflexivity. }\nrewrite -> H1.\nrewrite -> H2.\nassert (H3: n + m = m + n). { rewrite -> plus_comm. reflexivity. }\nrewrite -> H3.\nreflexivity.\nQed.\n\nTheorem add_term_mult_succ : forall n m: nat,\nm + (m * n) = m * (S n).\nProof.\nintros n m. induction m as [|m' IHm'].\n- simpl. reflexivity.\n- simpl. rewrite <- IHm'. rewrite -> plus_swap. reflexivity.\nQed.\n\n(* Main Theorem 2 *) \nTheorem mult_comm : forall n m: nat,\nn * m = m * n.\nProof.\nintros n m. induction n as [|n' IHn'].\n- simpl. rewrite -> mult_O_r. simpl. reflexivity.\n- simpl. rewrite -> IHn'. rewrite -> add_term_mult_succ. reflexivity.\nQed.", "meta": {"author": "jssandh2", "repo": "coq-types", "sha": "bc844def91356335816a0c97b556d98a202165f6", "save_path": "github-repos/coq/jssandh2-coq-types", "path": "github-repos/coq/jssandh2-coq-types/coq-types-bc844def91356335816a0c97b556d98a202165f6/src/Proofs/Induction/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.9230391595405136, "lm_q1q2_score": 0.8751837608735954}} {"text": "From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat.\n\n(*** Exercise 1 *)\n\n(** 1a. Define [orb_my] function implementing boolean disjunction *)\n\nDefinition orb_my (b c : bool) : bool :=\n match b with\n | true => true\n | false => c\n end.\n\nCompute orb_my true false.\nCompute orb_my false true.\nCompute orb_my false false.\n\nPrint orb_my.\n\n(** 1b. Figure out the implementation of [orb] function in the standard library\n using Coq's interactive query mechanism *)\n\nPrint orb.\n\n(** 1c. What's the difference between the standard implementation and\n the following one? *)\n\nDefinition orb_table (b c : bool) : bool :=\n match b, c with\n | true, true => true\n | true, false => true\n | false, true => true\n | false, false => false\n end.\n\n(** Note: the above translates into nested pattern-matching, check this *)\n\nPrint orb_table.\n\n(** 1d. Define [addb_my] function implementing exclusive boolean disjunction.\n {The name [addb] comes from the fact this operation behaves like addition modulo 2}\n If you are already familiar with proofs in Coq, think of a prover friendly\n definition, if you are not -- experiment with how different implementations\n behave under symbolic execution. *)\n\nDefinition addb_my (b1 b2 : bool) : bool :=\n match b1 with\n | false => b2\n | true => ~~ b2\n end.\n\nVariable p : bool.\n\nCompute addb_my true p.\n\n(*** Exercise 2 *)\n\n(** 2a. Implement power function of two arguments [x] and [n],\n raising [x] to the power of [n] *)\n\nFixpoint power (x n : nat) : nat :=\n match n with\n | 0 => 1\n | 1 => x\n | n0.+1 => power (x * x) n0\n end.\n\nCompute power 3 0.\nCompute power 3 1.\nCompute power 3 2.\n\n(*** Exercise 3 *)\n\n(** 3a. Implement division on unary natural numbers *)\n\nFixpoint divn_my (n m : nat) : nat :=\n match n, m with\n | 0, _ => 0\n | _, 0 => 0\n | n0.+1, m0.+1 => if n0 >= m0 then 1 + divn_my (n0 - m0) m else 0\n end.\n\n(* Unit tests: *)\nCompute divn_my 0 0. (* = 0 *)\nCompute divn_my 1 0. (* = 0 *)\nCompute divn_my 0 3. (* = 0 *)\nCompute divn_my 1 3. (* = 0 *)\nCompute divn_my 2 3. (* = 0 *)\nCompute divn_my 3 3. (* = 1 *)\nCompute divn_my 8 3. (* = 2 *)\nCompute divn_my 42 1. (* = 42 *)\nCompute divn_my 42 2. (* = 21 *)\nCompute divn_my 42 3. (* = 14 *)\nCompute divn_my 42 4. (* = 10 *)\n\n\n(** 3b. Provide several unit tests using [Compute] vernacular command *)\n\n\n(*** Exercise 4 *)\n\n(** Use the [applyn] function defined during the lecture\n (or better its Mathcomp sibling called [iter]) define\n\n 4a. addition on natural numbers\n\n 4b. multiplication on natural numbers\n\n Important: don't use recursion, i.e. no [Fixpoint] / [fix] should be in your solution.\n*)\n\n(** Here is out definition of [applyn]: *)\nDefinition applyn (f : nat -> nat) :=\n fix rec (n : nat) (x : nat) :=\n if n is n'.+1 then rec n' (f x)\n else x.\n\nAbout applyn.\nAbout iter.\n\nDefinition add_rec (n m : nat) : nat :=\n iter n (fun a => a + 1) m.\n\nVariable n : nat.\nCompute add_rec 1 0.\nCompute add_rec 1 2.\nCompute add_rec 2 n.\n\nDefinition mul_rec (n m : nat) : nat :=\n match n with\n | 0 => 0\n | n0.+1 => iter n0 (plus m) m\n end.\n\nCompute mul_rec 0 3.\nCompute mul_rec 3 0.\nCompute mul_rec 2 3.\nCompute mul_rec 2 6.\nCompute mul_rec 3 8.\nCompute mul_rec 8 3.\nCompute mul_rec 8 n.\n", "meta": {"author": "4e6", "repo": "verification-intro", "sha": "1ff0436fff4fbb700ca1f252dbd7efea0e786339", "save_path": "github-repos/coq/4e6-verification-intro", "path": "github-repos/coq/4e6-verification-intro/verification-intro-1ff0436fff4fbb700ca1f252dbd7efea0e786339/homework/hw01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067276593031, "lm_q2_score": 0.9273632921335859, "lm_q1q2_score": 0.8740461418201844}} {"text": "(** * Lists: Working with Structured Data *)\n\n(* $Date: 2013-01-04 20:13:58 -0500 (Fri, 04 Jan 2013) $ *)\n\nRequire Export Induction.\n\nModule NatList. \n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of parameters -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as in this definition: *)\n\nInductive natprod : Type :=\n pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\n(** We can construct an element of [natprod] like this: *)\n\nEval simpl in (pair 3 5).\n\n(** Here are two simple function definitions for extracting the\n first and second components of a pair. (The definitions also\n illustrate how to do pattern matching on two-argument\n constructors.) *)\n\nDefinition fst (p : natprod) : nat := \n match p with\n | pair x y => x\n end.\nDefinition snd (p : natprod) : nat := \n match p with\n | pair x y => y\n end.\n\nEval simpl in (fst (pair 3 5)).\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this notation is provided as part of the standard\n library): *)\n\nEval simpl in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat := \n match p with\n | (x,y) => x\n end.\nDefinition snd' (p : natprod) : nat := \n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod := \n match p with\n | (x,y) => (y,x)\n end.\n\n(** Let's try and prove a few simple facts about pairs. If we\n state the lemmas in a particular (and slightly peculiar) way, we\n can prove them with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** But reflexivity is not enough if we state the lemma in a more\n natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAdmitted.\n\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct].\n\n Notice that, unlike for [nat]s, [destruct] doesn't generate an\n extra subgoal here. That's because [natprod]s can only be\n constructed in one way. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as (n,m). simpl. reflexivity. Qed.\n\n(** Notice that Coq allows us to use the notation we introduced\n for pairs in the \"[as]...\" pattern that tells it what variables to\n bind. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p. destruct p as (n, m). \n reflexivity.\n Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros p. destruct p as (n, m). \n reflexivity.\n Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n describe the type of _lists_ of numbers like this: \"A list is\n either the empty list or else a pair of a number and another\n list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following two declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n but in case you are interested, here is roughly what's going on.\n\n The [right associativity] annotation tells Coq how to parenthesize\n expressions involving several uses of [::] so that, for example,\n the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1,2,3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\nNotation \"x + y\" := (plus x y) \n (at level 50, left associativity).\n The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (By the way, it's worth noting in passing that expressions like \"[1\n + 2 :: [3]]\" can be a little confusing when you read them in a .v\n file. The inner brackets, around 3, indicate a list, but the outer\n brackets are there to instruct the \"coqdoc\" tool that the bracketed\n part should be displayed as Coq code rather than running text.\n These brackets don't appear in the generated HTML.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist := \n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat := \n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist := \n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y) \n (right associativity, at level 60).\n\nExample test_app1: [1,2,3] ++ [4,5] = [1,2,3,4,5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4,5] = [4,5].\nProof. reflexivity. Qed.\nExample test_app3: [1,2,3] ++ nil = [1,2,3].\nProof. reflexivity. Qed.\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tail] returns everything but the first\n element. Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tail (l:natlist) : natlist :=\n match l with\n | nil => nil \n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1,2,3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tail: tail [1,2,3] = [2,3].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, recommended (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with \n | nil => nil\n | h::tl => \n match h with \n | O => nonzeros tl\n | (S n) => (S n) :: (nonzeros tl)\n end\n end.\n\nExample test_nonzeros: nonzeros [0,1,0,2,3,0,0] = [1,2,3].\nProof. reflexivity. Qed.\n\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h::tl =>\n match (oddb h) with \n | false => oddmembers tl\n | true => h :: oddmembers tl\n end\n end.\n\nExample test_oddmembers: oddmembers [0,1,0,2,3,0,0] = [1,3].\n (* FILL IN HERE *) \nProof. simpl. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n match l with \n | nil => 0\n | h::tl =>\n match (oddb h) with \n | false => countoddmembers tl\n | true => S (countoddmembers tl)\n end\n end.\n\nExample test_countoddmembers1: countoddmembers [1,0,3,1,4,5] = 4.\n (* FILL IN HERE *) Proof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers2: countoddmembers [0,2,4] = 0.\n (* FILL IN HERE *) Proof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers3: countoddmembers nil = 0.\n (* FILL IN HERE *) Proof. simpl. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\nmatch l1 with\n | nil => l2\n | h::tl => match l2 with\n | nil => h::tl\n | h2::t2 => h::h2::(alternate tl t2)\n end\nend.\n\n\nExample test_alternate1: alternate [1,2,3] [4,5,6] = [1,4,2,5,3,6].\n (* FILL IN HERE *) Proof. reflexivity. Qed.\nExample test_alternate2: alternate [1] [4,5,6] = [1,4,5,6].\n Proof. reflexivity. Qed.\nExample test_alternate3: alternate [1,2,3] [4] = [1,4,2,3].\n Proof. reflexivity. Qed.\nExample test_alternate4: alternate [] [20,30] = [20,30].\n Proof. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n multiple times instead of just once. One reasonable\n implementation of bags is to represent a bag of numbers as a\n list. *)\n\nDefinition bag := natlist. \n\n(** **** Exercise: 3 stars, recommended (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat := \nmatch s with\n | nil => 0\n | h::tl => match beq_nat h v with\n | true => S (count v tl)\n | false => count v tl\n end\nend.\n(** All these proofs can be done just by [reflexivity]. *)\nExample test_count1: count 1 [1,2,3,1,4,1] = 3.\nProof. reflexivity. Qed.\nExample test_count2: count 6 [1,2,3,1,4,1] = 0.\nProof. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := \n (* FILL IN HERE *) app.\n\nExample test_sum1: count 1 (sum [1,2,3] [1,4,1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := v::s.\n\n\nExample test_add1: count 1 (add 1 [1,4,1]) = 3.\nProof. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1,4,1]) = 0.\nProof. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool := \nmatch count v s with \n |0 => false\n |_ => true\nend.\n\nExample test_member1: member 1 [1,4,1] = true.\nProof. reflexivity. Qed.\nExample test_member2: member 2 [1,4,1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n (* When remove_one is applied to a bag without the number to remove,\n it should return the same bag unchanged. *)\n (* FILL IN HERE *) admit.\n\nExample test_remove_one1: count 5 (remove_one 5 [2,1,5,4,1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_one2: count 5 (remove_one 5 [2,1,4,1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_one3: count 4 (remove_one 5 [2,1,4,5,1,4]) = 2.\n (* FILL IN HERE *) Admitted.\nExample test_remove_one4: \n count 5 (remove_one 5 [2,1,5,4,5,1,4]) = 1.\n (* FILL IN HERE *) Admitted.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n (* FILL IN HERE *) admit.\n\nExample test_remove_all1: count 5 (remove_all 5 [2,1,5,4,1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all2: count 5 (remove_all 5 [2,1,4,1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all3: count 4 (remove_all 5 [2,1,4,5,1,4]) = 2.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all4: count 5 (remove_all 5 [2,1,5,4,5,1,4,5,1,4]) = 0.\n (* FILL IN HERE *) Admitted.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n (* FILL IN HERE *) admit.\n\nExample test_subset1: subset [1,2] [2,1,4,1] = true.\n (* FILL IN HERE *) Admitted.\nExample test_subset2: subset [1,2,2] [2,1,4,1] = false.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (bag_theorem) *)\n(** Write down an interesting theorem about bags involving the\n functions [count] and [add], and prove it. Note that, since this\n problem is somewhat open-ended, it's possible that you may come up\n with a theorem which is true, but whose proof requires techniques\n you haven't learned yet. Feel free to ask for help if you get\n stuck! *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof.\n reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match position\n in the definition of [app], allowing the match itself to be\n simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tail l).\nProof.\n intros l. destruct l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n l'\". \n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tail nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proofs will not get you very far! It is\n very important to work through the details of each one, using Coq\n and thinking about what each step of the proof achieves.\n Otherwise it is more or less guaranteed that the exercises will\n make no sense. *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n perhaps a little less familiar than standard natural number\n induction, but the basic idea is equally simple. Each [Inductive]\n declaration defines a set of data values that can be built up from\n the declared constructors: a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to a number; a\n list can be either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two things together establish the\n truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_ass : forall l1 l2 l3 : natlist, \n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3). \nProof.\n intros l1 l2 l3. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons n l1'\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n static written document -- it is easy to see what's going on if\n you are reading the proof in an interactive Coq session and you\n can see the current goal and context at each point, but this state\n is not visible in the written-down parts of the Coq proof. So a\n natural-language proof -- one written for human readers -- will\n need to include more explicit signposts; in particular, it will\n help the reader stay oriented if we remind them exactly what the\n induction hypothesis is in the second case. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3], \n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n (the induction hypothesis). We must show\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]] \n By the definition of [++], this follows from\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n which is immediate from the induction hypothesis. []\n\n Here is an exercise to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist, \n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** For a slightly more involved example of an inductive proof\n over lists, suppose we define a \"cons on the right\" function\n [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist := \n match l with\n | nil => [v]\n | h :: t => h :: (snoc t v)\n end.\n\n(** ... and use it to define a list-reversing function [rev]\n like this: *)\n\nFixpoint rev (l:natlist) : natlist := \n match l with\n | nil => nil\n | h :: t => snoc (rev t) h\n end.\n\nExample test_rev1: rev [1,2,3] = [3,2,1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** Now let's prove some more list theorems using our newly\n defined [snoc] and [rev]. For something a little more challenging\n than the inductive proofs we've seen so far, let's prove that\n reversing a list does not change its length. Our first attempt at\n this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n :: l'\".\n (* This is the tricky case. Let's begin as usual by simplifying. *)\n simpl. \n (* Now we seem to be stuck: the goal is an equality involving\n [snoc], but we don't have any equations in either the\n immediate context or the global environment that have\n anything to do with [snoc]! \n\n We can make a little progress by using the IH to rewrite the \n goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAdmitted.\n\n(** So let's take the equation about [snoc] that would have\n enabled us to make progress and prove it as a separate lemma. *)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n length (snoc l n) = S (length l).\nProof.\n intros n l. induction l as [| n' l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n' l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed. \n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons\".\n simpl. rewrite -> length_snoc. \n rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems: \n\n _Theorem_: For all numbers [n] and lists [l],\n [length (snoc l n) = S (length l)].\n \n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (snoc [] n) = S (length []),\n which follows directly from the definitions of\n [length] and [snoc].\n\n - Next, suppose [l = n'::l'], with\n length (snoc l' n) = S (length l').\n We must show\n length (snoc (n' :: l') n) = S (length (n' :: l')).\n By the definitions of [length] and [snoc], this\n follows from\n S (length (snoc l' n)) = S (S (length l')),\n]] \n which is immediate from the induction hypothesis. [] *)\n \n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n \n _Proof_: By induction on [l]. \n\n - First, suppose [l = []]. We must show\n length (rev []) = length [],\n which follows directly from the definitions of [length] \n and [rev].\n \n - Next, suppose [l = n::l'], with\n length (rev l') = length l'.\n We must show\n length (rev (n :: l')) = length (n :: l').\n By the definition of [rev], this follows from\n length (snoc (rev l') n) = S (length l')\n which, by the previous lemma, is the same as\n S (length (rev l')) = S (length l').\n This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n and pedantic. After the first few, we might find it easier to\n follow proofs that give a little less detail overall (since we can\n easily work them out in our own minds or on scratch paper if\n necessary) and just highlight the non-obvious steps. In this more\n compressed style, the above proof might look more like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that\n length (snoc l n) = S (length l)\n for any [l]. This follows by a straightforward induction on [l].\n The main property now follows by another straightforward\n induction on [l], using the observation together with the\n induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and on how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for\n present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, using [rewrite], and later we will see other ways\n of reusing previous theorems. But in order to refer to a theorem,\n we need to know its name, and remembering the names of all the\n theorems we might ever want to use can become quite difficult! It\n is often hard even to remember what theorems have been proven,\n much less what they are named.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following to\n see a list of theorems that we have proved about [rev]: *)\n\n(* SearchAbout rev. *)\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the course; it can save you a lot of time! *)\n \n(** Also, if you are using ProofGeneral, you can run [SearchAbout]\n with [C-c C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars, recommended (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist, \n l ++ [] = l. \nProof.\nintros. induction l. \nCase \" l = nil \". reflexivity. \nCase \" l = n l \". simpl. rewrite -> IHl. reflexivity. Qed.\n\nTheorem rev_snoc : forall l :natlist, forall n : nat,\n rev (snoc l n) = n::rev l. \nProof. intros. induction l as [| m l'].\nCase \" l = nil \". reflexivity.\nCase \" l = m l'\". simpl. rewrite IHl'. reflexivity. Qed.\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\nintros. induction l as [| n l'].\nCase \" l = nil \". reflexivity. \nCase \" l = n::l' \". simpl. rewrite -> rev_snoc. rewrite -> IHl'. reflexivity. Qed.\n\n(** There is a short solution to the next exercise. If you find\n yourself getting tangled up, step back and try to look for a\n simpler way. *)\n\nTheorem app_ass4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\nintros. rewrite <- app_ass; rewrite -> app_ass; rewrite -> app_ass; rewrite -> app_ass. reflexivity. Qed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n snoc l n = l ++ [n].\nProof.\nintros. induction l as [| m l'].\nCase \" l = nil \". reflexivity. \nCase \" l = m l' \". simpl. rewrite IHl'. reflexivity. Qed.\n\n\nTheorem distr_rev : forall l1 l2 : natlist,\n rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\nintros. induction l1 as [| m l1'].\nCase \" l1 = nil \". simpl. rewrite -> app_nil_end. reflexivity.\nCase \" l2 = m l2' \". simpl. rewrite IHl1'. rewrite -> snoc_append. rewrite -> snoc_append.\nrewrite -> app_ass. reflexivity. Qed.\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_length : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\nintros. induction l1 as [| n l1'].\nCase \" l1 = nil \". reflexivity.\nCase \" l1 = S n \". induction n as [| S n'].\nSCase \" n = 0 \". simpl. rewrite -> IHl1'. reflexivity.\nSCase \" n = S n' \". simpl. rewrite -> IHl1'. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 2 stars, recommended (list_design) *)\n(** Design exercise: \n - Write down a non-trivial theorem involving [cons]\n ([::]), [snoc], and [append] ([++]). \n - Prove it. *) \n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (bag_proofs) *)\n(** If you did the optional exercise about bags above, here are a\n couple of little theorems to prove about your definitions. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** The following lemma about [ble_nat] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n ble_nat n (S n) = true.\nProof.\n intros n. induction n as [| n'].\n Case \"0\". \n simpl. reflexivity.\n Case \"S n'\".\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *) \n(** Write down an interesting theorem about bags involving the\n functions [count] and [sum], and prove it.*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nThere is a hard way and an easy way to solve this exercise.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n(** Here is another type definition that is often useful in\n day-to-day programming: *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption. \n\n(** One use of [natoption] is as a way of returning \"error\n codes\" from functions. For example, suppose we want to write a\n function that returns the [n]th element of some list. If we give\n it type [nat -> natlist -> nat], then we'll have to return some\n number when the list is too short! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with \n | true => a \n | false => index_bad (pred n) l' \n end\n end.\n\n(** On the other hand, if we give it type [nat -> natlist ->\n natoption], then we can return [None] when the list is too short\n and [Some a] when the list has enough members and [a] appears at\n position [n]. *)\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => match beq_nat n O with \n | true => Some a\n | false => index (pred n) l' \n end\n end.\n\nExample test_index1 : index 0 [4,5,6,7] = Some 4.\nProof. reflexivity. Qed.\nExample test_index2 : index 3 [4,5,6,7] = Some 7.\nProof. reflexivity. Qed.\nExample test_index3 : index 10 [4,5,6,7] = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n small feature of Coq's programming language: conditional\n expressions... *)\n\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => if beq_nat n O then Some a else index' (pred n) l'\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_opt (l : natlist) : natoption :=\nindex 0 l.\n\nExample test_hd_opt1 : hd_opt [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_opt3 : hd_opt [5,6] = Some 5.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_opt l).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n match l1, l2 with\n | nil, nil => true\n | nil, h::l2' => false\n | h::l1', nil => false\n | h::l1', n::l2' => if beq_nat h n then beq_natlist l1' l2' else false\n end.\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\nExample test_beq_natlist2 : beq_natlist [1,2,3] [1,2,3] = true.\nProof. reflexivity. Qed.\nExample test_beq_natlist3 : beq_natlist [1,2,3] [1,2,4] = false.\nProof. reflexivity. Qed.\n\nTheorem beq_nat_refl : forall h:nat,\n beq_nat h h = true.\nProof.\nintros. induction h as [| S h'].\nCase \" h = 0 \". reflexivity. \nCase \" h = S h' \". simpl. rewrite h'. reflexivity. Qed.\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\nintros. induction l as [| h l'].\nCase \" l = nil \". reflexivity. \nCase \" l = h l' \". simpl. \nrewrite -> beq_nat_refl.\nrewrite IHl'. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Extended Exercise: Dictionaries *)\n\n(** As a final illustration of how fundamental data structures\n can be defined in Coq, here is the declaration of a simple\n [dictionary] data type, using numbers for both the keys and the\n values stored under these keys. (That is, a dictionary represents\n a finite map from numbers to numbers.) *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n | empty : dictionary \n | record : nat -> nat -> dictionary -> dictionary. \n\n(** This declaration can be read: \"There are two ways to construct a\n [dictionary]: either using the constructor [empty] to represent an\n empty dictionary, or by applying the constructor [record] to\n a key, a value, and an existing [dictionary] to construct a\n [dictionary] with an additional key to value mapping.\" *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n (record key value d).\n\n(** Here is a function [find] that searches a [dictionary] for a\n given key. It evaluates evaluates to [None] if the key was not\n found and [Some val] if the key was mapped to [val] in the\n dictionary. If the same key is mapped to multiple values, [find]\n will return the first one it finds. *)\n\nFixpoint find (key : nat) (d : dictionary) : natoption := \n match d with \n | empty => None\n | record k v d' => if (beq_nat key k) then (Some v) else (find key d')\n end.\n\n(** **** Exercise: 1 star (dictionary_invariant1) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant1 : forall (d : dictionary) (k v: nat),\n (find k (insert k v d)) = Some v.\nProof.\nintros. simpl. rewrite -> beq_nat_refl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2 : forall (d : dictionary) (m n o: nat),\n (beq_nat m n) = false -> (find m d) = (find m (insert n o d)).\nProof. \nintros. simpl. rewrite -> H. reflexivity. Qed.\n(** [] *)\n\nEnd Dictionary.\n\nEnd NatList.\n\n", "meta": {"author": "steven7woo", "repo": "Coq-CIS500", "sha": "405653248c19d78ec35f4b7bc2b2144c4aa92738", "save_path": "github-repos/coq/steven7woo-Coq-CIS500", "path": "github-repos/coq/steven7woo-Coq-CIS500/Coq-CIS500-405653248c19d78ec35f4b7bc2b2144c4aa92738/For_wenrui/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.9425067175660389, "lm_q1q2_score": 0.8740461338791253}} {"text": "From mathcomp Require Import ssreflect.\n\n(*| We continue working with our own definitions of Booleans and natural numbers |*)\n\nModule My.\n\nInductive bool : Type :=\n| true\n| false.\n\nDefinition negb :=\n fun (b : bool) =>\n match b with\n | true => false\n | false => true\n end.\n\n(** * Exercise 1 : boolean functions *)\n\n(*| 1a. Define `orb` function implementing boolean disjunction and test it\n_thoroughly_ using the command `Compute`. |*)\n\nDefinition andb (b c : bool) : bool :=\n match b with\n | true => c\n | _ => false\n end.\n\nDefinition orb (b c : bool) : bool :=\n match b with\n | true => true\n | _ => c\n end.\n\nCompute orb true false.\nCompute orb false false.\n\nDefinition orb' (b c : bool) : bool :=\n if b is true then true else c.\n\n(*| 1b. Define `addb` function implementing _exclusive_ boolean disjunction.\nTry to come up with more than one definition (try to make it interesting\nand don't just swap the variables) and explore its reduction behavior\nin the presence of symbolic variables. |*)\n\nDefinition addb (b c : bool) : bool :=\n andb (orb b c) (negb (andb b c)).\n\nCompute addb false false.\nCompute addb false true.\nCompute addb true true.\n\nDefinition addb' (b c : bool) : bool :=\n let\n overflow := andb b c\n in\n andb (orb b c) (negb overflow).\n\nCompute addb' false false.\nCompute addb' false true.\nCompute addb' true true.\n\n(*| 1c. Define `eqb` function implementing equality on booleans, i.e. `eqb b c`\nmust return `true` if and only iff `b` is equal to `c`. Add unit tests. |*)\n\nDefinition eqb (b c : bool) : bool :=\n orb (andb b c) (andb (negb b) (negb c)).\n\nCompute eqb true true.\nCompute eqb false false.\nCompute eqb true false.\n\nDefinition eqb' (b c : bool) : bool :=\n if b is false then negb c else c.\n\nCompute eqb' true true.\nCompute eqb false false.\nCompute eqb true false.\n\nDefinition eqb'' (b c : bool) : bool :=\n match b, c with\n | true, true | false, false => true\n | _, _ => false\n end.\n\nCompute eqb'' true true.\nCompute eqb'' false false.\nCompute eqb'' true false.\n\n(** * Exercise 2 : arithmetic *)\n\nInductive nat : Type :=\n| O\n| S of nat.\n\n\nDefinition one : nat := S O.\nDefinition two : nat := S one.\nDefinition three : nat := S two.\nDefinition four : nat := S three.\nDefinition five : nat := S four.\nDefinition six : nat := S five.\n\n(*| 2a. Define `dec2` function of type `nat -> nat` which takes a natural\nnumber and decrements it by 2, e.g. for the number `5` it must return `3`. Write\nsome unit tests for `dec2`. What should it return for `1` and `0`? |*)\n\nDefinition dec2 (n : nat) : nat :=\n if n is S (S n') then n' else O.\n\nCompute dec2 O.\nCompute dec2 one.\nCompute dec2 two.\nCompute dec2 three.\n\n(*| 2b. Define `subn` function of type `nat -> nat -> nat` which takes two\nnatural numbers `m` and `n` and returns the result of subtracting `n` from `m`.\nE.g. `subn 5 3` returns `2`. Write some unit tests. |*)\n\nFixpoint subn (m n : nat) : nat :=\n match m, n with\n | S m', S n' => subn m' n'\n | O, _ => O\n | _, O => m\n end.\n\nCompute subn one O.\nCompute subn one one.\nCompute subn two one.\n\nFixpoint addn (m n : nat) : nat :=\n match m with\n | S m' => S (addn m' n)\n | O => n\n end.\n\n(*| 2c. Define an `muln` function of type `nat -> nat -> nat` which takes two\nnatural numbers `m` and `n` and returns the result of their multiplication.\nWrite some unit tests. |*)\n\nFixpoint muln (m n : nat) : nat :=\n match m with\n | O => O\n | S m' => addn n (muln m' n)\n end.\n\nCompute muln O two.\nCompute muln one two.\nCompute muln two two.\n\n(** 2d. Implement equality comparison function `eqn` on natural numbers of\ntype `nat -> nat -> bool`. It returns true if and only if the input numbers are\nequal. *)\n\nFixpoint eqn (m n : nat) : bool :=\n match m, n with\n | O, S _ => false\n | S _, O => false\n | O, O => true\n | S m', S n' => eqn m' n'\n end.\n\nCompute eqn O one.\nCompute eqn one one.\nCompute eqn O O.\n\n(** 2e. Implement less-or-equal comparison function `leq` on natural numbers of\ntype `nat -> nat -> bool`. `leq m n` returns `true` if and only if `m` is less\nthan or equal to `n`. Your solution must not use recursion but you may reuse any\nof the functions you defined in this module so far. *)\n\nFixpoint leq' (m n : nat) : bool :=\n match m, n with\n | O, _ => true\n | S _, O => false\n | S m', S n' => leq' m' n'\n end.\n\nDefinition leq (m n : nat) : bool :=\n eqn (subn m n) O.\n\nCompute leq O one.\nCompute leq O O.\nCompute leq one O.\n\n(*| ---------------------------------------------------------------------------- |*)\n\n\n(*| EXTRA problems: feel free to skip these. If you need to get credit for this\nclass: extra exercises do not influence your grade negatively if you skip them.\n|*)\n\n(*| Ea: implement division (`divn`) on natural numbers and write some unit tests\nfor it. |*)\n\nDefinition lt (m n : nat ) : bool :=\n andb (leq m n) (negb (eqn m n)).\n\nFixpoint div_helper (m n dummy : nat) {struct dummy} :=\n if dummy is S dummy' then\n if lt m n is true then\n O\n else\n S (div_helper (subn m n) n dummy')\n else\n O.\n\nDefinition div (m n : nat) := div_helper m n m.\n\nCompute eqn two (div two O).\nCompute eqn three (div six two).\nCompute eqn three (div six two).\nCompute eqn one (div three two).\n\nEnd My.\n", "meta": {"author": "yugr", "repo": "Lalambda", "sha": "0c07b626ffac2cbbce621c4f2c458ac2b0d45bb7", "save_path": "github-repos/coq/yugr-Lalambda", "path": "github-repos/coq/yugr-Lalambda/Lalambda-0c07b626ffac2cbbce621c4f2c458ac2b0d45bb7/21/lecture-notes/Coq-prep/seminar01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.931462509346239, "lm_q1q2_score": 0.8738273484158227}} {"text": "Module NatPlayground.\n \nInductive nat : Type :=\n| O\n| S : nat -> nat.\n\nCheck (S O).\n\nDefinition pred (n : nat) : nat :=\n match n with\n | O => O\n | S n' => n'\n end.\n\nCompute (pred(S(S O))).\n\nEnd NatPlayground.\n\nCheck (S (S O)).\n\nDefinition minustwo (n: nat) : nat :=\n match n with\n | O => O\n | S O => O\n | S (S n') => n'\nend.\n\nCompute (minustwo 10).\n\nCheck S.\nCheck pred.\nCheck minustwo.\n\nFixpoint evenb (n : nat) : bool :=\n match n with\n | O => true\n | S O => false\n | S (S n') => evenb n'\n end.\n\nDefinition oddb (n : nat) : bool := (negb (evenb n)).\n\nCompute (oddb 3).\n\nExample test_oddb1: (oddb 1) = true.\nProof.\n unfold oddb.\n simpl.\n reflexivity.\nQed.\n\nExample test_oddb2: (oddb 4) = false.\nProof.\n unfold oddb.\n simpl.\n reflexivity.\nQed.\n\nModule NatPlayground2.\n\n Fixpoint plus (n : nat) (m : nat) : nat :=\n match m with\n | O => n\n | S n' => S (plus n n')\n end.\n\n Definition pred' (n : nat) : nat :=\n match n with\n | O => O\n | S n' => n'\n end.\n \n\n Compute (plus 4 3).\n\n Fixpoint minus (n : nat) (m : nat) : nat :=\n match m with\n | O => n\n | S n' => pred (minus n n')\n end.\n\n Compute (minus 3 1).\n\n Fixpoint mult (n : nat) (m : nat) : nat :=\n match m with\n | O => O\n | S n' => (plus (mult n n') n)\n end.\n\n Compute (mult 3 2).\n\n Notation \"x + y\" := (plus x y)\n (at level 50, left associativity)\n : nat_scope.\n\n Notation \"x - y\" := (minus x y)\n (at level 50, left associativity)\n : nat_scope.\n \n Notation \"x * y\" := (mult x y)\n (at level 40, left associativity)\n : nat_scope.\n\n Check ((0 + 1) + 1).\n\n Compute ((0 + 1) + 1).\nEnd NatPlayground2.\n", "meta": {"author": "zant", "repo": "gallina", "sha": "5259a6caf0c6abfb3be3437a74b42e8dee32d831", "save_path": "github-repos/coq/zant-gallina", "path": "github-repos/coq/zant-gallina/gallina-5259a6caf0c6abfb3be3437a74b42e8dee32d831/numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.9219218343187415, "lm_q1q2_score": 0.8734112695891754}} {"text": "Require Import Nat.\n\nTheorem plus_O_n : forall n:nat, n + 0 = n.\nProof.\n intros n.\n induction n.\n - (* base *) simpl. reflexivity.\n - (* i.h. *) simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n intros n.\n induction n.\n - (* n = 0 *) reflexivity.\n - (* n = S n' *) simpl. rewrite <- IHn. reflexivity.\nQed.\n\nTheorem minus_diag : forall n,\n minus n n = 0.\nProof.\n intros n. induction n.\n - (* n = 0 *)\n simpl. reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn. reflexivity.\nQed.\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n intros n.\n induction n.\n - (* base *) simpl. reflexivity.\n - (* i.h. *) simpl. exact IHn.\nQed.\n\nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof.\n intros n m.\n induction n.\n - (* base *) unfold add. reflexivity.\n - (* i.h. *) simpl. rewrite IHn. reflexivity.\nQed.\n\nLemma fancy_lemma : forall n m : nat, n + S m = S (m + n).\nProof.\n intros n m.\n induction n.\n - (* base *) simpl. rewrite <- plus_n_O. reflexivity.\n - (* i.h. *) rewrite <- plus_n_Sm. simpl. rewrite <- plus_n_Sm. rewrite <- IHn. rewrite plus_n_Sm. reflexivity.\nQed.\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros n m.\n induction m.\n - (* base *) simpl. exact (plus_O_n n).\n - (* i.h. *) simpl. exact (fancy_lemma n m).\nQed.\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p.\n induction p.\n - (* base *) rewrite plus_O_n. rewrite plus_O_n. reflexivity.\n - (* i.h. *) rewrite <- plus_n_Sm. rewrite fancy_lemma. rewrite plus_comm. rewrite IHp. rewrite plus_n_Sm. reflexivity.\nQed.\n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n intros n.\n induction n.\n - (* base *) simpl. reflexivity.\n - (* i.h. *) simpl. rewrite IHn. rewrite plus_n_Sm. reflexivity.\nQed.\n\nFixpoint evenb (n : nat) : bool :=\n match n with\n | S (S n) => evenb n\n | S n => false\n | 0 => true\nend.\n\nRequire Import Bool.\nSearch (negb (negb _) = _).\nPrint negb.\nPrint negb_involutive.\n\nTheorem evenb_S : forall n : nat,\n evenb (S n) = negb (evenb n).\nProof.\n intros n.\n induction n.\n - (* base *) simpl. reflexivity.\n - (* i.h. *) rewrite IHn. rewrite negb_involutive. simpl. reflexivity.\nQed.\n\n(* Briefly explain the difference between the tactics destruct and induction. *)\n(* When we use destruct to analyze cases, we don't have hypothesis to re-use on the subterms, unlike induction. *)\n", "meta": {"author": "FengZiGG", "repo": "coqlf", "sha": "73aea6d263b0e05d8e25c5ce1f6609faf8e3956c", "save_path": "github-repos/coq/FengZiGG-coqlf", "path": "github-repos/coq/FengZiGG-coqlf/coqlf-73aea6d263b0e05d8e25c5ce1f6609faf8e3956c/2_Induction/1_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025231, "lm_q2_score": 0.9196425300765949, "lm_q1q2_score": 0.8733563397742957}} {"text": "(* Define a function that takes a tuple of numbers (a,b) and returns\n the sum of the squares of both numbers. *)\n\n(* Define a function that computes the sum of all squares between 1 and n,\n as a natural number. Use the Fixpoint approach as described in the slides. *)\n\nRequire Import ZArith List.\nOpen Scope Z_scope.\n\n(* Write a function that maps any positive integer n to the list 1 ... n *)\n(* Use the iter function shown in the slides. *)\n\n\n(* Write a function that maps any n and any list a_1::...::a_p::nil\n to the list (n*a_1::...n*a_p::nil) *)\n\n(* Write a function that maps any n and any list l and returns the boolean\n value that indicates whether n is in l.\n Use the function fold_right given in the slides and a function Zeq_bool\n to compare to integers *)\n\n(* Write a function that checks whether n divides p, assuming n and p\n are both positive. Here's a plan:\n build the list n::2*n::...::p*n::nil,\n check whether p is in this list. *)\n\n(* Write a function that checks whether n is prime. *)\n\n", "meta": {"author": "sighingnow", "repo": "amazing-coq", "sha": "70acce0bac267f76f696b0f0a35865622b6a0ee8", "save_path": "github-repos/coq/sighingnow-amazing-coq", "path": "github-repos/coq/sighingnow-amazing-coq/amazing-coq-70acce0bac267f76f696b0f0a35865622b6a0ee8/tsinghua-coq-summer-school/exercises/exercises_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.9241418215456966, "lm_q1q2_score": 0.8733091313643319}} {"text": "Require Import Arith List.\n\n(* EXAMPLES *) \n(* The following function takes two arguments a and b\nwhich are numbers of type nat and returns b + 2 * (a + b) *)\nDefinition f_ex (a b : nat) := b + 2 * (a + b).\n\n(* When p is a pair, you can access its components by the \"pattern-matching\"\n construct illustrated in the following function. *)\nDefinition add_pair_components (p : nat * nat) :=\n match p with (a, b) => a + b end.\n\n(* f_ex is a function with two arguments. add_pair_components is a\n function with one argument, which is a pair. *)\n\n(* END OF EXAMPLES *)\n\n(* 1/ Define a function that takes two numbers as arguments and returns\n the sum of the squares of these numbers. *)\n\nDefinition f1_1 (x y : nat) : nat := x * x + y * y.\n\n(* 2/ Define a function that takes 5 arguments a b c d e, which are all\n numbers and returns the sum of all these numbers. *)\n\nDefinition f1_2 (a b c d e : nat) := a + b + c + d + e.\n\n(* 3/ Define a function named add5 that takes a number as argument and returns\n this number plus 5. *)\n\nDefinition add5 (x : nat) := x + 5.\n\n(* The following should return 8 *)\nCompute add5 3.\n\n(* The following commands make it possible to find pre-defined functions *)\nSearch nat.\nSearch bool.\n\n(* 4/ Write a function swap of type list nat -> list nat such that\n swap (a::b::l) = (b::a::l) and\n swap l' = l' if l' has less than 2 elements. *)\n\nDefinition swap (l : list nat) : list nat :=\n match l with\n a::b::l => b::a::l\n | _ => l\n end.\n\n(* 5/ Write a function proc2 of type list nat -> nat, such that\n proc2 (a::b::l) = (b + 3) and\n proc2 l' = 0 if l' has less than 2 elements.\n\n In other words, proc2 only processes the 2nd argument of the list and\n returns that number plus 3. If there is no second argument to the list,\n proc2 returns 0. *)\n\nDefinition proc2 (l : list nat) : nat :=\n match l with\n a::b::l => b + 3\n | _ => 0\n end.\n\n(* 6/ Write a function ms of type list nat -> list nat such that\n ms (a::b::...::nil) = a+2::b+2::...::nil\n For instance\n ms (2::3::5::nil) = (4::5::7::nil) *) \n\nFixpoint ms (l : list nat) : list nat :=\n match l with\n a::l' => a + 2 :: ms l'\n | nil => nil\n end.\n\n(* 7/ Write a function sorted of type list nat -> bool, such that\n sorted l = true exactly when the natural numbers in\n l are in increasing order. *)\n\nFixpoint sorted (l : list nat) : bool :=\n match l with\n a::l' => match l' with b::_ => if leb a b then sorted l' else false | _ => true end\n | nil => true\n end.\n\n(* 8/ Write a function p2 of type nat -> nat such that \n p2 n = 2 ^ n *)\n\nFixpoint p2 (n : nat) :=\n match n with 0 => 1 | S p => 2 * p2 p end.\n\n(* 9/ Write a function salt of type nat -> nat -> nat such that\n salt x n = x ^ n - x^ (n+1) + x^(n-2) .... + 1 or -1, if x <> 0,\n depending on the parity of n, thus\n salt x 3 = x^3 - x^2 + x - 1\n salt x 4 = x^4 - x^3 + x^2 - x + 1\n salt 2 3 = 5\n\n You may have to define auxiliary functions. *)\n\nFixpoint even n :=\n match n with 0 => true | 1 => false | S (S p) => even p end.\n\nFixpoint salt (x n : nat) :=\n match n with\n 0 => 1\n | S p => if even n then x * salt x p + 1 else x * salt x p - 1\n end.\n\nFixpoint pow x n :=\n match n with 0 => 1 | S p => x * pow x p end.\n\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Asian-Pacific Summer School/solutions/solutions/solutions1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620608291781, "lm_q2_score": 0.9099070103134426, "lm_q1q2_score": 0.8732942273813459}} {"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\n\nModule NatList. \n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as in this definition: *)\n\nInductive natprod : Type :=\n pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\n(** We can construct an element of [natprod] like this: *)\n\nCheck (pair 3 5).\n\n(** Here are two simple function definitions for extracting the\n first and second components of a pair. (The definitions also\n illustrate how to do pattern matching on two-argument\n constructors.) *)\n\nDefinition fst (p : natprod) : nat := \n match p with\n | pair x y => x\n end.\nDefinition snd (p : natprod) : nat := \n match p with\n | pair x y => y\n end.\n\nEval simpl in (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this notation is provided as part of the standard\n library): *)\n\nEval simpl in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat := \n match p with\n | (x,y) => x\n end.\nDefinition snd' (p : natprod) : nat := \n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod := \n match p with\n | (x,y) => (y,x)\n end.\n\n(** Let's try and prove a few simple facts about pairs. If we\n state the lemmas in a particular (and slightly peculiar) way, we\n can prove them with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** Note that [reflexivity] is not enough if we state the lemma in a\n more natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAdmitted.\n\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct].\n\n Notice that, unlike for [nat]s, [destruct] doesn't generate an\n extra subgoal here. That's because [natprod]s can only be\n constructed in one way. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as (n,m). simpl. reflexivity. Qed.\n\n(** Notice that Coq allows us to use the notation we introduced\n for pairs in the \"[as]...\" pattern that tells it what variables to\n bind. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n describe the type of _lists_ of numbers like this: \"A list is\n either the empty list or else a pair of a number and another\n list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following two declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n but in case you are interested, here is roughly what's going on.\n\n The [right associativity] annotation tells Coq how to parenthesize\n expressions involving several uses of [::] so that, for example,\n the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1,2,3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\nNotation \"x + y\" := (plus x y) \n (at level 50, left associativity).\n The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (By the way, it's worth noting in passing that expressions like \"[1\n + 2 :: [3]]\" can be a little confusing when you read them in a .v\n file. The inner brackets, around 3, indicate a list, but the outer\n brackets, which are invisible in the HTML rendering, are there to\n instruct the \"coqdoc\" tool that the bracketed part should be\n displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist := \n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat := \n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist := \n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y) \n (right associativity, at level 60).\n\nExample test_app1: [1,2,3] ++ [4,5] = [1,2,3,4,5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4,5] = [4,5].\nProof. reflexivity. Qed.\nExample test_app3: [1,2,3] ++ nil = [1,2,3].\nProof. reflexivity. Qed.\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tail] returns everything but the first\n element. Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tail (l:natlist) : natlist :=\n match l with\n | nil => nil \n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1,2,3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tail: tail [1,2,3] = [2,3].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n (* FILL IN HERE *) admit.\n\nExample test_nonzeros: nonzeros [0,1,0,2,3,0,0] = [1,2,3].\n (* FILL IN HERE *) Admitted.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n (* FILL IN HERE *) admit.\n\nExample test_oddmembers: oddmembers [0,1,0,2,3,0,0] = [1,3].\n (* FILL IN HERE *) Admitted.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n (* FILL IN HERE *) admit.\n\nExample test_countoddmembers1: countoddmembers [1,0,3,1,4,5] = 4.\n (* FILL IN HERE *) Admitted.\nExample test_countoddmembers2: countoddmembers [0,2,4] = 0.\n (* FILL IN HERE *) Admitted.\nExample test_countoddmembers3: countoddmembers nil = 0.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n (* FILL IN HERE *) admit.\n\n\nExample test_alternate1: alternate [1,2,3] [4,5,6] = [1,4,2,5,3,6].\n (* FILL IN HERE *) Admitted.\nExample test_alternate2: alternate [1] [4,5,6] = [1,4,5,6].\n (* FILL IN HERE *) Admitted.\nExample test_alternate3: alternate [1,2,3] [4] = [1,4,2,3].\n (* FILL IN HERE *) Admitted.\nExample test_alternate4: alternate [] [20,30] = [20,30].\n (* FILL IN HERE *) Admitted. \n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n multiple times instead of just once. One reasonable\n implementation of bags is to represent a bag of numbers as a\n list. *)\n\nDefinition bag := natlist. \n\n(** **** Exercise: 3 stars (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat := \n (* FILL IN HERE *) admit.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1,2,3,1,4,1] = 3.\n (* FILL IN HERE *) Admitted.\nExample test_count2: count 6 [1,2,3,1,4,1] = 0.\n (* FILL IN HERE *) Admitted.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := \n (* FILL IN HERE *) admit.\n\nExample test_sum1: count 1 (sum [1,2,3] [1,4,1]) = 3.\n (* FILL IN HERE *) Admitted.\n\nDefinition add (v:nat) (s:bag) : bag := \n (* FILL IN HERE *) admit.\n\nExample test_add1: count 1 (add 1 [1,4,1]) = 3.\n (* FILL IN HERE *) Admitted.\nExample test_add2: count 5 (add 1 [1,4,1]) = 0.\n (* FILL IN HERE *) Admitted.\n\nDefinition member (v:nat) (s:bag) : bool := \n (* FILL IN HERE *) admit.\n\nExample test_member1: member 1 [1,4,1] = true.\n (* FILL IN HERE *) Admitted.\nExample test_member2: member 2 [1,4,1] = false.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n (* When remove_one is applied to a bag without the number to remove,\n it should return the same bag unchanged. *)\n (* FILL IN HERE *) admit.\n\nExample test_remove_one1: count 5 (remove_one 5 [2,1,5,4,1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_one2: count 5 (remove_one 5 [2,1,4,1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_one3: count 4 (remove_one 5 [2,1,4,5,1,4]) = 2.\n (* FILL IN HERE *) Admitted.\nExample test_remove_one4: \n count 5 (remove_one 5 [2,1,5,4,5,1,4]) = 1.\n (* FILL IN HERE *) Admitted.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n (* FILL IN HERE *) admit.\n\nExample test_remove_all1: count 5 (remove_all 5 [2,1,5,4,1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all2: count 5 (remove_all 5 [2,1,4,1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all3: count 4 (remove_all 5 [2,1,4,5,1,4]) = 2.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all4: count 5 (remove_all 5 [2,1,5,4,5,1,4,5,1,4]) = 0.\n (* FILL IN HERE *) Admitted.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n (* FILL IN HERE *) admit.\n\nExample test_subset1: subset [1,2] [2,1,4,1] = true.\n (* FILL IN HERE *) Admitted.\nExample test_subset2: subset [1,2,2] [2,1,4,1] = false.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (bag_theorem) *)\n(** Write down an interesting theorem about bags involving the\n functions [count] and [add], and prove it. Note that, since this\n problem is somewhat open-ended, it's possible that you may come up\n with a theorem which is true, but whose proof requires techniques\n you haven't learned yet. Feel free to ask for help if you get\n stuck! *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match position\n in the definition of [app], allowing the match itself to be\n simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tail l).\nProof.\n intros l. destruct l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n l'\". \n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tail nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proofs will not get you very far! It is\n very important to work through the details of each one, using Coq\n and thinking about what each step of the proof achieves.\n Otherwise it is more or less guaranteed that the exercises will\n make no sense. *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n perhaps a little less familiar than standard natural number\n induction, but the basic idea is equally simple. Each [Inductive]\n declaration defines a set of data values that can be built up from\n the declared constructors: a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to a number; a\n list can be either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two things together establish the\n truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_ass : forall l1 l2 l3 : natlist, \n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3). \nProof.\n intros l1 l2 l3. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons n l1'\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n static written document -- it is easy to see what's going on if\n you are reading the proof in an interactive Coq session and you\n can see the current goal and context at each point, but this state\n is not visible in the written-down parts of the Coq proof. So a\n natural-language proof -- one written for human readers -- will\n need to include more explicit signposts; in particular, it will\n help the reader stay oriented if we remind them exactly what the\n induction hypothesis is in the second case. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3], \n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n (the induction hypothesis). We must show\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]] \n By the definition of [++], this follows from\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n which is immediate from the induction hypothesis. []\n\n Here is a similar example to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist, \n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** For a slightly more involved example of an inductive proof\n over lists, suppose we define a \"cons on the right\" function\n [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist := \n match l with\n | nil => [v]\n | h :: t => h :: (snoc t v)\n end.\n\n(** ... and use it to define a list-reversing function [rev]\n like this: *)\n\nFixpoint rev (l:natlist) : natlist := \n match l with\n | nil => nil\n | h :: t => snoc (rev t) h\n end.\n\nExample test_rev1: rev [1,2,3] = [3,2,1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** Now let's prove some more list theorems using our newly\n defined [snoc] and [rev]. For something a little more challenging\n than the inductive proofs we've seen so far, let's prove that\n reversing a list does not change its length. Our first attempt at\n this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n :: l'\".\n (* This is the tricky case. Let's begin as usual \n by simplifying. *)\n simpl. \n (* Now we seem to be stuck: the goal is an equality \n involving [snoc], but we don't have any equations \n in either the immediate context or the global \n environment that have anything to do with [snoc]! \n\n We can make a little progress by using the IH to \n rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAdmitted.\n\n(** So let's take the equation about [snoc] that would have\n enabled us to make progress and prove it as a separate lemma. *)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n length (snoc l n) = S (length l).\nProof.\n intros n l. induction l as [| n' l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n' l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed. \n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons\".\n simpl. rewrite -> length_snoc. \n rewrite -> IHl'. reflexivity. Qed.\n\n(** ** Discussion... *)\n\n(* QUIZ *)\n(** To prove the following theorem, which tactics will we need besides\n [intros], [simpl], [rewrite] and [reflexivity]? (1) none (2) [destruct],\n (3) [induction on n], (4) [induction on l], or (5) can't be\n done with the tactics we've seen.\n Theorem foo1 : forall n :nat, forall l: natlist, \n repeat n 0 = l -> length l = 0.\n*)\n(* /QUIZ *)\n\n(* QUIZ *)\n(** What about the next one? \n Theorem foo2 : forall n m:nat, forall l: natlist,\n repeat n m = l -> length l = m.\n Which tactics do we need besides [intros], [simpl], [rewrite] and\n [reflexivity]? (1) none (2) [destruct],\n (3) [induction on m], (4) [induction on l], or (5) can't be\n done with the tactics we've seen.\n*)\n(* /QUIZ *)\n\n(* SOONER check that having two cases that are true is ok *)\n\n(* QUIZ *)\n(** What about the next one? \n Theorem foo3 : forall l: natlist, forall n m:nat,\n length l = m -> length (snoc l n) = S m.\n Which tactics do we need besides [intros], [simpl], [rewrite] and\n [reflexivity]? (1) none (2) [destruct],\n (3) [induction on m], (4) [induction on l], (5) using an auxiliary lemma,\n or (6) can't be done with the tactics we've seen.\n*)\n(* /QUIZ *)\n\n(* QUIZ *)\n(** What about the next one? \n Theorem foo4 : forall n :nat, forall l1 l2: natlist,\n snoc l1 n = l2 -> (blt_nat 0 (length l2)) = true.\n Which tactics do we need besides [intros], [simpl], [rewrite] and\n [reflexivity]? (1) none (2) [destruct],\n (3) [induction on n], (4) [induction on l1], (5) [induction on l2], \n (6) can't be done with the tactics we've seen.\n*)\n(* /QUIZ *)\n\n(* /TERSE *)\n\n(** For comparison, here are informal proofs of these two theorems: \n\n _Theorem_: For all numbers [n] and lists [l],\n [length (snoc l n) = S (length l)].\n \n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (snoc [] n) = S (length []),\n which follows directly from the definitions of\n [length] and [snoc].\n\n - Next, suppose [l = n'::l'], with\n length (snoc l' n) = S (length l').\n We must show\n length (snoc (n' :: l') n) = S (length (n' :: l')).\n By the definitions of [length] and [snoc], this\n follows from\n S (length (snoc l' n)) = S (S (length l')),\n]] \n which is immediate from the induction hypothesis. [] *)\n \n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n \n _Proof_: By induction on [l]. \n\n - First, suppose [l = []]. We must show\n length (rev []) = length [],\n which follows directly from the definitions of [length] \n and [rev].\n \n - Next, suppose [l = n::l'], with\n length (rev l') = length l'.\n We must show\n length (rev (n :: l')) = length (n :: l').\n By the definition of [rev], this follows from\n length (snoc (rev l') n) = S (length l')\n which, by the previous lemma, is the same as\n S (length (rev l')) = S (length l').\n This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n and pedantic. After the first few, we might find it easier to\n follow proofs that give a little less detail overall (since we can\n easily work them out in our own minds or on scratch paper if\n necessary) and just highlight the non-obvious steps. In this more\n compressed style, the above proof might look more like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that\n length (snoc l n) = S (length l)\n for any [l]. This follows by a straightforward induction on [l].\n The main property now follows by another straightforward\n induction on [l], using the observation together with the\n induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and on how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for\n present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, using [rewrite], and later we will see other ways\n of reusing previous theorems. But in order to refer to a theorem,\n we need to know its name, and remembering the names of all the\n theorems we might ever want to use can become quite difficult! It\n is often hard even to remember what theorems have been proven,\n much less what they are named.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following to\n see a list of theorems that we have proved about [rev]: *)\n\n(* SearchAbout rev. *)\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the course; it can save you a lot of time! *)\n \n(** Also, if you are using ProofGeneral, you can run [SearchAbout]\n with [C-c C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist, \n l ++ [] = l. \nProof.\n (* FILL IN HERE *) Admitted.\n\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** There is a short solution to the next exercise. If you find\n yourself getting tangled up, step back and try to look for a\n simpler way. *)\n\nTheorem app_ass4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n snoc l n = l ++ [n].\nProof.\n (* FILL IN HERE *) Admitted.\n\n\nTheorem distr_rev : forall l1 l2 : natlist,\n rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_length : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 2 stars (list_design) *)\n(** Design exercise: \n - Write down a non-trivial theorem involving [cons]\n ([::]), [snoc], and [append] ([++]). \n - Prove it. *) \n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n definitions about bags in the previous problem. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** The following lemma about [ble_nat] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n ble_nat n (S n) = true.\nProof.\n intros n. induction n as [| n'].\n Case \"0\". \n simpl. reflexivity.\n Case \"S n'\".\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *) \n(** Write down an interesting theorem about bags involving the\n functions [count] and [sum], and prove it.*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nThere is a hard way and an easy way to solve this exercise.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n(** Here is another type definition that is often useful in\n day-to-day programming: *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption. \n\n(** One use of [natoption] is as a way of returning \"error\n codes\" from functions. For example, suppose we want to write a\n function that returns the [n]th element of some list. If we give\n it type [nat -> natlist -> nat], then we'll have to return some\n number when the list is too short! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with \n | true => a \n | false => index_bad (pred n) l' \n end\n end.\n\n(** On the other hand, if we give it type [nat -> natlist ->\n natoption], then we can return [None] when the list is too short\n and [Some a] when the list has enough members and [a] appears at\n position [n]. *)\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => match beq_nat n O with \n | true => Some a\n | false => index (pred n) l' \n end\n end.\n\nExample test_index1 : index 0 [4,5,6,7] = Some 4.\nProof. reflexivity. Qed.\nExample test_index2 : index 3 [4,5,6,7] = Some 7.\nProof. reflexivity. Qed.\nExample test_index3 : index 10 [4,5,6,7] = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n small feature of Coq's programming language: conditional\n expressions... *)\n\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => if beq_nat n O then Some a else index' (pred n) l'\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_opt (l : natlist) : natoption :=\n (* FILL IN HERE *) admit.\n\nExample test_hd_opt1 : hd_opt [] = None.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_opt3 : hd_opt [5,6] = Some 5.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_opt l).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n (* FILL IN HERE *) admit.\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\n (* FILL IN HERE *) Admitted.\nExample test_beq_natlist2 : beq_natlist [1,2,3] [1,2,3] = true.\n (* FILL IN HERE *) Admitted.\nExample test_beq_natlist3 : beq_natlist [1,2,3] [1,2,4] = false.\n (* FILL IN HERE *) Admitted.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Dictionaries *)\n\n(** As a final illustration of how fundamental data structures\n can be defined in Coq, here is the declaration of a simple\n [dictionary] data type, using numbers for both the keys and the\n values stored under these keys. (That is, a dictionary represents\n a finite map from numbers to numbers.) *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n | empty : dictionary \n | record : nat -> nat -> dictionary -> dictionary. \n\n(** This declaration can be read: \"There are two ways to construct a\n [dictionary]: either using the constructor [empty] to represent an\n empty dictionary, or by applying the constructor [record] to\n a key, a value, and an existing [dictionary] to construct a\n [dictionary] with an additional key to value mapping.\" *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n (record key value d).\n\n(** Here is a function [find] that searches a [dictionary] for a\n given key. It evaluates evaluates to [None] if the key was not\n found and [Some val] if the key was mapped to [val] in the\n dictionary. If the same key is mapped to multiple values, [find]\n will return the first one it finds. *)\n\nFixpoint find (key : nat) (d : dictionary) : natoption := \n match d with \n | empty => None\n | record k v d' => if (beq_nat key k) \n then (Some v) \n else (find key d')\n end.\n\n(** **** Exercise: 1 star (dictionary_invariant1) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n (find k (insert k v d)) = Some v.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),\n (beq_nat m n) = false -> (find m d) = (find m (insert n o d)).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\nEnd Dictionary.\n\n\n\n\nEnd NatList.\n\n(* $Date: 2013-01-16 22:29:57 -0500 (Wed, 16 Jan 2013) $ *)\n\n", "meta": {"author": "steven7woo", "repo": "Coq-CIS500", "sha": "405653248c19d78ec35f4b7bc2b2144c4aa92738", "save_path": "github-repos/coq/steven7woo-Coq-CIS500", "path": "github-repos/coq/steven7woo-Coq-CIS500/Coq-CIS500-405653248c19d78ec35f4b7bc2b2144c4aa92738/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761565, "lm_q2_score": 0.9273633006654725, "lm_q1q2_score": 0.8732555047803632}} {"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export Logic.\nFrom Coq Require Import Lia.\n\n(* ################################################################# *)\n(** * Inductively Defined Propositions *)\n\n(** In the [Logic] chapter, we looked at several ways of writing\n propositions, including conjunction, disjunction, and existential\n quantification. In this chapter, we bring yet another new tool\n into the mix: _inductively defined propositions_. *)\n\n(** We've already seen two ways of stating a proposition that a number\n [n] is even: We can say\n\n (1) [even n = true], or\n\n (2) [exists k, n = double k].\n\n A third possibility that we'll explore here is to say that [n] is\n even if we can _establish_ its evenness from the following rules:\n\n - Rule [ev_0]: The number [0] is even.\n - Rule [ev_SS]: If [n] is even, then [S (S n)] is even. *)\n\n(** To illustrate how this new definition of evenness works,\n let's imagine using it to show that [4] is even. By rule [ev_SS],\n it suffices to show that [2] is even. This, in turn, is again\n guaranteed by rule [ev_SS], as long as we can show that [0] is\n even. But this last fact follows directly from the [ev_0] rule. *)\n\n(** We will see many definitions like this one during the rest\n of the course. For purposes of informal discussions, it is\n helpful to have a lightweight notation that makes them easy to\n read and write. _Inference rules_ are one such notation. (We'll\n use [ev] for the name of this property, since [even] is already\n used.)\n\n ------------ (ev_0)\n ev 0\n\n ev n\n ---------------- (ev_SS)\n ev (S (S n))\n*)\n\n(** Each of the textual rules that we started with is\n reformatted here as an inference rule; the intended reading is\n that, if the _premises_ above the line all hold, then the\n _conclusion_ below the line follows. For example, the rule\n [ev_SS] says that, if [n] satisfies [ev], then [S (S n)] also\n does. If a rule has no premises above the line, then its\n conclusion holds unconditionally.\n\n We can represent a proof using these rules by combining rule\n applications into a _proof tree_. Here's how we might transcribe\n the above proof that [4] is even:\n\n -------- (ev_0)\n ev 0\n -------- (ev_SS)\n ev 2\n -------- (ev_SS)\n ev 4\n*)\n\n(* ================================================================= *)\n(** ** Inductive Definition of Evenness *)\n\n(** Putting all of this together, we can translate the definition of\n evenness into a formal Coq definition using an [Inductive]\n declaration, where each constructor corresponds to an inference\n rule: *)\n\nInductive ev: nat -> Prop :=\n | ev_0 : ev 0\n | ev_SS : forall n:nat, ev n -> ev (S (S n)). \n\n(*Inductive ev : nat -> Prop :=\n | ev_0 : ev 0\n | ev_SS (n : nat) (H : ev n) : ev (S (S n)).*)\n\nTheorem ev_4 : ev 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0. Qed.\n \n(** ... or we can use function application syntax to combine several\n constructors: *)\n \nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n \n(** In this way, we can also prove theorems that have hypotheses\n involving [ev]. *)\n \nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n intros n. simpl. intros Hn.\n apply ev_SS. apply ev_SS. apply Hn.\nQed.\n \n(* ################################################################# *)\n(** * Using Evidence in Proofs *)\n\n(** Besides _constructing_ evidence that numbers are even, we can also\n _destruct_ such evidence, which amounts to reasoning about how it\n could have been built.\n\n Introducing [ev] with an [Inductive] declaration tells Coq not\n only that the constructors [ev_0] and [ev_SS] are valid ways to\n build evidence that some number is [ev], but also that these two\n constructors are the _only_ ways to build evidence that numbers\n are [ev]. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n [ev n], then we know that [E] must be one of two things:\n\n - [E] is [ev_0] (and [n] is [O]), or\n - [E] is [ev_SS n' E'] (and [n] is [S (S n')], where [E'] is\n evidence for [ev n']). *)\n\n(** This suggests that it should be possible to analyze a\n hypothesis of the form [ev n] much as we do inductively defined\n data structures; in particular, it should be possible to argue by\n _induction_ and _case analysis_ on such evidence. Let's look at a\n few examples to see what this means in practice. *)\n\n(* ================================================================= *)\n(** ** Inversion on Evidence *)\n\n(** Suppose we are proving some fact involving a number [n], and\n we are given [ev n] as a hypothesis. We already know how to\n perform case analysis on [n] using [destruct] or [induction],\n generating separate subgoals for the case where [n = O] and the\n case where [n = S n'] for some [n']. But for some proofs we may\n instead want to analyze the evidence for [ev n] _directly_. As\n a tool, we can prove our characterization of evidence for\n [ev n], using [destruct]. *)\n\nTheorem ev_inversion :\n forall (n : nat), ev n ->\n (n = 0) \\/ (exists n', n = S (S n') /\\ ev n').\nProof.\n intros n E.\n destruct E as [ | n' E'] eqn:EE.\n - (* E = ev_0 : ev 0 *)\n left. reflexivity.\n - (* E = ev_SS n' E' : ev (S (S n')) *)\n right. exists n'. split. reflexivity. apply E'.\nQed.\n\n(** Facts like this are often called \"inversion lemmas\" because they\n allow us to \"invert\" some given information to reason about all\n the different ways it could have been derived.\n\n Here, there are two ways to prove that a number is [ev], and\n the inversion lemma makes this explicit. *)\n\n(** The following theorem can easily be proved using [destruct] on\n evidence. *)\n\nTheorem ev_minus2 : forall n,\n ev n -> ev (pred (pred n)).\nProof.\n intros n E.\n destruct E as [| n' E'] eqn:EE.\n - (* E = ev_0 *) simpl. apply ev_0.\n - (* E = ev_SS n' E' *) simpl. apply E'.\nQed.\n\nTheorem evSS_ev : forall n,\n ev (S (S n)) -> ev n.\n(** Intuitively, we know that evidence for the hypothesis cannot\n consist just of the [ev_0] constructor, since [O] and [S] are\n different constructors of the type [nat]; hence, [ev_SS] is the\n only case that applies. Unfortunately, [destruct] is not smart\n enough to realize this, and it still generates two subgoals. Even\n worse, in doing so, it keeps the final goal unchanged, failing to\n provide any useful information for completing the proof. *)\nProof.\n intros n E. \n remember (S (S n)) as k eqn:Hk.\n destruct E as [| n' E'] eqn:EE.\n - discriminate.\n - injection Hk as H. rewrite <- H. assumption.\nQed.\n\n\n(** The inversion tactic *)\nTheorem evSS_ev' : forall n,\n ev (S (S n)) -> ev n.\nProof.\n intros n E.\n inversion E as [| n' E' Heq].\n (* We are in the [E = ev_SS n' E'] case now. *)\n apply E'.\nQed.", "meta": {"author": "csci5535", "repo": "csci5535.github.io", "sha": "591108aa7b2c74a2a53f55cc80ad47ff7dd0f26d", "save_path": "github-repos/coq/csci5535-csci5535.github.io", "path": "github-repos/coq/csci5535-csci5535.github.io/csci5535.github.io-591108aa7b2c74a2a53f55cc80ad47ff7dd0f26d/coq/MyIndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.9334308045480275, "lm_q1q2_score": 0.8730812519416628}} {"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\n\nModule NatList. \n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as in this definition: *)\n\nInductive natprod : Type :=\n pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\n(** We can construct an element of [natprod] like this: *)\n\nCheck (pair 3 5).\n\n(** Here are two simple function definitions for extracting the\n first and second components of a pair. (The definitions also\n illustrate how to do pattern matching on two-argument\n constructors.) *)\n\nDefinition fst (p : natprod) : nat := \n match p with\n | pair x y => x\n end.\nDefinition snd (p : natprod) : nat := \n match p with\n | pair x y => y\n end.\n\nEval compute in (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this notation is provided as part of the standard\n library): *)\n\nEval compute in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat := \n match p with\n | (x,y) => x\n end.\nDefinition snd' (p : natprod) : nat := \n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod := \n match p with\n | (x,y) => (y,x)\n end.\n\n(** Let's try and prove a few simple facts about pairs. If we\n state the lemmas in a particular (and slightly peculiar) way, we\n can prove them with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** Note that [reflexivity] is not enough if we state the lemma in a\n more natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct].\n\n Notice that, unlike for [nat]s, [destruct] doesn't generate an\n extra subgoal here. That's because [natprod]s can only be\n constructed in one way. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p.\n destruct p as [m n].\n simpl. reflexivity.\n Qed.\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros p. destruct p as [m n].\n simpl. reflexivity.\n Qed.\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n describe the type of _lists_ of numbers like this: \"A list is\n either the empty list or else a pair of a number and another\n list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following two declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n but in case you are interested, here is roughly what's going on.\n\n The [right associativity] annotation tells Coq how to parenthesize\n expressions involving several uses of [::] so that, for example,\n the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\nNotation \"x + y\" := (plus x y) \n (at level 50, left associativity).\n The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (By the way, it's worth noting in passing that expressions like \"[1\n + 2 :: [3]]\" can be a little confusing when you read them in a .v\n file. The inner brackets, around 3, indicate a list, but the outer\n brackets, which are invisible in the HTML rendering, are there to\n instruct the \"coqdoc\" tool that the bracketed part should be\n displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist := \n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat := \n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist := \n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y) \n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\"). \n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil \n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\n\nFixpoint nonzeros (l:natlist) : natlist :=\nmatch l with\n |x::xs => if beq_nat x 0 then nonzeros xs else x :: nonzeros xs\n |nil => nil\nend.\n\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n Proof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n |x::xs => if oddb x then x::oddmembers xs else oddmembers xs\n |nil => nil\n end.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\n Proof. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat := length (oddmembers l).\n \n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers3: countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\nmatch l1, l2 with \n |x::xs, y::ys => x::y::alternate xs ys\n |nil, y::ys => l2\n |x::Xs, nil => l1\n |nil, nil => nil\nend.\n\n\nExample test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. reflexivity. Qed. \nExample test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\nExample test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].\nProof. reflexivity. Qed.\nExample test_alternate4: alternate [] [20;30] = [20;30].\nProof. reflexivity. Qed.\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n multiple times instead of just once. One reasonable\n implementation of bags is to represent a bag of numbers as a\n list. *)\n\nDefinition bag := natlist. \n\n(** **** Exercise: 3 stars (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\n\nFixpoint count (v:nat) (s:bag) : nat := \nmatch s with\n |x::xs => if beq_nat x v then S(count v xs) else count v xs\n |nil => 0\nend.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := \n v::s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool := \n negb(ble_nat (count v s) 0).\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\nmatch s with\n |x::xs => if beq_nat x v then xs else x::remove_one v xs\n |nil => nil\nend.\n\nExample test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one2: count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one3: count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_one4: count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\nmatch s with\n |x::xs => if beq_nat x v then remove_all v xs else x::remove_all v xs\n |nil => nil\nend.\n\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n match s1 with\n |x::xs => if member x s2 then subset xs (remove_one x s2) else false\n |nil => true\n end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 3 stars (bag_theorem) *)\n(** Write down an interesting theorem about bags involving the\n functions [count] and [add], and prove it. Note that, since this\n problem is somewhat open-ended, it's possible that you may come up\n with a theorem which is true, but whose proof requires techniques\n you haven't learned yet. Feel free to ask for help if you get\n stuck! *)\n\nTheorem XEqX : forall x : nat, beq_nat x x = true.\nProof.\n induction x as [|x']. reflexivity. simpl. \n rewrite -> IHx'. reflexivity.\n Qed.\n\nTheorem AddSize1 : forall (b : bag) (x : nat), count x b + 1 = count x (add x b).\nProof.\n intros b x.\n induction b as [|y ys].\n simpl. rewrite -> XEqX. reflexivity.\n simpl. rewrite -> XEqX.\n rewrite -> plus_comm. reflexivity.\n Qed.\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match position\n in the definition of [app], allowing the match itself to be\n simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n l'\". \n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proofs will not get you very far! It is\n very important to work through the details of each one, using Coq\n and thinking about what each step of the proof achieves.\n Otherwise it is more or less guaranteed that the exercises will\n make no sense. *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n perhaps a little less familiar than standard natural number\n induction, but the basic idea is equally simple. Each [Inductive]\n declaration defines a set of data values that can be built up from\n the declared constructors: a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to a number; a\n list can be either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two things together establish the\n truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_ass : forall l1 l2 l3 : natlist, \n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3). \nProof.\n intros l1 l2 l3. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons n l1'\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n static written document -- it is easy to see what's going on if\n you are reading the proof in an interactive Coq session and you\n can see the current goal and context at each point, but this state\n is not visible in the written-down parts of the Coq proof. So a\n natural-language proof -- one written for human readers -- will\n need to include more explicit signposts; in particular, it will\n help the reader stay oriented if we remind them exactly what the\n induction hypothesis is in the second case. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3], \n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n (the induction hypothesis). We must show\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]] \n By the definition of [++], this follows from\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n which is immediate from the induction hypothesis. []\n\n Here is a similar example to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist, \n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** For a slightly more involved example of an inductive proof\n over lists, suppose we define a \"cons on the right\" function\n [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist := \n match l with\n | nil => [v]\n | h :: t => h :: (snoc t v)\n end.\n\n(** ... and use it to define a list-reversing function [rev]\n like this: *)\n\nFixpoint rev (l:natlist) : natlist := \n match l with\n | nil => nil\n | h :: t => snoc (rev t) h\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** Now let's prove some more list theorems using our newly\n defined [snoc] and [rev]. For something a little more challenging\n than the inductive proofs we've seen so far, let's prove that\n reversing a list does not change its length. Our first attempt at\n this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n :: l'\".\n (* This is the tricky case. Let's begin as usual \n by simplifying. *)\n simpl. \n (* Now we seem to be stuck: the goal is an equality \n involving [snoc], but we don't have any equations \n in either the immediate context or the global \n environment that have anything to do with [snoc]! \n\n We can make a little progress by using the IH to \n rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation about [snoc] that would have\n enabled us to make progress and prove it as a separate lemma. \n*)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n length (snoc l n) = S (length l).\nProof.\n intros n l. induction l as [| n' l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n' l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed. \n\n(**\n Note that we make the lemma as _general_ as possible: in particular,\n we quantify over _all_ [natlist]s, not just those that result\n from an application of [rev]. This should seem natural, \n because the truth of the goal clearly doesn't depend on \n the list having been reversed. Moreover, it is much easier\n to prove the more general property. \n*)\n \n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons\".\n simpl. rewrite -> length_snoc. \n rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems: \n\n _Theorem_: For all numbers [n] and lists [l],\n [length (snoc l n) = S (length l)].\n \n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (snoc [] n) = S (length []),\n which follows directly from the definitions of\n [length] and [snoc].\n\n - Next, suppose [l = n'::l'], with\n length (snoc l' n) = S (length l').\n We must show\n length (snoc (n' :: l') n) = S (length (n' :: l')).\n By the definitions of [length] and [snoc], this\n follows from\n S (length (snoc l' n)) = S (S (length l')),\n]] \n which is immediate from the induction hypothesis. [] *)\n \n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n \n _Proof_: By induction on [l]. \n\n - First, suppose [l = []]. We must show\n length (rev []) = length [],\n which follows directly from the definitions of [length] \n and [rev].\n \n - Next, suppose [l = n::l'], with\n length (rev l') = length l'.\n We must show\n length (rev (n :: l')) = length (n :: l').\n By the definition of [rev], this follows from\n length (snoc (rev l') n) = S (length l')\n which, by the previous lemma, is the same as\n S (length (rev l')) = S (length l').\n This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n and pedantic. After the first few, we might find it easier to\n follow proofs that give fewer details (since we can easily work\n them out in our own minds or on scratch paper if necessary) and\n just highlight the non-obvious steps. In this more compressed\n style, the above proof might look more like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that\n length (snoc l n) = S (length l)\n for any [l]. This follows by a straightforward induction on [l].\n The main property now follows by another straightforward\n induction on [l], using the observation together with the\n induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and on how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for\n present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, using [rewrite], and later we will see other ways\n of reusing previous theorems. But in order to refer to a theorem,\n we need to know its name, and remembering the names of all the\n theorems we might ever want to use can become quite difficult! It\n is often hard even to remember what theorems have been proven,\n much less what they are named.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following to\n see a list of theorems that we have proved about [rev]: *)\n\n(* SearchAbout rev. *)\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the course; it can save you a lot of time! *)\n \n\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist, \n l ++ [] = l. \nProof.\n intros l. induction l as [|hd tl].\n reflexivity. \n simpl. rewrite -> IHtl. reflexivity.\n Qed.\n \n(** There is a short solution to the next exercise. If you find\n yourself getting tangled up, step back and try to look for a\n simpler way. *)\n \nTheorem app_ass4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros. rewrite -> app_ass.\n rewrite -> app_ass. reflexivity. Qed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n snoc l n = l ++ [n].\nProof.\n intros. induction l as [|hd tl]. reflexivity.\n simpl. rewrite -> IHtl. reflexivity. Qed.\n\nLemma SnocApp1 : forall l1 l2 h, snoc(l1 ++ l2) h = l1 ++ snoc l2 h.\nProof.\n intros.\n induction l1 as [|hd tl].\n reflexivity.\n simpl. rewrite -> IHtl. reflexivity.\n Qed.\n\nTheorem distr_rev : forall l1 l2 : natlist,\n rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n intros. induction l1 as [|hd tl].\n simpl. rewrite -> app_nil_end. reflexivity.\n simpl. rewrite -> IHtl. rewrite -> SnocApp1.\n reflexivity. Qed.\n \n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros. induction l1 as [|hd tl].\n simpl. reflexivity.\n simpl. destruct hd. simpl. rewrite -> IHtl. reflexivity.\n simpl. rewrite -> IHtl. reflexivity.\n Qed.\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 2 stars (list_design) *)\n(** Design exercise: \n - Write down a non-trivial theorem involving [cons]\n ([::]), [snoc], and [app] ([++]). \n - Prove it. *) \n\nTheorem SnocApp : forall l v, snoc l v = l ++ [v].\nProof. \n intros. induction l as [|hd tl].\n reflexivity. simpl. rewrite -> IHtl.\n reflexivity. Qed.\n\n(*This originally came after app_nil_end, I moved it down here so I could use \n**SnocApp and distr_rev to get this to work out.*)\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros l.\n induction l as [|hd tl].\n reflexivity. \n simpl. rewrite -> SnocApp. rewrite -> distr_rev. simpl. rewrite -> IHtl.\n reflexivity.\n Qed.\n\nTheorem AppMid : forall l1 v, l1 ++ (v::l1) = (snoc l1 v) ++ l1.\nProof.\n intros.\n induction l1 as [|hd tl]. reflexivity.\n simpl. rewrite -> SnocApp. rewrite -> app_ass. simpl.\n reflexivity. Qed.\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n definitions about bags in the previous problem. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n intros. reflexivity. Qed.\n\n(** The following lemma about [ble_nat] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n ble_nat n (S n) = true.\nProof.\n intros n. induction n as [| n'].\n Case \"0\". \n simpl. reflexivity.\n Case \"S n'\".\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n intros.\n induction s as [|hd tl].\n reflexivity.\n simpl. destruct hd. simpl. rewrite -> ble_n_Sn. reflexivity.\n simpl. rewrite -> IHtl. reflexivity.\n Qed.\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *) \n(** Write down an interesting theorem about bags involving the\n functions [count] and [sum], and prove it.*)\n \nTheorem CountSum : forall b1 b2 v, count v (sum b1 b2) = count v b1 + count v b2.\nProof. \n intros.\n induction b1 as [|hd tl]. reflexivity.\n simpl. destruct(beq_nat hd v). simpl. rewrite -> IHtl. reflexivity.\n rewrite -> IHtl. reflexivity. Qed.\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nThere is a hard way and an easy way to solve this exercise.\n*)\n\nTheorem rev_injective : forall l1 l2 , rev l1 = rev l2 -> l1 = l2.\nProof.\n intros. rewrite <- rev_involutive. assert(H2:l1 = rev(rev(l1))).\n rewrite -> rev_involutive. reflexivity. rewrite -> H2. \n rewrite -> H. reflexivity. Qed.\n\n(* ###################################################### *)\n(** * Options *)\n\n(** Here is another type definition that is often useful in\n day-to-day programming: *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption. \n\n(** One use of [natoption] is as a way of returning \"error\n codes\" from functions. For example, suppose we want to write a\n function that returns the [n]th element of some list. If we give\n it type [nat -> natlist -> nat], then we'll have to return some\n number when the list is too short! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with \n | true => a \n | false => index_bad (pred n) l' \n end\n end.\n\n(** On the other hand, if we give it type [nat -> natlist ->\n natoption], then we can return [None] when the list is too short\n and [Some a] when the list has enough members and [a] appears at\n position [n]. *)\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => match beq_nat n O with \n | true => Some a\n | false => index (pred n) l' \n end\n end.\n\nExample test_index1 : index 0 [4;5;6;7] = Some 4.\nProof. reflexivity. Qed.\nExample test_index2 : index 3 [4;5;6;7] = Some 7.\nProof. reflexivity. Qed.\nExample test_index3 : index 10 [4;5;6;7] = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n small feature of Coq's programming language: conditional\n expressions... *)\n\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => if beq_nat n O then Some a else index' (pred n) l'\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_opt (l : natlist) : natoption :=\nmatch l with\n |hd::tl => Some hd\n |nil => None\nend.\n\nExample test_hd_opt1 : hd_opt [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\nProof. reflexivity. Qed. \n\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_opt l).\nProof.\n intros.\n destruct l as [|hd tl]. reflexivity.\n reflexivity.\n Qed.\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\nmatch l1, l2 with\n |x::xs, y::ys => if beq_nat x y then beq_natlist xs ys else false\n |nil, nil => true\n |_, _ => false\nend.\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\nExample test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\nExample test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\n intros.\n induction l as [|hd tl].\n reflexivity. simpl. rewrite -> XEqX. rewrite -> IHtl.\n reflexivity. Qed.\n\n(* ###################################################### *)\n(** * Dictionaries *)\n\n(** As a final illustration of how fundamental data structures\n can be defined in Coq, here is the declaration of a simple\n [dictionary] data type, using numbers for both the keys and the\n values stored under these keys. (That is, a dictionary represents\n a finite map from numbers to numbers.) *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n | empty : dictionary \n | record : nat -> nat -> dictionary -> dictionary. \n\n(** This declaration can be read: \"There are two ways to construct a\n [dictionary]: either using the constructor [empty] to represent an\n empty dictionary, or by applying the constructor [record] to\n a key, a value, and an existing [dictionary] to construct a\n [dictionary] with an additional key to value mapping.\" *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n (record key value d).\n\n(** Here is a function [find] that searches a [dictionary] for a\n given key. It evaluates evaluates to [None] if the key was not\n found and [Some val] if the key was mapped to [val] in the\n dictionary. If the same key is mapped to multiple values, [find]\n will return the first one it finds. *)\n\nFixpoint find (key : nat) (d : dictionary) : natoption := \n match d with \n | empty => None\n | record k v d' => if (beq_nat key k) \n then (Some v) \n else (find key d')\n end.\n\n\n(** **** Exercise: 1 star (dictionary_invariant1) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n (find k (insert k v d)) = Some v.\nProof.\n intros. \n simpl. rewrite -> XEqX. reflexivity.\n Qed.\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),\n beq_nat m n = false -> find m d = find m (insert n o d).\nProof.\n intros.\n simpl. rewrite -> H. reflexivity. Qed.\n\n\nEnd Dictionary.\n\nEnd NatList.\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n\n", "meta": {"author": "lexxx320", "repo": "PersonalProjects", "sha": "bc83fb250467b013d9db9fe535ff7bd314632d4c", "save_path": "github-repos/coq/lexxx320-PersonalProjects", "path": "github-repos/coq/lexxx320-PersonalProjects/PersonalProjects-bc83fb250467b013d9db9fe535ff7bd314632d4c/software_foundations/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083139, "lm_q2_score": 0.9230391605990603, "lm_q1q2_score": 0.8722671226043717}} {"text": "Inductive nat : Set := \n | O : nat \n | S : nat->nat.\nCheck nat.\nCheck O.\nCheck S.\n\nReset nat.\nPrint nat.\n\n\nPrint le.\n\nTheorem zero_leq_three: 0 <= 3.\n\nProof.\n constructor 2. \n constructor 2. \n constructor 2.\n constructor 1.\n\nQed.\n\nPrint zero_leq_three.\n\n\nLemma zero_leq_three': 0 <= 3.\n repeat constructor.\nQed.\n\n\nLemma zero_lt_three : 0 < 3.\nProof.\n unfold lt.\n repeat constructor. \nQed.\n\n\nRequire Import List.\n\nPrint list.\n\nCheck list.\n\nCheck (nil (A:=nat)).\n\nCheck (nil (A:= nat -> nat)).\n\nCheck (fun A: Set => (cons (A:=A))).\n\nCheck (cons 3 (cons 2 nil)).\n\n\n\n\nRequire Import Bvector.\n\nPrint vector.\n\nCheck (Vnil nat).\n\nCheck (fun (A:Set)(a:A)=> Vcons _ a _ (Vnil _)).\n\nCheck (Vcons _ 5 _ (Vcons _ 3 _ (Vnil _))).\n\n\n\n\n\n\n\n\n\n\n\n\n\nLemma eq_3_3 : 2 + 1 = 3.\nProof.\n reflexivity.\nQed.\nPrint eq_3_3.\n\nLemma eq_proof_proof : refl_equal (2*6) = refl_equal (3*4).\nProof.\n reflexivity.\nQed.\nPrint eq_proof_proof.\n\nLemma eq_lt_le : ( 2 < 4) = (3 <= 4).\nProof.\n reflexivity.\nQed.\n\nLemma eq_nat_nat : nat = nat.\nProof.\n reflexivity.\nQed.\n\nLemma eq_Set_Set : Set = Set.\nProof.\n reflexivity.\nQed.\n\nLemma eq_Type_Type : Type = Type.\nProof.\n reflexivity.\nQed.\n\n\nCheck (2 + 1 = 3).\n\n\nCheck (Type = Type).\n\nGoal Type = Type.\nreflexivity.\nQed.\n\n\nPrint or.\n\nPrint and.\n\n\nPrint sumbool.\n\nPrint ex.\n\nRequire Import ZArith.\nRequire Import Compare_dec.\n\nCheck le_lt_dec.\n\nDefinition max (n p :nat) := match le_lt_dec n p with \n | left _ => p\n | right _ => n\n end.\n\nTheorem le_max : forall n p, n <= p -> max n p = p.\nProof.\n intros n p ; unfold max ; case (le_lt_dec n p); simpl.\n trivial.\n intros; absurd (p < p); eauto with arith.\nQed.\n\nExtraction max.\n\n\n\n\n\n\nInductive tree(A:Set) : Set :=\n node : A -> forest A -> tree A \nwith\n forest (A: Set) : Set := \n nochild : forest A |\n addchild : tree A -> forest A -> forest A.\n\n\n\n\n\nInductive \n even : nat->Prop :=\n evenO : even O |\n evenS : forall n, odd n -> even (S n)\nwith\n odd : nat->Prop :=\n oddS : forall n, even n -> odd (S n).\n\nLemma odd_49 : odd (7 * 7).\n simpl; repeat constructor.\nQed.\n\n\n\nDefinition nat_case := \n fun (Q : Type)(g0 : Q)(g1 : nat -> Q)(n:nat) =>\n match n return Q with\n | 0 => g0 \n | S p => g1 p \n end.\n\nEval simpl in (nat_case nat 0 (fun p => p) 34).\n\nEval simpl in (fun g0 g1 => nat_case nat g0 g1 34).\n\nEval simpl in (fun g0 g1 => nat_case nat g0 g1 0).\n\n\nDefinition pred (n:nat) := match n with O => O | S m => m end.\n\nEval simpl in pred 56.\n\nEval simpl in pred 0.\n\nEval simpl in fun p => pred (S p).\n\n\nDefinition xorb (b1 b2:bool) :=\nmatch b1, b2 with \n | false, true => true\n | true, false => true\n | _ , _ => false\nend.\n\n\n Definition pred_spec (n:nat) := {m:nat | n=0 /\\ m=0 \\/ n = S m}.\n \n\n Definition predecessor : forall n:nat, pred_spec n.\n intro n;case n.\n unfold pred_spec;exists 0;auto.\n unfold pred_spec; intro n0;exists n0; auto.\n Defined.\n\nPrint predecessor.\n\nExtraction predecessor.\n\nTheorem nat_expand : \n forall n:nat, n = match n with 0 => 0 | S p => S p end.\n intro n;case n;simpl;auto.\nQed.\n\nCheck (fun p:False => match p return 2=3 with end).\n\nTheorem fromFalse : False -> 0=1.\n intro absurd. \n contradiction.\nQed.\n\nSection equality_elimination.\n Variables (A: Type)\n (a b : A)\n (p : a = b)\n (Q : A -> Type).\n Check (fun H : Q a =>\n match p in (eq _ y) return Q y with\n refl_equal => H\n end).\n\nEnd equality_elimination.\n\n \nTheorem trans : forall n m p:nat, n=m -> m=p -> n=p.\nProof.\n intros n m p eqnm. \n case eqnm.\n trivial. \nQed.\n\nLemma Rw : forall x y: nat, y = y * x -> y * x * x = y.\n intros x y e; do 2 rewrite <- e.\n reflexivity.\nQed.\n\n\nRequire Import Arith.\n\nCheck mult_1_l.\n(*\nmult_1_l\n : forall n : nat, 1 * n = n\n*)\n\nCheck mult_plus_distr_r.\n(*\nmult_plus_distr_r\n : forall n m p : nat, (n + m) * p = n * p + m * p\n\n*)\n\nLemma mult_distr_S : forall n p : nat, n * p + p = (S n)* p.\n simpl;auto with arith.\nQed.\n\nLemma four_n : forall n:nat, n+n+n+n = 4*n.\n intro n;rewrite <- (mult_1_l n).\n\n Undo.\n intro n; pattern n at 1.\n \n\n rewrite <- mult_1_l.\n repeat rewrite mult_distr_S.\n trivial.\nQed.\n\n\nSection Le_case_analysis.\n Variables (n p : nat)\n (H : n <= p)\n (Q : nat -> Prop)\n (H0 : Q n)\n (HS : forall m, n <= m -> Q (S m)).\n Check (\n match H in (_ <= q) return (Q q) with\n | le_n => H0\n | le_S m Hm => HS m Hm\n end\n ).\n\n\nEnd Le_case_analysis.\n\n\nLemma predecessor_of_positive : forall n, 1 <= n -> exists p:nat, n = S p.\nProof.\n intros n H; case H.\n exists 0; trivial.\n intros m Hm; exists m;trivial.\nQed.\n\nDefinition Vtail_total \n (A : Set) (n : nat) (v : vector A n) : vector A (pred n):=\nmatch v in (vector _ n0) return (vector A (pred n0)) with\n| Vnil => Vnil A\n| Vcons _ n0 v0 => v0\nend.\n\nDefinition Vtail' (A:Set)(n:nat)(v:vector A n) : vector A (pred n).\n intros A n v; case v. \n simpl.\n exact (Vnil A).\n simpl.\n auto.\nDefined.\n\n(*\nInductive Lambda : Set :=\n lambda : (Lambda -> False) -> Lambda. \n\n\nError: Non strictly positive occurrence of \"Lambda\" in\n \"(Lambda -> False) -> Lambda\"\n\n*)\n\nSection Paradox.\n Variable Lambda : Set.\n Variable lambda : (Lambda -> False) ->Lambda.\n\n Variable matchL : Lambda -> forall Q:Prop, ((Lambda ->False) -> Q) -> Q.\n (*\n understand matchL Q l (fun h : Lambda -> False => t)\n\n as match l return Q with lambda h => t end \n *)\n\n Definition application (f x: Lambda) :False :=\n matchL f False (fun h => h x).\n\n Definition Delta : Lambda := lambda (fun x : Lambda => application x x).\n\n Definition loop : False := application Delta Delta.\n\n Theorem two_is_three : 2 = 3.\n Proof.\n elim loop.\n Qed.\n\nEnd Paradox.\n\n\nRequire Import ZArith.\n\n\n\nInductive itree : Set :=\n| ileaf : itree\n| inode : Z-> (nat -> itree) -> itree.\n\nDefinition isingle l := inode l (fun i => ileaf).\n\nDefinition t1 := inode 0 (fun n => isingle (Z_of_nat (2*n))).\n\nDefinition t2 := inode 0 \n (fun n : nat => \n inode (Z_of_nat n)\n (fun p => isingle (Z_of_nat (n*p)))).\n\n\nInductive itree_le : itree-> itree -> Prop :=\n | le_leaf : forall t, itree_le ileaf t\n | le_node : forall l l' s s', \n Zle l l' -> \n (forall i, exists j:nat, itree_le (s i) (s' j)) -> \n itree_le (inode l s) (inode l' s').\n\n\nTheorem itree_le_trans : \n forall t t', itree_le t t' ->\n forall t'', itree_le t' t'' -> itree_le t t''.\n induction t.\n constructor 1.\n \n intros t'; case t'.\n inversion 1.\n intros z0 i0 H0.\n intro t'';case t''.\n inversion 1.\n intros.\n inversion_clear H1.\n constructor 2.\n inversion_clear H0;eauto with zarith.\n inversion_clear H0.\n intro i2; case (H4 i2).\n intros.\n generalize (H i2 _ H0). \n intros.\n case (H3 x);intros.\n generalize (H5 _ H6).\n exists x0;auto.\nQed.\n\n \n\nInductive itree_le' : itree-> itree -> Prop :=\n | le_leaf' : forall t, itree_le' ileaf t\n | le_node' : forall l l' s s' g, \n Zle l l' -> \n (forall i, itree_le' (s i) (s' (g i))) -> \n itree_le' (inode l s) (inode l' s').\n\n\n\n\n\nLemma t1_le_t2 : itree_le t1 t2.\n unfold t1, t2.\n constructor.\n auto with zarith.\n intro i; exists (2 * i).\n unfold isingle. \n constructor.\n auto with zarith.\n exists i;constructor.\nQed.\n\n\n\nLemma t1_le'_t2 : itree_le' t1 t2.\n unfold t1, t2.\n constructor 2 with (fun i : nat => 2 * i).\n auto with zarith.\n unfold isingle;\n intro i ; constructor 2 with (fun i :nat => i).\n auto with zarith.\n constructor .\nQed.\n\n\nRequire Import List.\n\nInductive ltree (A:Set) : Set := \n lnode : A -> list (ltree A) -> ltree A.\n\nInductive prop : Prop :=\n prop_intro : Prop -> prop.\n\nLemma prop_inject: prop.\nProof prop_intro prop.\n\n\nInductive ex_Prop (P : Prop -> Prop) : Prop :=\n exP_intro : forall X : Prop, P X -> ex_Prop P.\n\nLemma ex_Prop_inhabitant : ex_Prop (fun P => P -> P).\nProof.\n exists (ex_Prop (fun P => P -> P)).\n trivial.\nQed.\n\n\n\n\n(*\n\nCheck (fun (P:Prop->Prop)(p: ex_Prop P) =>\n match p with exP_intro X HX => X end).\nError:\nIncorrect elimination of \"p\" in the inductive type \n\"ex_Prop\", the return type has sort \"Type\" while it should be \n\"Prop\"\n\nElimination of an inductive object of sort \"Prop\"\nis not allowed on a predicate in sort \"Type\"\nbecause proofs can be eliminated only to build proofs\n\n*)\n\n(*\nCheck (match prop_inject with (prop_intro P p) => P end).\n\nError:\nIncorrect elimination of \"prop_inject\" in the inductive type \n\"prop\", the return type has sort \"Type\" while it should be \n\"Prop\"\n\nElimination of an inductive object of sort \"Prop\"\nis not allowed on a predicate in sort \"Type\"\nbecause proofs can be eliminated only to build proofs\n\n*)\nPrint prop_inject.\n\n(*\nprop_inject = \nprop_inject = prop_intro prop (fun H : prop => H)\n : prop\n*)\n\n\nInductive typ : Type := \n typ_intro : Type -> typ. \n\nDefinition typ_inject: typ.\nsplit. \nexact typ.\n(*\nDefined.\n\nError: Universe Inconsistency.\n*)\nAbort.\n(*\n\nInductive aSet : Set :=\n aSet_intro: Set -> aSet.\n\n\nUser error: Large non-propositional inductive types must be in Type\n\n*)\n\nInductive ex_Set (P : Set -> Prop) : Type :=\n exS_intro : forall X : Set, P X -> ex_Set P.\n\n\nInductive comes_from_the_left (P Q:Prop): P \\/ Q -> Prop :=\n c1 : forall p, comes_from_the_left P Q (or_introl (A:=P) Q p).\n\nGoal (comes_from_the_left _ _ (or_introl True I)).\nsplit.\nQed.\n\nGoal ~(comes_from_the_left _ _ (or_intror True I)).\n red;inversion 1.\n (* discriminate H0.\n *)\nAbort.\n\nReset comes_from_the_left.\n\n(*\n\n\n\n\n\n\n Definition comes_from_the_left (P Q:Prop)(H:P \\/ Q): Prop :=\n match H with\n | or_introl p => True \n | or_intror q => False\n end.\n\nError:\nIncorrect elimination of \"H\" in the inductive type \n\"or\", the return type has sort \"Type\" while it should be \n\"Prop\"\n\nElimination of an inductive object of sort \"Prop\"\nis not allowed on a predicate in sort \"Type\"\nbecause proofs can be eliminated only to build proofs\n\n*)\n\nDefinition comes_from_the_left_sumbool\n (P Q:Prop)(x:{P}+{Q}): Prop :=\n match x with\n | left p => True \n | right q => False\n end.\n\n\n\n \nClose Scope Z_scope.\n\n\n\n\n\nTheorem S_is_not_O : forall n, S n <> 0. \n\nDefinition Is_zero (x:nat):= match x with \n | 0 => True \n | _ => False\n end.\n Lemma O_is_zero : forall m, m = 0 -> Is_zero m.\n Proof.\n intros m H; subst m.\n (* \n ============================\n Is_zero 0\n *)\n simpl;trivial.\n Qed.\n \n red; intros n Hn.\n apply O_is_zero with (m := S n).\n assumption.\nQed.\n\nTheorem disc2 : forall n, S (S n) <> 1. \nProof.\n intros n Hn; discriminate.\nQed.\n\n\nTheorem disc3 : forall n, S (S n) = 0 -> forall Q:Prop, Q.\nProof.\n intros n Hn Q.\n discriminate.\nQed.\n\n\n\nTheorem inj_succ : forall n m, S n = S m -> n = m.\nProof.\n \n\nLemma inj_pred : forall n m, n = m -> pred n = pred m.\nProof.\n intros n m eq_n_m.\n rewrite eq_n_m.\n trivial.\nQed.\n\n intros n m eq_Sn_Sm.\n apply inj_pred with (n:= S n) (m := S m); assumption.\nQed.\n\nLemma list_inject : forall (A:Set)(a b :A)(l l':list A),\n a :: b :: l = b :: a :: l' -> a = b /\\ l = l'.\nProof.\n intros A a b l l' e.\n injection e.\n auto.\nQed.\n\n\nTheorem not_le_Sn_0 : forall n:nat, ~ (S n <= 0).\nProof.\n red; intros n H.\n case H.\nUndo.\n\nLemma not_le_Sn_0_with_constraints :\n forall n p , S n <= p -> p = 0 -> False.\nProof.\n intros n p H; case H ;\n intros; discriminate.\nQed.\n \neapply not_le_Sn_0_with_constraints; eauto.\nQed. \n\n\nTheorem not_le_Sn_0' : forall n:nat, ~ (S n <= 0).\nProof.\n red; intros n H ; inversion H.\nQed.\n\nDerive Inversion le_Sn_0_inv with (forall n :nat, S n <= 0).\nCheck le_Sn_0_inv.\n\nTheorem le_Sn_0'' : forall n p : nat, ~ S n <= 0 .\nProof.\n intros n p H; \n inversion H using le_Sn_0_inv.\nQed.\n\nDerive Inversion_clear le_Sn_0_inv' with (forall n :nat, S n <= 0).\nCheck le_Sn_0_inv'.\n\n\nTheorem le_reverse_rules : \n forall n m:nat, n <= m -> \n n = m \\/ \n exists p, n <= p /\\ m = S p.\nProof.\n intros n m H; inversion H.\n left;trivial.\n right; exists m0; split; trivial.\nRestart.\n intros n m H; inversion_clear H.\n left;trivial.\n right; exists m0; split; trivial.\nQed.\n\nInductive ArithExp : Set :=\n Zero : ArithExp \n | Succ : ArithExp -> ArithExp\n | Plus : ArithExp -> ArithExp -> ArithExp.\n\nInductive RewriteRel : ArithExp -> ArithExp -> Prop :=\n RewSucc : forall e1 e2 :ArithExp,\n RewriteRel e1 e2 -> RewriteRel (Succ e1) (Succ e2) \n | RewPlus0 : forall e:ArithExp,\n RewriteRel (Plus Zero e) e \n | RewPlusS : forall e1 e2:ArithExp,\n RewriteRel e1 e2 ->\n RewriteRel (Plus (Succ e1) e2) (Succ (Plus e1 e2)).\n\n\n \nFixpoint plus (n p:nat) {struct n} : nat :=\n match n with\n | 0 => p\n | S m => S (plus m p)\n end.\n\nFixpoint plus' (n p:nat) {struct p} : nat :=\n match p with\n | 0 => n\n | S q => S (plus' n q)\n end.\n\nFixpoint plus'' (n p:nat) {struct n} : nat :=\n match n with\n | 0 => p\n | S m => plus'' m (S p)\n end.\n\n\nFixpoint even_test (n:nat) : bool :=\n match n \n with 0 => true\n | 1 => false\n | S (S p) => even_test p\n end.\n\n\nReset even_test.\n\nFixpoint even_test (n:nat) : bool :=\n match n \n with \n | 0 => true\n | S p => odd_test p\n end\nwith odd_test (n:nat) : bool :=\n match n\n with \n | 0 => false\n | S p => even_test p\n end.\n\n\n \nEval simpl in even_test.\n\n\n\nEval simpl in (fun x : nat => even_test x).\n\nEval simpl in (fun x : nat => plus 5 x).\nEval simpl in (fun x : nat => even_test (plus 5 x)).\n\nEval simpl in (fun x : nat => even_test (plus x 5)).\n\n\nSection Principle_of_Induction.\nVariable P : nat -> Prop.\nHypothesis base_case : P 0.\nHypothesis inductive_step : forall n:nat, P n -> P (S n).\nFixpoint nat_ind (n:nat) : (P n) := \n match n return P n with\n | 0 => base_case\n | S m => inductive_step m (nat_ind m)\n end. \n\nEnd Principle_of_Induction.\n\nScheme Even_induction := Minimality for even Sort Prop\nwith Odd_induction := Minimality for odd Sort Prop.\n\nTheorem even_plus_four : forall n:nat, even n -> even (4+n).\nProof.\n intros n H.\n elim H using Even_induction with (P0 := fun n => odd (4+n));\n simpl;repeat constructor;assumption.\nQed.\n\n\nSection Principle_of_Double_Induction.\nVariable P : nat -> nat ->Prop.\nHypothesis base_case1 : forall x:nat, P 0 x.\nHypothesis base_case2 : forall x:nat, P (S x) 0.\nHypothesis inductive_step : forall n m:nat, P n m -> P (S n) (S m).\nFixpoint nat_double_ind (n m:nat){struct n} : P n m := \n match n, m return P n m with \n | 0 , x => base_case1 x \n | (S x), 0 => base_case2 x\n | (S x), (S y) => inductive_step x y (nat_double_ind x y)\n end.\nEnd Principle_of_Double_Induction.\n\nSection Principle_of_Double_Recursion.\nVariable P : nat -> nat -> Set.\nHypothesis base_case1 : forall x:nat, P 0 x.\nHypothesis base_case2 : forall x:nat, P (S x) 0.\nHypothesis inductive_step : forall n m:nat, P n m -> P (S n) (S m).\nFixpoint nat_double_rec (n m:nat){struct n} : P n m := \n match n, m return P n m with \n | 0 , x => base_case1 x \n | (S x), 0 => base_case2 x\n | (S x), (S y) => inductive_step x y (nat_double_rec x y)\n end.\nEnd Principle_of_Double_Recursion.\n\nDefinition min : nat -> nat -> nat := \n nat_double_rec (fun (x y:nat) => nat)\n (fun (x:nat) => 0)\n (fun (y:nat) => 0)\n (fun (x y r:nat) => S r).\n\nEval compute in (min 5 8).\nEval compute in (min 8 5).\n\n\n\nLemma not_circular : forall n:nat, n <> S n.\nProof.\n intro n.\n apply nat_ind with (P:= fun n => n <> S n).\n discriminate.\n red; intros n0 Hn0 eqn0Sn0;injection eqn0Sn0;trivial.\nQed.\n\nDefinition eq_nat_dec : forall n p:nat , {n=p}+{n <> p}.\nProof.\n intros n p.\n apply nat_double_rec with (P:= fun (n q:nat) => {q=p}+{q <> p}).\nUndo.\n pattern p,n.\n elim n using nat_double_rec.\n destruct x; auto.\n destruct x; auto.\n intros n0 m H; case H.\n intro eq; rewrite eq ; auto.\n intro neg; right; red ; injection 1; auto.\nDefined.\n\nDefinition eq_nat_dec' : forall n p:nat, {n=p}+{n <> p}.\n decide equality.\nDefined.\n\nPrint Acc.\n\n\nRequire Import Minus.\n\n(*\nFixpoint div (x y:nat){struct x}: nat :=\n if eq_nat_dec x 0 \n then 0\n else if eq_nat_dec y 0\n then x\n else S (div (x-y) y).\n\nError:\nRecursive definition of div is ill-formed.\nIn environment\ndiv : nat -> nat -> nat\nx : nat\ny : nat\n_ : x <> 0\n_ : y <> 0\n\nRecursive call to div has principal argument equal to\n\"x - y\"\ninstead of a subterm of x\n\n*)\n\nLemma minus_smaller_S: forall x y:nat, x - y < S x.\nProof.\n intros x y; pattern y, x;\n elim x using nat_double_ind.\n destruct x0; auto with arith.\n simpl; auto with arith.\n simpl; auto with arith.\nQed.\n\nLemma minus_smaller_positive : forall x y:nat, x <>0 -> y <> 0 ->\n x - y < x.\nProof.\n destruct x; destruct y; \n ( simpl;intros; apply minus_smaller_S || \n intros; absurd (0=0); auto).\nQed.\n\nDefinition minus_decrease : forall x y:nat, Acc lt x -> \n x <> 0 -> \n y <> 0 ->\n Acc lt (x-y).\nProof.\n intros x y H; case H.\n intros z Hz posz posy. \n apply Hz; apply minus_smaller_positive; assumption.\nDefined.\n\nPrint minus_decrease.\n\n\n\nDefinition div_aux (x y:nat)(H: Acc lt x):nat.\n fix 3.\n intros.\n refine (if eq_nat_dec x 0 \n then 0 \n else if eq_nat_dec y 0 \n then y\n else div_aux (x-y) y _).\n apply (minus_decrease x y H);assumption. \nDefined.\n\n\nPrint div_aux.\n(*\ndiv_aux = \n(fix div_aux (x y : nat) (H : Acc lt x) {struct H} : nat :=\n match eq_nat_dec x 0 with\n | left _ => 0\n | right _ =>\n match eq_nat_dec y 0 with\n | left _ => y\n | right _0 => div_aux (x - y) y (minus_decrease x y H _ _0)\n end\n end)\n : forall x : nat, nat -> Acc lt x -> nat\n*)\n\nRequire Import Wf_nat.\nDefinition div x y := div_aux x y (lt_wf x). \n\nExtraction div.\n(*\nlet div x y =\n div_aux x y\n*)\n\nExtraction div_aux.\n\n(*\nlet rec div_aux x y =\n match eq_nat_dec x O with\n | Left -> O\n | Right ->\n (match eq_nat_dec y O with\n | Left -> y\n | Right -> div_aux (minus x y) y)\n*)\n\nLemma vector0_is_vnil : forall (A:Set)(v:vector A 0), v = Vnil A.\nProof.\n intros A v;inversion v.\nAbort.\n\n(*\n Lemma vector0_is_vnil_aux : forall (A:Set)(n:nat)(v:vector A n), \n n= 0 -> v = Vnil A.\n\nToplevel input, characters 40281-40287\n> Lemma vector0_is_vnil_aux : forall (A:Set)(n:nat)(v:vector A n), n= 0 -> v = Vnil A.\n> ^^^^^^\nError: In environment\nA : Set\nn : nat\nv : vector A n\ne : n = 0\nThe term \"Vnil A\" has type \"vector A 0\" while it is expected to have type\n \"vector A n\"\n*)\n Require Import JMeq.\n\nLemma vector0_is_vnil_aux : forall (A:Set)(n:nat)(v:vector A n), \n n= 0 -> JMeq v (Vnil A).\nProof.\n destruct v.\n auto.\n intro; discriminate.\nQed.\n\nLemma vector0_is_vnil : forall (A:Set)(v:vector A 0), v = Vnil A.\nProof.\n intros a v;apply JMeq_eq.\n apply vector0_is_vnil_aux.\n trivial.\nQed.\n\n\nImplicit Arguments Vcons [A n].\nImplicit Arguments Vnil [A].\nImplicit Arguments Vhead [A n].\nImplicit Arguments Vtail [A n].\n\nDefinition Vid : forall (A : Set)(n:nat), vector A n -> vector A n.\nProof.\n destruct n; intro v.\n exact Vnil.\n exact (Vcons (Vhead v) (Vtail v)).\nDefined.\n\nEval simpl in (fun (A:Set)(v:vector A 0) => (Vid _ _ v)).\n\nEval simpl in (fun (A:Set)(v:vector A 0) => v).\n\n\n\nLemma Vid_eq : forall (n:nat) (A:Set)(v:vector A n), v=(Vid _ n v).\nProof.\n destruct v. \n reflexivity.\n reflexivity.\nDefined.\n\nTheorem zero_nil : forall A (v:vector A 0), v = Vnil.\nProof.\n intros.\n change (Vnil (A:=A)) with (Vid _ 0 v). \n apply Vid_eq.\nDefined.\n\n\nTheorem decomp :\n forall (A : Set) (n : nat) (v : vector A (S n)),\n v = Vcons (Vhead v) (Vtail v).\nProof.\n intros.\n change (Vcons (Vhead v) (Vtail v)) with (Vid _ (S n) v).\n apply Vid_eq.\nDefined.\n\n\n\nDefinition vector_double_rect : \n forall (A:Set) (P: forall (n:nat),(vector A n)->(vector A n) -> Type),\n P 0 Vnil Vnil ->\n (forall n (v1 v2 : vector A n) a b, P n v1 v2 ->\n P (S n) (Vcons a v1) (Vcons b v2)) ->\n forall n (v1 v2 : vector A n), P n v1 v2.\n induction n.\n intros; rewrite (zero_nil _ v1); rewrite (zero_nil _ v2).\n auto.\n intros v1 v2; rewrite (decomp _ _ v1);rewrite (decomp _ _ v2).\n apply X0; auto.\nDefined.\n\nRequire Import Bool.\n\nDefinition bitwise_or n v1 v2 : vector bool n :=\n vector_double_rect bool (fun n v1 v2 => vector bool n)\n Vnil\n (fun n v1 v2 a b r => Vcons (orb a b) r) n v1 v2.\n\n\nFixpoint vector_nth (A:Set)(n:nat)(p:nat)(v:vector A p){struct v}\n : option A :=\n match n,v with\n _ , Vnil => None\n | 0 , Vcons b _ _ => Some b\n | S n', Vcons _ p' v' => vector_nth A n' p' v'\n end.\n\nImplicit Arguments vector_nth [A p].\n\n\nLemma nth_bitwise : forall (n:nat) (v1 v2: vector bool n) i a b,\n vector_nth i v1 = Some a ->\n vector_nth i v2 = Some b ->\n vector_nth i (bitwise_or _ v1 v2) = Some (orb a b).\nProof.\n intros n v1 v2; pattern n,v1,v2.\n apply vector_double_rect.\n simpl.\n destruct i; discriminate 1.\n destruct i; simpl;auto.\n injection 1; injection 2;intros; subst a; subst b; auto.\nQed.\n\n Set Implicit Arguments.\n\n CoInductive Stream (A:Set) : Set :=\n | Cons : A -> Stream A -> Stream A.\n\n CoInductive LList (A: Set) : Set :=\n | LNil : LList A\n | LCons : A -> LList A -> LList A.\n\n\n \n\n\n Definition head (A:Set)(s : Stream A) := match s with Cons a s' => a end.\n\n Definition tail (A : Set)(s : Stream A) :=\n match s with Cons a s' => s' end.\n\n CoFixpoint repeat (A:Set)(a:A) : Stream A := Cons a (repeat a).\n\n CoFixpoint iterate (A: Set)(f: A -> A)(a : A) : Stream A:=\n Cons a (iterate f (f a)).\n\n CoFixpoint map (A B:Set)(f: A -> B)(s : Stream A) : Stream B:=\n match s with Cons a tl => Cons (f a) (map f tl) end.\n\nEval simpl in (fun (A:Set)(a:A) => repeat a).\n\nEval simpl in (fun (A:Set)(a:A) => head (repeat a)).\n\n\nCoInductive EqSt (A: Set) : Stream A -> Stream A -> Prop :=\n eqst : forall s1 s2: Stream A,\n head s1 = head s2 ->\n EqSt (tail s1) (tail s2) ->\n EqSt s1 s2.\n\n\nSection Parks_Principle.\nVariable A : Set.\nVariable R : Stream A -> Stream A -> Prop.\nHypothesis bisim1 : forall s1 s2:Stream A, R s1 s2 ->\n head s1 = head s2.\nHypothesis bisim2 : forall s1 s2:Stream A, R s1 s2 ->\n R (tail s1) (tail s2).\n\nCoFixpoint park_ppl : forall s1 s2:Stream A, R s1 s2 ->\n EqSt s1 s2 :=\n fun s1 s2 (p : R s1 s2) =>\n eqst s1 s2 (bisim1 p) \n (park_ppl (bisim2 p)).\nEnd Parks_Principle.\n\n\nTheorem map_iterate : forall (A:Set)(f:A->A)(x:A),\n EqSt (iterate f (f x)) (map f (iterate f x)).\nProof.\n intros A f x.\n apply park_ppl with\n (R:= fun s1 s2 => exists x: A, \n s1 = iterate f (f x) /\\ s2 = map f (iterate f x)).\n\n intros s1 s2 (x0,(eqs1,eqs2));rewrite eqs1;rewrite eqs2;reflexivity.\n intros s1 s2 (x0,(eqs1,eqs2)).\n exists (f x0);split;[rewrite eqs1|rewrite eqs2]; reflexivity.\n exists x;split; reflexivity.\nQed.\n\nLtac infiniteproof f :=\n cofix f; constructor; [clear f| simpl; try (apply f; clear f)].\n\n\nTheorem map_iterate' : forall (A:Set)(f:A->A)(x:A),\n EqSt (iterate f (f x)) (map f (iterate f x)).\ninfiniteproof map_iterate'.\n reflexivity.\nQed.\n\n\nImplicit Arguments LNil [A].\n\nLemma Lnil_not_Lcons : forall (A:Set)(a:A)(l:LList A),\n LNil <> (LCons a l).\n intros;discriminate.\nQed.\n\nLemma injection_demo : forall (A:Set)(a b : A)(l l': LList A),\n LCons a (LCons b l) = LCons b (LCons a l') ->\n a = b /\\ l = l'.\nProof.\n intros A a b l l' e; injection e; auto.\nQed.\n\n\nInductive Finite (A:Set) : LList A -> Prop :=\n| Lnil_fin : Finite (LNil (A:=A))\n| Lcons_fin : forall a l, Finite l -> Finite (LCons a l).\n\nCoInductive Infinite (A:Set) : LList A -> Prop :=\n| LCons_inf : forall a l, Infinite l -> Infinite (LCons a l).\n\nLemma LNil_not_Infinite : forall (A:Set), ~ Infinite (LNil (A:=A)).\nProof.\n intros A H;inversion H.\nQed.\n\nLemma Finite_not_Infinite : forall (A:Set)(l:LList A),\n Finite l -> ~ Infinite l.\nProof.\n intros A l H; elim H.\n apply LNil_not_Infinite.\n intros a l0 F0 I0' I1.\n case I0'; inversion_clear I1.\n trivial.\nQed.\n\nLemma Not_Finite_Infinite : forall (A:Set)(l:LList A),\n ~ Finite l -> Infinite l.\nProof.\n cofix H.\n destruct l.\n intro; absurd (Finite (LNil (A:=A)));[auto|constructor].\n constructor.\n apply H.\n red; intro H1;case H0.\n constructor.\n trivial.\nQed.\n\n\n\n\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/IndTutorial/RecTutorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541528387691, "lm_q2_score": 0.9263037236819582, "lm_q1q2_score": 0.8722577481951316}} {"text": "From NAT Require Import Peanos_axioms.\nFrom NAT Require Import Tutorial_World.\nSection Addition_World.\n\n(*Now that the tutorial is complete we can begin to prove something a little more difficult. Namely, that 0 + n = n. Obvious, says your intro to proof student, but of course it is not nearly as trivial as it sounds, since good old Peano, in his hurry, did not leave us an axiom that says addition is commutative. Our only option then is to prove it, which we will do now.*)\nProposition zero_add (n : nat) : 0 + n = n.\nProof.\n induction n.\n(*In this step we are doing induction on n. This is a good moment to remind yourself how the naturals are formally defined. In some sense the naturals consist of two things, 0, and something that is one more than something else. induction knows this (since the naturals are inductively defined) and allows us to prove our proposition for the 0-case (the base case) and then allows us to prove the proposition for the inductive step.*)\n rewrite add_zero. reflexivity.\n(*Now we just need to do some cleaning up and our base case is complete. If you are starting to feel tired of all this explicit computation you are not alone, and there are tactics that can make these steps trivial. But for now your suffering is rewarded, in that you will actually understand what Coq is doing. Eventually, though, it will become neccesary to use these tactics in order to avoid tedium, but by then we will know what goes into them, and will only use the old ones to show off to our readers.*)\n(*Now it is time to do our inductive step.*)\n rewrite succ_add.\n rewrite IHn.\n reflexivity.\nQed.\n\n(*Now that we have our result we can finally prove a big result about the natural numbers, that their addition is associative!*)\nProposition add_assoc (a b c : nat) : (a + b) + c = a + (b + c). \nProof.\n induction c.\n(*We will choose to do induction on c, by way of knowing that the other choices will bring us pain, although this is a good lesson on not getting to entrenched on your choice of inductive variable, if there are others available, else you spend lots of time trying to induct on a. The author of this file would never commit such an error, though, and since no backlogs of this file exist, I dare you to prove (forgive the pun) otherwise. *)\n rewrite add_zero. rewrite add_zero. reflexivity.\n(*again, we must do some simple computations in order to arrive at the conclusion of our base case.*)\n rewrite succ_add. rewrite succ_add. rewrite succ_add.\n rewrite IHc.\n reflexivity.\nQed.\n\n(*Again, our next proposition looks like something that we already know, and thus, highlights the importance of using a theorem prover, since this statment is NOT something we already know, at least not formally. Remember Peano said that x + S a = S (x + a) and at the moment, we have no commutativity, so if we wish to use this fact we must actually sit down and prove it.*)\nProposition add_succ (a b : nat) : (S a) + b = S (a + b).\nProof.\n induction b.\n rewrite add_zero. rewrite add_zero. reflexivity.\n rewrite succ_add.\n rewrite succ_add.\n rewrite IHb.\n reflexivity.\nQed.\n(*WE COULD HAVE THE USER USE AN END OF PROOF SYMBOL FOR REFL, THAT WAY IT \nCAN BE DONE WITHOUT USER IMPUT*)\n\n(*Now that we have many of the proofs we want in order to manipulate addition we can move on to prove the commutivity. You may have noticed that all of these propositions seem to follow fairly quickly from previous results. This is something that should be strived for, since especially in theorem provers, extremely long arguments tend to become cumbersome and confusing. Furthermore, if every lemma and sub-proof is proven in your proposition then you will have to prove them all again when you try and prove a similair theorem! Therefore, if possible it is good to prove many small theoreoms, and then combine them for your result.*)\nProposition commute (m n : nat) : m + n = n + m. \nProof.\n induction n.\n rewrite add_zero. rewrite zero_add. reflexivity.\n rewrite succ_add.\n rewrite add_succ.\n rewrite IHn.\n reflexivity.\nQed.\n\nProposition add_one (n : nat) : S n = n + 1.\nProof.\n rewrite commute.\n reflexivity.\n(*What on Earth, you say? Why did that work. Well remember that S n \"stands for\" 1 + n. In some sense Coq cannot tell the difference between them! On the other hand n + 1 is a mysterious, unknown, and potentially distinct object. Therefore, if you attempt to just complete this proof using only reflexivity, Coq will protest, and you will be met with an error.*)\nQed.\n\n(*This proposition is designed in order to exibit how Coq uses parenthesis. Unfortunately, for addition it is left-ward associative, which while being the norm throughout most of mathematics, is counter to the convention in Type Theory, and thus earned itself snippy remark from the author. *)\nProposition rcomm ( m n k : nat) : (m + n) + k = (m + k) + n.\nProof.\n symmetry.\n rewrite add_assoc.\n rewrite commute.\n rewrite add_assoc.\n rewrite commute.\n rewrite (commute n m).\n(*This line highlighs an important point. Up until now we have not specified where we want out tactics and propositions to act. This is usually fine, Coq will just look for somewhere that it can apply the proposition, and most of the time the only place it can do so is where we intended it. On the other hand, if there are many options then Coq will just choose the first one, and if that is not what we intended then it is neccsary to give it more information on where exactly we want it to act.*)\n reflexivity.\nQed.\n\nEnd Addition_World.", "meta": {"author": "brandon-sisler", "repo": "Intros-Blockly", "sha": "c8a64ba3a8e8ce5dbe066b448bfe359221535c5d", "save_path": "github-repos/coq/brandon-sisler-Intros-Blockly", "path": "github-repos/coq/brandon-sisler-Intros-Blockly/Intros-Blockly-c8a64ba3a8e8ce5dbe066b448bfe359221535c5d/natural_number_game/Addition_World.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620585273154, "lm_q2_score": 0.9086178919837706, "lm_q1q2_score": 0.8720569784250937}} {"text": "Module Induction.\n\nTheorem add_0_r_firsttry : forall (n : nat),\n n + 0 = n.\nProof.\n intros n.\n induction n as [| n' IHn'].\n - reflexivity.\n - simpl.\n rewrite -> IHn'.\n reflexivity.\nQed.\n\nPrint add_0_r_firsttry.\n\nTheorem minus_n_n : forall (n : nat),\n n - n = 0.\nProof.\n intros n.\n induction n as [| n' IHn'].\n - simpl.\n reflexivity.\n - simpl.\n rewrite -> IHn'.\n reflexivity.\nQed.\n\n\nTheorem mul_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n intros n.\n induction n as [| n' H].\n - simpl.\n reflexivity.\n - simpl.\n rewrite -> H.\n reflexivity.\nQed.\n\nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof.\n intros n.\n induction n as [| n' H ].\n - simpl.\n reflexivity.\n - simpl.\n intros m.\n rewrite -> H.\n reflexivity.\nQed.\n\nTheorem plus_Sm_Sn : forall n m : nat,\n (S n) + m = n + (S m).\nProof.\n intros n.\n induction n as [| n' H ].\n - simpl.\n reflexivity.\n - simpl.\n intros m.\n rewrite <- H.\n simpl.\n reflexivity.\nQed.\n\nTheorem add_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros n.\n induction n as [| n' H ].\n - simpl.\n intros m.\n simpl.\n rewrite -> add_0_r_firsttry.\n reflexivity.\n - simpl.\n intros m.\n rewrite <- plus_n_Sm.\n simpl.\n rewrite -> H.\n reflexivity.\nQed.\n\n\nTheorem add_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n.\n induction n as [| n' H].\n - simpl.\n reflexivity.\n - simpl.\n intros m p.\n rewrite -> H.\n reflexivity.\nQed.\n\n\n\n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n intros n.\n induction n as [| n' H ].\n - simpl.\n reflexivity.\n - simpl.\n rewrite -> H.\n rewrite -> plus_n_Sm.\n reflexivity.\nQed.\n\nFixpoint even (n : nat) : bool :=\n match n with \n | O => true\n | S O => false\n | S (S m) => even m\n end.\n\nLemma double_neg : forall b : bool,\n negb (negb b) = b.\nProof.\n intros b.\n destruct b.\n - simpl.\n reflexivity.\n - simpl.\n reflexivity.\nQed.\n\nTheorem even_S : forall n : nat,\n even (S n) = negb (even n).\nProof.\n intros n.\n induction n as [| n' H ].\n - simpl.\n reflexivity.\n - rewrite -> H.\n simpl.\n rewrite -> double_neg.\n reflexivity.\nQed.\n\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n). {\n reflexivity.\n }\n rewrite -> H.\n reflexivity. \nQed.\n\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n (* We just need to swap (n + m) for (m + n)... seems\n like add_comm should do the trick! *)\n rewrite add_comm.\n (* Doesn't work... Coq rewrites the wrong plus! :-( *)\nAbort.\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n assert (H : n + m = m + n). {\n rewrite add_comm. \n reflexivity.\n }\n rewrite -> H.\n reflexivity.\nQed.\n\nPrint plus_rearrange_firsttry.\n\n\nTheorem add_shuffle3 : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n assert (H1 : n + (m + p) = (n + m) + p). {\n rewrite -> add_assoc.\n reflexivity.\n }\n assert (H2 : m + (n + p) = (m + n) + p). {\n rewrite -> add_assoc.\n reflexivity.\n }\n rewrite -> H1.\n rewrite -> H2.\n assert (H3 : n + m = m + n). {\n rewrite -> add_comm.\n reflexivity.\n }\n rewrite -> H3.\n reflexivity.\nQed.\n\n\nLemma second_mult_expand : forall m n : nat,\n n * (S m) = n + n * m.\nProof.\n induction n as [| n' H].\n - simpl.\n reflexivity.\n - simpl.\n rewrite -> H.\n rewrite -> add_shuffle3.\n reflexivity.\nQed.\n\n\nTheorem mul_comm : forall m n : nat,\n m * n = n * m.\nProof.\n intros m n.\n induction m as [| m' H].\n - simpl.\n assert (G : n * 0 = 0). {\n induction n as [| n' G'].\n - simpl.\n reflexivity.\n - simpl.\n rewrite -> G'.\n reflexivity.\n }\n rewrite -> G.\n \n reflexivity.\n - simpl.\n rewrite -> H.\n rewrite -> second_mult_expand.\n reflexivity.\nQed.\n\n\n\n\n\n\nFixpoint eqb (n m : nat) : bool :=\n match n, m with\n | O, O => true\n | S i, S j => eqb i j\n | _, _ => false\n end.\nFixpoint leb (n m : nat) : bool :=\n match n, m with\n | O, O => true\n | S i, S j => leb i j\n | O, S _ => true\n | _, _ => false\n end.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nCheck leb.\n\nTheorem leb_refl : forall n:nat,\n (n <=? n) = true.\nProof.\n intros n.\n induction n as [| n' H ].\n - reflexivity.\n - simpl.\n rewrite -> H.\n reflexivity.\nQed.\n\n\nTheorem zero_neqb_S : forall n:nat,\n 0 =? (S n) = false.\nProof.\n intros n.\n destruct n as [| n'].\n - simpl.\n reflexivity.\n - simpl.\n reflexivity.\nQed.\n\n\nTheorem andb_false_r : forall b : bool,\n andb b false = false.\nProof.\n intros n.\n destruct n as [|].\n - reflexivity.\n - reflexivity.\nQed.\n\n\nTheorem plus_leb_compat_l : forall n m p : nat,\n n <=? m = true -> (p + n) <=? (p + m) = true.\nProof.\n intros n m p H.\n induction p as [| p' I].\n - simpl.\n rewrite -> H.\n reflexivity.\n - simpl.\n rewrite -> I.\n reflexivity.\nQed. \n\nTheorem S_neqb_0 : forall n:nat,\n (S n) =? 0 = false.\nProof.\n intros n.\n simpl.\n reflexivity.\nQed.\n\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n intros n.\n simpl.\n rewrite -> add_comm.\n simpl.\n reflexivity.\nQed.\n\n\nTheorem all3_spec : forall b c : bool,\n orb\n (andb b c)\n (orb (negb b)\n (negb c))\n = true.\nProof.\n intros b c.\n destruct b as [|].\n assert (H: forall i : bool, orb i (negb i) = true). {\n intros i.\n destruct i.\n - reflexivity.\n - reflexivity.\n }\n - simpl.\n rewrite -> H.\n reflexivity.\n - simpl.\n reflexivity.\nQed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n (n + m) * p = (n * p) + (m * p).\nProof.\n intros n m p.\n induction p as [| p' H ].\n - simpl.\n rewrite -> mul_0_r.\n rewrite -> mul_0_r.\n rewrite -> mul_0_r.\n reflexivity.\n - rewrite -> second_mult_expand.\n rewrite -> second_mult_expand.\n rewrite -> second_mult_expand.\n rewrite -> H.\n assert (G: forall a b c d : nat, (a + b) + (c + d) = (a + c) + (b + d)). {\n intros a b c d.\n rewrite <- add_assoc.\n assert (G' : b + (c + d) = c + d + b). {\n rewrite -> add_comm.\n reflexivity.\n }\n rewrite -> G'.\n assert (G'' : c + d + b = c + (d + b)). {\n rewrite -> add_assoc.\n reflexivity.\n }\n rewrite -> G''.\n rewrite -> add_assoc.\n assert (G''' : d + b = b + d). {\n rewrite -> add_comm.\n reflexivity.\n }\n rewrite -> G'''.\n reflexivity.\n }\n rewrite -> G.\n reflexivity.\nQed.\n\n\nTheorem mult_assoc : forall n m p : nat,\n n * (m * p) = (n * m) * p.\nProof.\n intros n m p.\n induction n as [| n' H ].\n - simpl.\n reflexivity.\n - simpl.\n rewrite -> mult_plus_distr_r.\n rewrite -> H.\n reflexivity.\nQed.\n\nTheorem eqb_refl : forall n : nat,\n (n =? n) = true.\nProof.\n intros n.\n induction n as [| n' H ].\n - reflexivity.\n - simpl.\n rewrite -> H.\n reflexivity.\nQed.\n\nTheorem add_shuffle3' : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n rewrite -> add_assoc.\n replace (n + m) with (m + n).\n rewrite <- add_assoc.\n reflexivity.\n\n rewrite -> add_comm.\n reflexivity.\nQed.\n\n\nModule BinNat.\nInductive bin : Type :=\n | Z\n | B0 (n : bin)\n | B1 (n : bin).\n\nFixpoint incr (b : bin) : bin :=\n match b with\n | Z => B1 Z\n | B0 i => B1 i\n | B1 i => B0 (incr i)\n end.\n\nFixpoint bin_to_nat (m:bin) : nat :=\n match m with\n | Z => O\n | B0 i => 2 * (bin_to_nat i)\n | B1 i => 1 + 2 * (bin_to_nat i)\n end.\n\nTheorem bin_to_nat_pres_incr : forall (b: bin),\n bin_to_nat(incr b) = S (bin_to_nat b).\nProof.\n intros b.\n induction b as [| b' H | b' H ].\n - simpl.\n reflexivity.\n - simpl. \n reflexivity.\n - simpl.\n rewrite -> add_0_r_firsttry.\n rewrite -> add_0_r_firsttry.\n rewrite -> H.\n assert (G: forall a b : nat, S (a + b) = a + (S b)). {\n intros a b.\n induction a as [| a' G' ].\n - simpl.\n reflexivity.\n - simpl.\n rewrite -> G'.\n reflexivity.\n }\n rewrite -> G.\n simpl.\n reflexivity.\nQed.\n\nFixpoint nat_to_bin (n:nat) : bin := \n match n with\n | O => B0 Z\n | S n' => incr (nat_to_bin n')\n end.\n\nTheorem nat_bin_nat : forall n : nat, bin_to_nat (nat_to_bin n) = n.\nProof.\n intros n.\n induction n as [| n' H ].\n - simpl.\n reflexivity.\n - simpl.\n rewrite -> bin_to_nat_pres_incr.\n rewrite -> H.\n reflexivity.\nQed.\n\nTheorem bin_nat_bin : forall b : bin, nat_to_bin (bin_to_nat b) = b.\nProof.\n (* Impossible *)\nAdmitted.\n\n\n\nFixpoint repeatB0 (n: nat) (zb: bin) : bin :=\n match n with\n | O => zb\n | S n' => B0 (repeatB0 n' zb)\n end.\n\n\nFixpoint normalize' (zerosAmount: nat) (b : bin) : bin := \n match b with\n | Z => Z\n | B0 i => normalize' (S zerosAmount) i\n | B1 i => repeatB0 zerosAmount (B1 (normalize' O i))\n end.\n\nDefinition normalize (b : bin) : bin := \n match b with\n | Z => B0 Z\n | b' => normalize' O b'\n end.\n\n(*\nLemma normalize_preserves_incr: forall (b: bin), \n normalize (incr b) = incr (normalize b).\nProof.\n intros b.\n induction b as [| b' H | b' H ].\n - unfold normalize.\n simpl.\n reflexivity.\n - simpl.\n \n \n\nLemma double_n_is_one_more_zero_to_bin: forall (n : nat), \n nat_to_bin (n + n) = normalize (B0 (nat_to_bin n)).\nProof.\n intros n.\n induction n as [| n' H ].\n - unfold normalize.\n simpl.\n reflexivity.\n - simpl.\n rewrite -> add_comm.\n simpl.\n rewrite -> H.\n\n\n\n\n\nTheorem bin_nat_bin_is_normalize: forall (b : bin), \n nat_to_bin (bin_to_nat b) = normalize b.\nProof.\n intros b.\n induction b as [| b' H | b' H ].\n - unfold normalize.\n simpl.\n reflexivity.\n - unfold normalize.\n simpl.\n rewrite -> add_0_r_firsttry.\n destruct b' as [| b'0 | b'1 ].\n * simpl.\n reflexivity.\n * \n\n*)\n\n\n\n\n\n\nEnd BinNat.\n\n\nEnd Induction.\n", "meta": {"author": "cattingcat", "repo": "coq_lessons", "sha": "49ea5727398acddd5b347b234d6b4efcab305422", "save_path": "github-repos/coq/cattingcat-coq_lessons", "path": "github-repos/coq/cattingcat-coq_lessons/coq_lessons-49ea5727398acddd5b347b234d6b4efcab305422/softwarefoundations/vol1/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361159764527, "lm_q2_score": 0.9073122251200417, "lm_q1q2_score": 0.8713474207848169}} {"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\nRequire Export Coq.Init.Nat.\nModule NatList.\n\n\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as here: *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n(** Here are simple functions for extracting the first and\n second components of a pair. The definitions also illustrate how\n to do pattern matching on two-argument constructors. *)\n\nDefinition fst (p : natprod) : nat :=\n match p with\n | pair x y => x\n end.\n\nDefinition snd (p : natprod) : nat :=\n match p with\n | pair x y => y\n end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new pair notation can be used both in expressions and in\n pattern matches (indeed, we've actually seen this already in the\n [Basics] chapter, in the definition of the [minus] function --\n this works because the pair notation is also provided as part of\n the standard library): *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n match p with\n | (x,y) => x\n end.\n\nDefinition snd' (p : natprod) : nat :=\n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n match p with\n | (x,y) => (y,x)\n end.\n\n(** Let's try to prove a few simple facts about pairs.\n\n If we state things in a slightly peculiar way, we can complete\n proofs with just reflexivity (and its built-in simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** Notice that, unlike its behavior with [nat]s, [destruct]\n generates just one subgoal here. That's because [natprod]s can\n only be constructed in one way. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n destruct p.\n simpl.\n reflexivity.\n Qed.\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n destruct p.\n simpl.\n reflexivity. Qed.\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n type of _lists_ of numbers like this: \"A list is either the empty\n list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n declarations, but in case you are interested, here is roughly\n what's going on. The [right associativity] annotation tells Coq\n how to parenthesize expressions involving several uses of [::] so\n that, for example, the next three declarations mean exactly the\n same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\n\n Notation \"x + y\" := (plus x y)\n (at level 50, left associativity).\n\n the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n you read them in a [.v] file. The inner brackets, around 3, indicate\n a list, but the outer brackets, which are invisible in the HTML\n rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n part should be displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head (with default) and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\").\n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, recommended (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | nil => []\n | x :: xs => match x with \n | 0 => nonzeros xs\n | n => n :: (nonzeros xs)\n end\n end. \n \nExample test_nonzeros:\n nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof.\n reflexivity. Qed.\n\nDefinition isOdd (x : nat) : bool :=\n match x mod 2 with \n | 1 => true\n | _ => false\n end.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | nil => []\n | x :: xs => match isOdd x with\n | true => x :: oddmembers xs\n | _ => oddmembers xs\n end\n end.\n\nExample test_oddmembers:\n oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof.\n simpl. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n match l with\n | [] => 0\n | x :: xs => match isOdd x with\n | true => 1 + countoddmembers xs\n | false => countoddmembers xs\n end\nend.\n\nExample test_countoddmembers1:\n countoddmembers [1;0;3;1;4;5] = 4.\nProof.\n simpl. reflexivity. Qed.\n\nExample test_countoddmembers2:\n countoddmembers [0;2;4] = 0.\nProof.\n reflexivity. Qed.\n\nExample test_countoddmembers3:\n countoddmembers nil = 0.\nProof.\n reflexivity. Qed.\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_alternate1:\n alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n (* FILL IN HERE *) Admitted.\n\nExample test_alternate2:\n alternate [1] [4;5;6] = [1;4;5;6].\n (* FILL IN HERE *) Admitted.\n\nExample test_alternate3:\n alternate [1;2;3] [4] = [1;4;2;3].\n (* FILL IN HERE *) Admitted.\n\nExample test_alternate4:\n alternate [] [20;30] = [20;30].\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n can appear multiple times rather than just once. One possible\n implementation is to represent a bag of numbers as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, recommended (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat :=\n match s with\n | [] => 0\n | x :: xs => if eqb v x then S (count v xs) else (count v xs)\n end.\n\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof.\n simpl. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof.\n reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n the elements of [a] and of [b]. (Mathematicians usually define\n [union] on multisets a little bit differently -- using max instead\n of sum -- which is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag :=\n app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof.\n reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag :=\n v :: s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof.\n reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof.\n reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n if ltb 0 (count v s) then true else false.\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more [bag] functions for you to practice with. *)\n\n(** When [remove_one] is applied to a bag without the number to remove,\n it should return the same bag unchanged. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_remove_one1:\n count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\n\nExample test_remove_one2:\n count 5 (remove_one 5 [2;1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\n\nExample test_remove_one3:\n count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n (* FILL IN HERE *) Admitted.\n\nExample test_remove_one4:\n count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n (* FILL IN HERE *) Admitted.\n\nFixpoint remove_all (v:nat) (s:bag) : bag\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n (* FILL IN HERE *) Admitted.\n\nFixpoint subset (s1:bag) (s2:bag) : bool\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\n (* FILL IN HERE *) Admitted.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\n (* FILL IN HERE *) Admitted.\n\n(* Do not modify the following line: *)\n(* Definition manual_grade_for_bag_theorem : option (prod nat string) := None. *)\n(* (** [] *) *)\n\n(** **** Exercise: 3 stars, recommended (bag_theorem) *)\n(** Write down an interesting theorem [bag_theorem] about bags\n involving the functions [count] and [add], and prove it. Note\n that, since this problem is somewhat open-ended, it's possible\n that you may come up with a theorem which is true, but whose proof\n requires techniques you haven't learned yet. Feel free to ask for\n help if you get stuck! *)\n\n\n(* Theorem bag_theorem : forall s:bag , count 2 (sum (add 5 (add 2 (add 1 (add 3 s)))) (add 2 s)) = 2 + count 2 s. *)\n(* Proof. *)\n(* intros s. *)\n(* simpl. *)\n(* Qed. *)\n\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ...because the [[]] is substituted into the\n \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n the match) in the definition of [app], allowing the match itself\n to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons n l' *)\n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n It is important to work through the details of each one, using Coq\n and thinking about what each step achieves. Otherwise it is more\n or less guaranteed that the exercises will make no sense when you\n get to them. 'Nuff said. *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n little less familiar than standard natural number induction, but\n the idea is equally simple. Each [Inductive] declaration defines\n a set of data values that can be built up using the declared\n constructors: a boolean can be either [true] or [false]; a number\n can be either [O] or [S] applied to another number; a list can be\n either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two arguments together establish\n the truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons n l1' *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n [as...] clause provided to the [induction] tactic gives a name to\n the induction hypothesis corresponding to the smaller list [l1']\n in the [cons] case. Once again, this Coq proof is not especially\n illuminating as a static written document -- it is easy to see\n what's going on if you are reading the proof in an interactive Coq\n session and you can see the current goal and context at each\n point, but this state is not visible in the written-down parts of\n the Coq proof. So a natural-language proof -- one written for\n human readers -- will need to include more explicit signposts; in\n particular, it will help the reader stay oriented if we remind\n them exactly what the induction hypothesis is in the second\n case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n (the induction hypothesis). We must show\n\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n By the definition of [++], this follows from\n\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n which is immediate from the induction hypothesis. [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n lists, suppose we use [app] to define a list-reversing function\n [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => rev t ++ [h]\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Properties of [rev] *)\n\n(** Now let's prove some theorems about our newly defined [rev].\n For something a bit more challenging than what we've seen, let's\n prove that reversing a list does not change its length. Our first\n attempt gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = [] *)\n reflexivity.\n - (* l = n :: l' *)\n (* This is the tricky case. Let's begin as usual\n by simplifying. *)\n simpl.\n (* Now we seem to be stuck: the goal is an equality\n involving [++], but we don't have any useful equations\n in either the immediate context or in the global\n environment! We can make a little progress by using\n the IH to rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n would have enabled us to make progress and state it as a separate\n lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Note that, to make the lemma as general as possible, we\n quantify over _all_ [natlist]s, not just those that result from an\n application of [rev]. This should seem natural, because the truth\n of the goal clearly doesn't depend on the list having been\n reversed. Moreover, it is easier to prove the more general\n property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons *)\n simpl. rewrite -> app_length, plus_comm.\n simpl. rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n _Theorem_: For all lists [l1] and [l2],\n [length (l1 ++ l2) = length l1 + length l2].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n length ([] ++ l2) = length [] + length l2,\n\n which follows directly from the definitions of\n [length] and [++].\n\n - Next, suppose [l1 = n::l1'], with\n\n length (l1' ++ l2) = length l1' + length l2.\n\n We must show\n\n length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n This follows directly from the definitions of [length] and [++]\n together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n\n length (rev []) = length [],\n\n which follows directly from the definitions of [length]\n and [rev].\n\n - Next, suppose [l = n::l'], with\n\n length (rev l') = length l'.\n\n We must show\n\n length (rev (n :: l')) = length (n :: l').\n\n By the definition of [rev], this follows from\n\n length ((rev l') ++ [n]) = S (length l')\n\n which, by the previous lemma, is the same as\n\n length (rev l') + length [n] = S (length l').\n\n This follows directly from the induction hypothesis and the\n definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n After the first few, we might find it easier to follow proofs that\n give fewer details (which can easily work out in our own minds or\n on scratch paper if necessary) and just highlight the non-obvious\n steps. In this more compressed style, the above proof might look\n like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n for any [l] (this follows by a straightforward induction on [l]).\n The main property again follows by induction on [l], using the\n observation together with the induction hypothesis in the case\n where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for our\n present purposes. *)\n\n\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, e.g., using [rewrite]. But in order to refer to a\n theorem, we need to know its name! Indeed, it is often hard even\n to remember what theorems have been proven, much less what they\n are called.\n\n Coq's [Search] command is quite helpful with this. Typing\n [Search foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following line\n to see a list of theorems that we have proved about [rev]: *)\n\n (* Search rev. *)\n\n(** Keep [Search] in mind as you do the following exercises and\n throughout the rest of the book; it can save you a lot of time!\n\n If you are using ProofGeneral, you can run [Search] with [C-c\n C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n l ++ [] = l.\nProof.\n intros l.\n induction l as [|l' IHl'].\n - reflexivity.\n - simpl. rewrite IHIHl'. reflexivity. Qed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n intros l1 l2.\n induction l1 as [|l' IHl'].\n - simpl. rewrite app_nil_r. reflexivity.\n - simpl. rewrite IHIHl'. rewrite app_assoc. reflexivity. Qed.\n\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros l.\n induction l as [|l' IHl'].\n - reflexivity.\n - simpl. rewrite rev_app_distr. rewrite IHIHl'. simpl. reflexivity. Qed.\n\n(** There is a short solution to the next one. If you find yourself\n getting tangled up, step back and try to look for a simpler\n way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros l1 l2 l3 l4.\n repeat rewrite app_assoc. reflexivity. Qed.\n \n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros l1 l2.\n induction l1 as [|l' IHl'].\n - simpl. reflexivity.\n - induction l' as [|l'' IHl''].\n + simpl. rewrite IHIHl'. reflexivity.\n + simpl. rewrite IHIHl'. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n match l1 with\n | [] => if (length l2) =? 0 then true else false\n | x :: xs => match l2 with\n | [] => false\n | y :: ys => if eqb x y then beq_natlist xs ys else false\n end\n end.\n\n \nExample test_beq_natlist1 :\n (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\n\nExample test_beq_natlist2 :\n beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\nExample test_beq_natlist3 :\n beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof. \n intros l.\n induction l as [|l' IHl'].\n - reflexivity.\n - simpl. rewrite <- IHIHl'. induction l'.\n + reflexivity.\n + simpl. rewrite <- IHl'0. reflexivity. Qed.\n\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** Here are a couple of little theorems to prove about your\n definitions about bags above. *)\n\n\n(* Theorem count_member_nonzero : forall (s : bag), *)\n(* leb 1 (count 1 (1 :: s)) = true. *)\n(* Proof. *)\n\n(* (** The following lemma about [leb] might help you in the next exercise. *) *)\n\n(* Theorem ble_n_Sn : forall n, *)\n(* leb n (S n) = true. *)\n(* Proof. *)\n(* intros n. induction n as [| n' IHn']. *)\n(* - (* 0 *) *)\n(* simpl. reflexivity. *)\n(* - (* S n' *) *)\n(* simpl. rewrite IHn'. reflexivity. Qed. *)\n\n(* (** **** Exercise: 3 stars, advanced (remove_does_not_increase_count) *) *)\n(* Theorem remove_does_not_increase_count: forall (s : bag), *)\n(* leb (count 0 (remove_one 0 s)) (count 0 s) = true. *)\n(* Proof. *)\n(* (* FILL IN HERE *) Admitted. *)\n(* (** [] *) *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *)\n(** Write down an interesting theorem [bag_count_sum] about bags\n involving the functions [count] and [sum], and prove it using\n Coq. (You may find that the difficulty of the proof depends on\n how you defined [count]!) *)\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective -- that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\n (There is a hard way and an easy way to do this.) *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\n(* Definition manual_grade_for_rev_injective : option (prod nat string) := None. *)\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n element of some list. If we give it type [nat -> natlist -> nat],\n then we'll have to choose some number to return when the list is\n too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with\n | true => a\n | false => nth_bad l' (pred n)\n end\n end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n can't tell whether that value actually appears on the input\n without further processing. A better alternative is to change the\n return type of [nth_bad] to include an error value as a possible\n outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption.\n\n(** We can then change the above definition of [nth_bad] to\n return [None] when the list is too short and [Some a] when the\n list has enough members and [a] appears at position [n]. We call\n this new function [nth_error] to indicate that it may result in an\n error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => match beq_nat n O with\n | true => Some a\n | false => nth_error l' (pred n)\n end\n end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n examples are elided. Click on a box if you want to see one.)\n\n This example is also an opportunity to introduce one more small\n feature of Coq's programming language: conditional\n expressions... *)\n\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => if beq_nat n O then Some a\n else nth_error' l' (pred n)\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually supports conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_error) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_error (l : natlist) : natoption :=\n match l with\n | [] => None\n | x :: xs => Some x\n end.\n\nExample test_hd_error1 : hd_error [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_error l).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n Coq, here is a simple _partial map_ data type, analogous to the\n map or dictionary data structures found in most programming\n languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n | Id : nat -> id.\n\n(** Internally, an [id] is just a number. Introducing a separate type\n by wrapping each nat with the tag [Id] makes definitions more\n readable and gives us the flexibility to change representations\n later if we wish. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition beq_id (x1 x2 : id) :=\n match x1, x2 with\n | Id n1, Id n2 => beq_nat n1 n2\n end.\n\n(** **** Exercise: 1 star (beq_id_refl) *)\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n destruct x as [id].\n - simpl. rewrite <- beq_nat_refl. reflexivity. Qed.\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n \nInductive partial_map : Type :=\n | empty : partial_map\n | record : id -> nat -> partial_map -> partial_map.\n\n(** This declaration can be read: \"There are two ways to construct a\n [partial_map]: either using the constructor [empty] to represent an\n empty partial map, or by applying the constructor [record] to\n a key, a value, and an existing [partial_map] to construct a\n [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n partial map by shadowing it with a new one (or simply adds a new\n entry if the given key is not already present). *)\n\nDefinition update (d : partial_map)\n (x : id) (value : nat)\n : partial_map :=\n record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n key. It returns [None] if the key was not found and [Some val] if\n the key was associated with [val]. If the same key is mapped to\n multiple values, [find] will return the first one it\n encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n match d with\n | empty => None\n | record y v d' => if beq_id x y\n then Some v\n else find x d'\n end.\n\n\n(** **** Exercise: 1 star (update_eq) *)\nTheorem update_eq :\n forall (d : partial_map) (x : id) (v: nat),\n find x (update d x v) = Some v.\nProof.\n intros d x v.\n simpl. rewrite <- beq_id_refl. reflexivity. Qed.\n\n(** **** Exercise: 1 star (update_neq) *)\nTheorem update_neq :\n forall (d : partial_map) (x y : id) (o: nat),\n beq_id x y = false -> find x (update d y o) = find x d.\nProof.\n intros d x y o H.\n simpl. rewrite H. reflexivity. Qed.\n\nEnd PartialMap.\n\n(** **** Exercise: 2 stars (baz_num_elts) *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n | Baz1 : baz -> baz\n | Baz2 : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have?\n (Explain your answer in words, preferrably English.) *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\n(** [] *)\n\n\n", "meta": {"author": "robkorn", "repo": "coq-software-foundations", "sha": "95522c89a964ee00b68cb0e1f7f1600943a95936", "save_path": "github-repos/coq/robkorn-coq-software-foundations", "path": "github-repos/coq/robkorn-coq-software-foundations/coq-software-foundations-95522c89a964ee00b68cb0e1f7f1600943a95936/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.9458012720864439, "lm_q1q2_score": 0.8708840508934568}} {"text": "(**************************************\n Finish reading, Finish exercise\n**************************************)\n\nRequire Import Nat Bool.\n\n\n(* ================================================================= *)\n(** * Proof by Induction *)\n\nTheorem plus_n_O: forall n: nat, n = n + 0.\nProof.\n induction n as [| n' IHn'].\n - (* n = 0 *) reflexivity.\n - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity.\nQed.\n\n\n(** **** Exercise: 2 stars, recommended (basic_induction) *)\nTheorem mult_0_r: forall n: nat, n * 0 = 0.\nProof.\n induction n as [|n' H].\n - reflexivity.\n - simpl.\n rewrite -> H.\n reflexivity.\nQed.\n\n\nTheorem plus_n_Sm: forall n m: nat, S (n + m) = n + (S m).\nProof.\n intros n m.\n induction n as [|n' H].\n - reflexivity.\n - simpl.\n rewrite -> H.\n reflexivity.\nQed.\n\nTheorem plus_comm: forall n m: nat, n + m = m + n.\nProof.\n intros n m.\n induction n as [|n' H].\n - simpl.\n rewrite <- plus_n_O.\n reflexivity.\n - simpl.\n rewrite -> H.\n rewrite -> plus_n_Sm.\n reflexivity.\nQed.\n\n\n\nTheorem plus_assoc: forall n m p: nat, n + (m + p) = (n + m) + p.\nProof.\n intros m n p.\n induction n as [|n' H].\n - simpl.\n rewrite <- plus_n_O.\n reflexivity.\n - simpl.\n rewrite -> plus_comm.\n simpl.\n rewrite -> plus_comm.\n rewrite -> H.\n rewrite <- plus_n_Sm.\n simpl.\n reflexivity.\nQed.\n\n\n\n(** **** Exercise: 2 stars (double_plus) *)\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\nLemma double_plus: forall n, double n = n + n.\nProof.\n intros n.\n induction n as [|n' H].\n - reflexivity.\n - simpl.\n rewrite H.\n rewrite plus_n_Sm.\n reflexivity.\nQed.\n\n\n\n\n\n(** **** Exercise: 2 stars, optional (evenb_S) *)\nTheorem evenb_S: forall n: nat, even (S n) = negb (even n).\nProof.\n intros n.\n induction n as [|n H].\n - reflexivity.\n - rewrite H.\n rewrite negb_involutive.\n reflexivity.\nQed.\n\n\n\n(** **** Exercise: 1 star (destruct_induction) *)\n(*\n destruct: without Hypothesis.\n induction: with Hypothesis.\n*)\n\n\n\n\n(* ================================================================= *)\n(** * Formal vs. Informal Proof *)\n\n\n(** **** Exercise: 2 stars, advanced, recommended (plus_comm_informal) *)\n(*\n Proof: (* not do the exercise *)\n*)\n\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl_informal) *)\n(* \n Proof: (* not do the exercise *)\n*)", "meta": {"author": "valaxy", "repo": "software-foundations-exercise", "sha": "fb475bab69fb44adb38ccce803c1f7fa5fcf8ea2", "save_path": "github-repos/coq/valaxy-software-foundations-exercise", "path": "github-repos/coq/valaxy-software-foundations-exercise/software-foundations-exercise-fb475bab69fb44adb38ccce803c1f7fa5fcf8ea2/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.9294404052785552, "lm_q1q2_score": 0.8702211118938405}} {"text": "Add LoadPath \"../Basics\".\nRequire Export NamingCases.\n\n(** We start with a basic example of induction : proving that\n [n + 0 = n] *)\nTheorem plus_0_r : forall n : nat, n + 0 = n.\n\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n\".\n simpl. rewrite -> IHn' . reflexivity. Qed.\n\n(** Another induction example. This time, we prove\n that n-n = 0 *)\nTheorem minus_diag : forall n,\n minus n n = 0.\n\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** EXERCISE [**]: Basic induction proofs. Prove the\n following lemmas using induction *)\n\nTheorem mult_0_r : forall n : nat,\n n * 0 = 0.\n\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\n\nProof.\n intros n m. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\n\n(** Addition is commutative *)\nProof.\n intros n m. induction n as [| n'].\n Case \"n = 0\".\n simpl. rewrite -> plus_0_r. reflexivity.\n Case \"n = S n\".\n simpl. rewrite <- plus_n_Sm. rewrite <- IHn'. reflexivity. Qed.\n\n(** Addition is associative *)\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\n\nProof.\n intros n m p. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n\".\n simpl. rewrite <- IHn'. reflexivity. Qed.\n\n(** EXERCISE [**]: Use induction to prove the given fact\n [double_plus.] *)\nFixpoint double (n : nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\nLemma double_plus : forall n, double n = n + n.\n\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity. Qed.\n\n(** EXERCISE [*]: Discuss the differences between the induction and\n destruct strategies *)\n\n(** Using the [destruct] tactic results in Coq specifically going to\n the data type definition, and generating cases for each member\n of the data type. Induction is a more powerful reasoning principle:\n prove a base case P(b) (when working over the natural numbers, this is\n usually proving your proposition for [b = 0]). Then, prove that, for\n all n in N, P(n) => P(n+1). The common analogy is dominoes falling.\n You've already proved P(b), then using the proven inductive impl.,\n you get P(b+1), P(b+2), and so on and so forth. *)\n\n", "meta": {"author": "madelgi", "repo": "software-foundations", "sha": "7f533d9596c4408eedd02bb7463f4ed532e9541e", "save_path": "github-repos/coq/madelgi-software-foundations", "path": "github-repos/coq/madelgi-software-foundations/software-foundations-7f533d9596c4408eedd02bb7463f4ed532e9541e/Induction/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.9284088084787998, "lm_q1q2_score": 0.8701147606527427}} {"text": "Module Playground1.\nInductive nat : Type :=\n | O : nat\n | S : nat -> nat.\n\nDefinition pred (n : nat) : nat :=\n match n with\n | O => O\n | S n' => n'\n end.\nEnd Playground1.\n\nDefinition minustwo (n : nat) : nat :=\n match n with\n | O => O\n | S O => O\n | S (S n') => n'\n end.\nCheck (S (S (S (S O)))).\nEval simpl in (minustwo 4).\n\nCheck S.\nCheck pred.\nCheck minustwo.\n\nFixpoint evenb (n:nat) : bool :=\n match n with\n | O => true\n | S O => false\n | S (S n') => evenb n'\n end.\n\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\nExample test_oddb1: (oddb (S O)) = true.\nProof. simpl. reflexivity. Qed.\nExample test_oddb2: (oddb (S (S (S (S O))))) = false.\nProof. simpl. reflexivity. Qed.\n\nModule Playground2.\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n match n with\n | O => m\n | S n' => S (plus n' m)\n end.\nEval simpl in (plus (S (S (S O))) (S (S O))).\n\nFixpoint mult (n m : nat) : nat :=\n match n with\n | O => O\n | S n' => plus m (mult n' m)\n end.\nEval simpl in (mult 5 6).\nFixpoint minus (n m:nat) : nat :=\n match n, m with\n | O , _ => O\n | S _ , O => n\n | S n', S m' => minus n' m'\n end.\n\nEnd Playground2.\n\nFixpoint exp (base power : nat) : nat :=\n match power with\n | O => S O\n | S p => mult base (exp base p)\n end.\n\nExample test_mult1: (mult 3 3) = 9.\nProof. simpl. reflexivity. Qed.\n\nFixpoint factorial (n:nat) : nat :=\n match n with\n | 0 => 1\n | S p => mult n (factorial p)\n end.\n\nExample test_factorial1: (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. simpl. reflexivity. Qed.\n\nNotation \"x + y\" := (plus x y)\n (at level 50, left associativity)\n : nat_scope.\nNotation \"x - y\" := (minus x y)\n (at level 50, left associativity)\n : nat_scope.\nNotation \"x * y\" := (mult x y)\n (at level 40, left associativity)\n : nat_scope.\n\nCheck ((0 + 1) + 1).\n\nFixpoint beq_nat (n m : nat) : bool :=\n match n with\n | O => match m with\n | O => true\n | S m' => false\n end\n | S n' => match m with\n | O => false\n | S m' => beq_nat n' m'\n end\n end.\n\nFixpoint ble_nat (n m : nat) : bool :=\n match n with\n | O => true\n | S n' =>\n match m with\n | O => false\n | S m' => ble_nat n' m'\n end\n end.\n\nExample test_ble_nat1: (ble_nat 2 2) = true.\nProof. simpl. reflexivity. Qed.\nExample test_ble_nat2: (ble_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_ble_nat3: (ble_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition blt_nat (n m : nat) : bool :=\n andb (ble_nat n m) (notb (beq_nat n m)).\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.", "meta": {"author": "MichaelBurge", "repo": "matroids", "sha": "a9e42e2f93af300caf408ad9b25712431a2f79fe", "save_path": "github-repos/coq/MichaelBurge-matroids", "path": "github-repos/coq/MichaelBurge-matroids/matroids-a9e42e2f93af300caf408ad9b25712431a2f79fe/basics.numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.9073122113355091, "lm_q1q2_score": 0.869692984994724}} {"text": "Require Import Arith.\nRequire Import Bool.\n\n(**************)\n(* Exercise 1 *)\n(**************)\n\n(* We first want to prove that our definition of add satisfies commutativity. *)\n\nFixpoint add n m := \n match n with 0 => m | S p => add p (S m) end.\n\nLemma addnS : forall n m, add n (S m) = S (add n m).\n induction n.\n - intros m; simpl.\n auto.\n - intros m; simpl.\n apply IHn.\nQed.\n\n(* Q1. Prove the following two theorems: beware that you will probably need\n addnS. *)\n\n(* Already done during the lecture ? *)\nLemma addn0 : forall n, add n 0 = n.\nAdmitted.\n\nLemma add_comm : forall n m, add n m = add m n.\nAdmitted.\n\n(* Q2. Now state and prove the associativity of this function. *)\n\n(* Q3. Now state and prove a theorem that expresses that the add function\n returns the same result as the addition available in the loaded libraries\n (given by function plus) *)\n\n(*********************)\n(* Exercise 2: lists *)\n(*********************)\nRequire Import List Bool_nat.\nRequire Import Coq.omega.Omega.\n\n(* From lecture 2 *)\nClass Eq (A : Type) := cmp : A -> A -> bool.\n\nInfix \"==\" := cmp (at level 70, no associativity).\n\nInstance bool_Eq : Eq nat := beq_nat.\n(* beq_nat comes from the Coq library. *)\n\nFixpoint multiplicity (n : nat)(l : list nat) : nat := \n match l with \n nil => 0%nat \n | a :: l' => \n if n == a then S (multiplicity n l') \n else multiplicity n l' \n end. \n\n\nDefinition is_perm (l l' : list nat) := \n forall n, multiplicity n l = multiplicity n l'.\n\n(* Q4. Show the following theorem : *)\n\nLemma multiplicity_app (x : nat) (l1 l2 : list nat) : \n multiplicity x (l1 ++ l2) = multiplicity x l1 + multiplicity x l2.\nAdmitted.\n\n(* Note : for Q5 and Q6, you will probably have an opportunity\n to use the omega tactic *)\n\n(* Q5. State and prove a theorem that expresses that element counts are\n preserved by reverse. *)\n\n\n(* Q6. Show the following theorem. *)\n\nLemma is_perm_transpose x y l1 l2 l3 : \n is_perm (l1 ++ x::l2 ++ y::l3) (l1 ++ y :: l2 ++ x :: l3).\nAdmitted.\n\n(* Q7 : Complete the following lemma using only a reasonning\n on the function rev_app defined in Lecture3.v *)\n(* Excerpt from Lectuer3.v - Begin *)\nFixpoint rev_app (A : Type)(l1 l2 : list A) : list A :=\n match l1 with\n | nil => l2\n | a :: tl => rev_app A tl (a :: l2)\n end.\n\nLemma rev_app_nil : forall A (l1 : list A), \nrev_app A l1 nil = rev l1.\nProof.\nintros A l1.\nassert (Htmp: forall l2, rev_app A l1 l2 = rev l1 ++ l2).\n+ induction l1; intros l2.\n * simpl. auto.\n * simpl.\n rewrite app_assoc_reverse.\n simpl.\n apply IHl1.\n+ rewrite Htmp. \n rewrite app_nil_r.\n auto.\nQed.\n(* Excerpt from Lecture3.v - End *)\n\nLemma rev_rev_id : forall A (l:list A), rev (rev l) = l.\nProof.\n intros.\n rewrite <- rev_app_nil.\n rewrite <- rev_app_nil.\nAdmitted.\n\n(* Q8 : What does this function do? *)\nFixpoint mask (A : Type)(m : list bool)(s : list A) {struct m} :=\n match m, s with\n | b :: m', x :: s' => if b then x :: mask A m' s' else mask A m' s'\n | _, _ => nil\n end.\n\nArguments mask [A] _ _.\n\n(* Q9 Prove that : *)\nLemma mask_cat : forall A m1 (s1 : list A),\n length m1 = length s1 ->\n forall m2 s2, mask (m1 ++ m2) (s1 ++ s2) = mask m1 s1 ++ mask m2 s2.\nAdmitted.\n\n(**************)\n(* Exercise 3 *)\n(**************)\n\n(* Define an inductive type formula : Type that represents the *)\n(*abstract language of propositional logic without variables: \nL = L /\\ L | L \\/ L | ~L | L_true | L_false\n*)\n\n\n(* Define a function formula_holds of type (formula -> Prop computing the *)\n(* Coq formula corresponding to an element of type formula *)\n\n(* Define a function isT_formula of type (formula -> bool) computing *)\n(* the intended truth value of (f : formula) *)\n\n\n(* prove that is (idT_formula f) evaluates to true, then its *)\n(*corresponding Coq formula holds ie.:\n\nRequire Import Bool.\nLemma isT_formula_correct : forall f : formula, \n isT_formula f = true <-> formula_holds f.\n*)\n\n(**************)\n(* Exercise 4 *)\n(**************)\n\n(* We use the inductive type defined in the lecture: *)\n\nInductive natBinTree : Set :=\n| Leaf : natBinTree\n| Node : nat -> natBinTree -> natBinTree -> natBinTree.\n\n(* Define a function which sums all the values present in the tree.\n\nDefine a function is_zero_present : natBinTree -> bool, which tests whether\nthe value 0 is present or not in the tree.\n\nProve several simple statements about the fonctions tree_size\nand tree_height seen in the lecture\n\nDefine a function called mirror that computes the mirror image of a tree.\n\nProve that a tree and its mirror image have the same height.\n\nProve that mirror is involutive (ie the mirror image of the mirror image\nof the tree is this tree).\n\nIt is possible to navigate in a binary tree, given a tree t and\na path like \"from the root, go to the left subtree, then \n go to the right subtree, then go to the left subtree, etc. \"\n\nSuch a path can be easily represented by a list of directions. *)\n\nInductive direction : Set := L (* go left *) | R (* go right *).\n\n\n(* Define in Coq a function get_label that takes a tree and some path,\nand returns the label at which one arrives following the path\n(if any) *)\n\nFixpoint get_label (path : list direction)(t:natBinTree): option nat:= None.\n(* TO DO *)\n\n(* Consider the following function :\n*)\n\nFixpoint zero_present (t: natBinTree) : bool :=\nmatch t with Leaf => false\n | Node n t1 t2 => beq_nat n 0 ||\n zero_present t1 ||\n zero_present t2\nend.\n(* \nProve that whenever zero_present t = true, then there exists \nsome path p such that get_label p t = Some 0\n\n*)\n \n(**************)\n(* Exercise 5 *)\n(**************)\n\n(* Define the function \nsplit : forall A B : Set, list A * B -> (list A) * (list B)\n\nwhich transforms a list of pairs into a pair of lists\nand the function\ncombine : forall A B : Set, list A * list B -> list (A * B)\nwhich transforms a pair of lists into a list of pairs.\n\nWrite and prove two theorems relating the two functions.\n*)", "meta": {"author": "wdomitrz", "repo": "Coq-Exercises", "sha": "86d6ae9488901a0f61d45234a6b1c2c684cf60ef", "save_path": "github-repos/coq/wdomitrz-Coq-Exercises", "path": "github-repos/coq/wdomitrz-Coq-Exercises/Coq-Exercises-86d6ae9488901a0f61d45234a6b1c2c684cf60ef/ZPF/Lab19/Lab3/coqITP2015-ex3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.9207896726304802, "lm_q1q2_score": 0.8693882993335675}} {"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\n\nModule NatList. \n \n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as in this definition: *)\n\nInductive natprod : Type :=\n pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\n(** We can construct an element of [natprod] like this: *)\n\nCheck (pair 3 5).\n\n(** *** *)\n\n(** Here are two simple function definitions for extracting the\n first and second components of a pair. (The definitions also\n illustrate how to do pattern matching on two-argument\n constructors.) *)\n\nDefinition fst (p : natprod) : nat := \n match p with\n | pair x y => x\n end.\nDefinition snd (p : natprod) : nat := \n match p with\n | pair x y => y\n end.\n\nEval compute in (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** *** *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this notation is provided as part of the standard\n library): *)\n\nEval compute in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat := \n match p with\n | (x,y) => x\n end.\nDefinition snd' (p : natprod) : nat := \n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod := \n match p with\n | (x,y) => (y,x)\n end.\n\n(** *** *)\n\n(** Let's try and prove a few simple facts about pairs. If we\n state the lemmas in a particular (and slightly peculiar) way, we\n can prove them with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** Note that [reflexivity] is not enough if we state the lemma in a\n more natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** *** *)\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct].\n\n Notice that, unlike for [nat]s, [destruct] doesn't generate an\n extra subgoal here. That's because [natprod]s can only be\n constructed in one way. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros. destruct p as [n m]. simpl. reflexivity.\nQed. \n\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros. destruct p as [n m]. simpl. reflexivity.\nQed.\n\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n describe the type of _lists_ of numbers like this: \"A list is\n either the empty list or else a pair of a number and another\n list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n\n(** *** *)\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following two declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n but in case you are interested, here is roughly what's going on.\n\n The [right associativity] annotation tells Coq how to parenthesize\n expressions involving several uses of [::] so that, for example,\n the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\nNotation \"x + y\" := (plus x y) \n (at level 50, left associativity).\n The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (By the way, it's worth noting in passing that expressions like \"[1\n + 2 :: [3]]\" can be a little confusing when you read them in a .v\n file. The inner brackets, around 3, indicate a list, but the outer\n brackets, which are invisible in the HTML rendering, are there to\n instruct the \"coqdoc\" tool that the bracketed part should be\n displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(** *** Repeat *)\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist := \n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(** *** Length *)\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat := \n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(** *** Append *)\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist := \n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y) \n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\"). \n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\n(** *** Head (with default) and Tail *)\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil \n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => match h with\n | 0 => (nonzeros t)\n | _ => [h] ++ (nonzeros t) \n end\nend.\n\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => match (oddb h) with\n | true => [h] ++ (oddmembers t)\n | false => oddmembers t\n end\nend.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\n Proof. simpl. reflexivity. \nQed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n match (oddmembers l) with\n | nil => 0\n | _ => (length (oddmembers l))\nend.\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\n Proof. simpl. reflexivity.\nQed.\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\n Proof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers3: countoddmembers nil = 0.\n Proof. simpl. reflexivity. Qed. \n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n (* FILL IN HERE *) admit.\n\n\nExample test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n (* FILL IN HERE *) Admitted.\nExample test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].\n (* FILL IN HERE *) Admitted.\nExample test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].\n (* FILL IN HERE *) Admitted.\nExample test_alternate4: alternate [] [20;30] = [20;30].\n (* FILL IN HERE *) Admitted. \n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n multiple times instead of just once. One reasonable\n implementation of bags is to represent a bag of numbers as a\n list. *)\n\nDefinition bag := natlist. \n\n(** **** Exercise: 3 stars (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat := \n match s with\n | nil => 0\n | h :: t => match (beq_nat h v) with\n | true => 1 + (count v t)\n | false => 0 + (count v t)\n end\nend.\n\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. simpl. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. simpl. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := app.\n \nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed. \n\nDefinition add (v:nat) (s:bag) : bag := sum [v] s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed. \nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool := ble_nat 1 (count v s).\n\nEval compute in (member 2 [1;4;1]).\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. simpl. reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | h :: t => match (beq_nat h v) with\n | true => t\n | false => [h] ++ (remove_one v t)\n end\nend.\n\nEval compute in (remove_one 5 [2;1;5;4;1]).\n\nExample test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_one2: count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_one3: count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\nExample test_remove_one4: count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. simpl. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | h :: t => match (beq_nat h v) with\n | true => remove_all v t\n | false => [h] ++ (remove_all v t)\nend\nend.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. simpl. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n match s1 with\n | nil => true\n | h :: t => match (member h s2) with\n | true => andb true (subset t (remove_one h s2))\n | false => false\nend\nend.\n\nEval compute in (subset [1;2;2] [2;1;4;1]).\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. simpl. reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (bag_theorem) *)\n(** Write down an interesting theorem about bags involving the\n functions [count] and [add], and prove it. Note that, since this\n problem is somewhat open-ended, it's possible that you may come up\n with a theorem which is true, but whose proof requires techniques\n you haven't learned yet. Feel free to ask for help if you get\n stuck! *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match position\n in the definition of [app], allowing the match itself to be\n simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n l'\". \n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proofs will not get you very far! It is\n very important to work through the details of each one, using Coq\n and thinking about what each step of the proof achieves.\n Otherwise it is more or less guaranteed that the exercises will\n make no sense. *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n perhaps a little less familiar than standard natural number\n induction, but the basic idea is equally simple. Each [Inductive]\n declaration defines a set of data values that can be built up from\n the declared constructors: a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to a number; a\n list can be either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two things together establish the\n truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist, \n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3). \nProof.\n intros l1 l2 l3. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons n l1'\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n static written document -- it is easy to see what's going on if\n you are reading the proof in an interactive Coq session and you\n can see the current goal and context at each point, but this state\n is not visible in the written-down parts of the Coq proof. So a\n natural-language proof -- one written for human readers -- will\n need to include more explicit signposts; in particular, it will\n help the reader stay oriented if we remind them exactly what the\n induction hypothesis is in the second case. *)\n\n(** *** Informal version *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3], \n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n (the induction hypothesis). We must show\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]] \n By the definition of [++], this follows from\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n which is immediate from the induction hypothesis. []\n*)\n\n(** *** Another example *)\n(**\n Here is a similar example to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist, \n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n\n(** *** Reversing a list *)\n(** For a slightly more involved example of an inductive proof\n over lists, suppose we define a \"cons on the right\" function\n [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist := \n match l with\n | nil => [v]\n | h :: t => h :: (snoc t v)\n end.\n\n(** ... and use it to define a list-reversing function [rev]\n like this: *)\n\nFixpoint rev (l:natlist) : natlist := \n match l with\n | nil => nil\n | h :: t => snoc (rev t) h\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** *** Proofs about reverse *)\n(** Now let's prove some more list theorems using our newly\n defined [snoc] and [rev]. For something a little more challenging\n than the inductive proofs we've seen so far, let's prove that\n reversing a list does not change its length. Our first attempt at\n this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n :: l'\".\n (* This is the tricky case. Let's begin as usual \n by simplifying. *)\n simpl. \n (* Now we seem to be stuck: the goal is an equality \n involving [snoc], but we don't have any equations \n in either the immediate context or the global \n environment that have anything to do with [snoc]! \n\n We can make a little progress by using the IH to \n rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation about [snoc] that would have\n enabled us to make progress and prove it as a separate lemma. \n*)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n length (snoc l n) = S (length l).\nProof.\n intros n l. induction l as [| n' l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n' l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed. \n\n(**\n Note that we make the lemma as _general_ as possible: in particular,\n we quantify over _all_ [natlist]s, not just those that result\n from an application of [rev]. This should seem natural, \n because the truth of the goal clearly doesn't depend on \n the list having been reversed. Moreover, it is much easier\n to prove the more general property. \n*)\n \n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons\".\n simpl. rewrite -> length_snoc. \n rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems: \n\n _Theorem_: For all numbers [n] and lists [l],\n [length (snoc l n) = S (length l)].\n \n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (snoc [] n) = S (length []),\n which follows directly from the definitions of\n [length] and [snoc].\n\n - Next, suppose [l = n'::l'], with\n length (snoc l' n) = S (length l').\n We must show\n length (snoc (n' :: l') n) = S (length (n' :: l')).\n By the definitions of [length] and [snoc], this\n follows from\n S (length (snoc l' n)) = S (S (length l')),\n]] \n which is immediate from the induction hypothesis. [] *)\n \n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n \n _Proof_: By induction on [l]. \n\n - First, suppose [l = []]. We must show\n length (rev []) = length [],\n which follows directly from the definitions of [length] \n and [rev].\n \n - Next, suppose [l = n::l'], with\n length (rev l') = length l'.\n We must show\n length (rev (n :: l')) = length (n :: l').\n By the definition of [rev], this follows from\n length (snoc (rev l') n) = S (length l')\n which, by the previous lemma, is the same as\n S (length (rev l')) = S (length l').\n This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n and pedantic. After the first few, we might find it easier to\n follow proofs that give fewer details (since we can easily work\n them out in our own minds or on scratch paper if necessary) and\n just highlight the non-obvious steps. In this more compressed\n style, the above proof might look more like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that\n length (snoc l n) = S (length l)\n for any [l]. This follows by a straightforward induction on [l].\n The main property now follows by another straightforward\n induction on [l], using the observation together with the\n induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and on how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for\n present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, using [rewrite], and later we will see other ways\n of reusing previous theorems. But in order to refer to a theorem,\n we need to know its name, and remembering the names of all the\n theorems we might ever want to use can become quite difficult! It\n is often hard even to remember what theorems have been proven,\n much less what they are named.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following to\n see a list of theorems that we have proved about [rev]: *)\n\n(* SearchAbout rev. *)\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the course; it can save you a lot of time! *)\n\n(** Also, if you are using ProofGeneral, you can run [SearchAbout]\n with [C-c C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist, \n l ++ [] = l. \nProof.\n intros. induction l as [| n l'].\n Case \"[]\".\n simpl. reflexivity.\n Case \"l1 = cons\".\n simpl. rewrite IHl'. reflexivity.\nQed.\n\nTheorem rev_snoc : forall l : natlist, forall n : nat,\n rev (snoc l n) = n :: (rev l).\nProof.\n intros. induction l.\n Case \"nil\".\n simpl. reflexivity.\n Case \"l = cons\". \n simpl. rewrite IHl. simpl. reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros. induction l.\n Case \"nil\".\n simpl. reflexivity.\n Case \"cons\".\n simpl. rewrite rev_snoc. rewrite IHl. reflexivity.\nQed.\n\n(** There is a short solution to the next exercise. If you find\n yourself getting tangled up, step back and try to look for a\n simpler way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros. rewrite app_assoc. rewrite app_assoc. reflexivity.\nQed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n snoc l n = l ++ [n].\nProof.\n intros. induction l.\n Case \"[]\".\n simpl. reflexivity.\n Case \"cons\".\n simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem distr_rev : forall l1 l2 : natlist,\n rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n intros. induction l1.\n Case \"[]\".\n simpl. rewrite app_nil_end. reflexivity.\n Case \"l1 = cons\".\n simpl. \n rewrite snoc_append. \n rewrite IHl1. \n rewrite snoc_append. \n rewrite app_assoc.\n reflexivity.\nQed.\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros. induction l1.\n Case \"[]\".\n simpl. reflexivity.\n Case \"cons\".\n destruct n as [| n'].\n simpl. apply IHl1.\n simpl. rewrite IHl1. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n match l1 with\n | nil => match l2 with\n | nil => true\n | _ => false\n end\n | h :: t => match l2 with\n | nil => false\n | x :: xs => match (beq_nat h x) with\n | true => beq_natlist t xs\n | false => false\nend\nend\nend.\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\nProof. simpl. reflexivity. Qed.\nExample test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\nProof. simpl. reflexivity. Qed.\nExample test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.\nProof. simpl. reflexivity. Qed.\n\nTheorem beq_nat_refl : forall n:nat,\n true = beq_nat n n.\nProof.\n intros. induction n.\n simpl. reflexivity.\n simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\n intros. induction l.\n simpl. reflexivity.\n simpl. rewrite <- beq_nat_refl. rewrite IHl. reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 2 stars (list_design) *)\n(** Design exercise: \n - Write down a non-trivial theorem involving [cons]\n ([::]), [snoc], and [app] ([++]). \n - Prove it. *) \n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n definitions about bags earlier in the file. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** The following lemma about [ble_nat] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n ble_nat n (S n) = true.\nProof.\n intros n. induction n as [| n'].\n Case \"0\". \n simpl. reflexivity.\n Case \"S n'\".\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *) \n(** Write down an interesting theorem about bags involving the\n functions [count] and [sum], and prove it.*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nThere is a hard way and an easy way to solve this exercise.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n\n(** One use of [natoption] is as a way of returning \"error\n codes\" from functions. For example, suppose we want to write a\n function that returns the [n]th element of some list. If we give\n it type [nat -> natlist -> nat], then we'll have to return some\n number when the list is too short! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with \n | true => a \n | false => index_bad (pred n) l' \n end\n end.\n\n(** *** *)\n(** On the other hand, if we give it type [nat -> natlist ->\n natoption], then we can return [None] when the list is too short\n and [Some a] when the list has enough members and [a] appears at\n position [n]. *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption. \n\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => match beq_nat n O with \n | true => Some a\n | false => index (pred n) l' \n end\n end.\n\nExample test_index1 : index 0 [4;5;6;7] = Some 4.\nProof. reflexivity. Qed.\nExample test_index2 : index 3 [4;5;6;7] = Some 7.\nProof. reflexivity. Qed.\nExample test_index3 : index 10 [4;5;6;7] = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n small feature of Coq's programming language: conditional\n expressions... *)\n\n(** *** *)\n\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => if beq_nat n O then Some a else index' (pred n) l'\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_opt (l : natlist) : natoption :=\n (* FILL IN HERE *) admit.\n\nExample test_hd_opt1 : hd_opt [] = None.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_opt l).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Dictionaries *)\n\n(** As a final illustration of how fundamental data structures\n can be defined in Coq, here is the declaration of a simple\n [dictionary] data type, using numbers for both the keys and the\n values stored under these keys. (That is, a dictionary represents\n a finite map from numbers to numbers.) *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n | empty : dictionary \n | record : nat -> nat -> dictionary -> dictionary. \n\n(** This declaration can be read: \"There are two ways to construct a\n [dictionary]: either using the constructor [empty] to represent an\n empty dictionary, or by applying the constructor [record] to\n a key, a value, and an existing [dictionary] to construct a\n [dictionary] with an additional key to value mapping.\" *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n (record key value d).\n\n(** Here is a function [find] that searches a [dictionary] for a\n given key. It evaluates evaluates to [None] if the key was not\n found and [Some val] if the key was mapped to [val] in the\n dictionary. If the same key is mapped to multiple values, [find]\n will return the first one it finds. *)\n\nFixpoint find (key : nat) (d : dictionary) : natoption := \n match d with \n | empty => None\n | record k v d' => if (beq_nat key k) \n then (Some v) \n else (find key d')\n end.\n\n\n\n(** **** Exercise: 1 star (dictionary_invariant1) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n (find k (insert k v d)) = Some v.\nProof.\n intros. induction k.\n simpl. reflexivity.\n simpl. rewrite <- beq_nat_refl. reflexivity.\nQed.\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),\n beq_nat m n = false -> find m d = find m (insert n o d).\nProof.\n intros. induction d.\n simpl. rewrite H. reflexivity.\n simpl. rewrite H. reflexivity.\nQed.\n\nEnd Dictionary.\n\nEnd NatList.\n\n(* $Date: 2014-01-28 13:19:45 -0500 (Tue, 28 Jan 2014) $ *)\n\n", "meta": {"author": "dariajung", "repo": "cis500", "sha": "86ee167e374df1941dc65df2267b5d37408bf50e", "save_path": "github-repos/coq/dariajung-cis500", "path": "github-repos/coq/dariajung-cis500/cis500-86ee167e374df1941dc65df2267b5d37408bf50e/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.9263037226647284, "lm_q1q2_score": 0.8689877699502789}} {"text": "Require Import Bool Arith List.\n \n(* 6. Write the script that proves the following formula\n forall (P Q : nat -> Prop),\n forall (x y : nat), (forall z, P z -> Q z) -> x = y -> P x ->\n P x /\\ Q y. *)\n\nLemma ex6 :\n forall (P Q : nat -> Prop),\n forall (x y : nat), (forall z, P z -> Q z) -> x = y -> P x -> P x /\\ Q y.\nProof.\nintros P Q.\nintros x y.\nintros z.\n\nintros x_eq_y.\nintros px.\n\nsplit.\n\nexact px.\n\nrewrite <- x_eq_y.\n\napply z.\nexact px.\n\nQed.\n\n\n(* 8. Write the script that proves the following formula\n forall P : nat -> Prop, (forall x, P x) ->\n exists y:nat, P y /\\ y = 0 *)\n\nLemma ex8 :\n forall P : nat -> Prop, (forall x, P x) -> exists y:nat, P y /\\ y = 0.\nProof.\nintros P.\nintros Px.\n\nexists 0.\n\nsplit.\n\napply Px.\nreflexivity.\nQed.\n\n(* 1. Write a predicate multiple_of type nat -> nat -> Prop, \n so that multiple a b expresses that a is a multiple of b\n (in other words, there exists a number k such that a = k * b). *)\n\nDefinition multiple_of (a b : nat) : Prop := \n exists k, a = k * b.\n\n(* 2. Write a formula using natural numbers that expresses that when\n n is even (a multiple of 2) then n * n is even. *)\n\nDefinition even (n : nat) :=\n multiple_of n 2.\n\nCheck forall n, even n -> even (n * n).\n\n(* 3. Write a formula using natural numbers that expresses that when\n a number n is a multiple of some k, then n * n is a multiple of k\n (you don't have to prove it yet). *)\n\nDefinition mul_sq (n k : nat) :=\n forall (n k : nat), (multiple_of n k) -> ( multiple_of (n * n) k).\n\nCheck forall n k, mul_sq n k.\n\n(* 4. Write a predicate odd of type nat -> Prop that characterize\n odd numbers like 3, 5, 37. Avoid ~ (even ..). *)\n\nDefinition odd (n : nat) : Prop :=\n even (n + 1).\n \n(* 9. Search the lemma proving associativity of multiplication *)\n\nSearchAbout ( _ * _ * _ = _ *(_ * _) ).\n\n(* 10. Write the script that proves that when n is a multiple of k,\n then n * n is also a multiple of k. *)\n\nLemma ex10 :\n forall (n k : nat), (multiple_of n k) -> ( multiple_of (n * n) k).\nProof.\nunfold multiple_of.\nintros n k.\nintros k0.\n\n\n(* 11. Search the lemmas proving the following properties:\n - distributivity of plus and mult\n - associativity of plus\n - 1 is a neutral elelemt for multiplication *)\n\nSearchAbout ( 1 * _ = _ ).\n\n(* 12. Show that the sum of two even numbers is even *)\n\nLemma ex12 : ...\n\n(* 13. Write the script that proves that when n is odd,\n then n * n is also odd. *)\n\nLemma ex13 : ...\n", "meta": {"author": "vabh", "repo": "Coq", "sha": "75b90a61d518aead333de748a08b5ed04585ef9c", "save_path": "github-repos/coq/vabh-Coq", "path": "github-repos/coq/vabh-Coq/Coq-75b90a61d518aead333de748a08b5ed04585ef9c/ex3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.921921834855049, "lm_q1q2_score": 0.8689175242827322}} {"text": "Inductive bool : Type :=\n | true\n | false.\n\nDefinition negb (b:bool) : bool :=\n match b with\n | false => true\n | true => false\n end.\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n match b1 with\n | false => true\n | true => negb b2\n end.\n\nExample test_nandb1:(nandb true false) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_nandb2:(nandb false false) = true.\nProof. simpl. reflexivity. Qed.\n\nDefinition andb2 (b1:bool)(b2:bool) : bool :=\n match b1 with\n | false => false\n | true => b2\n end.\n\nNotation \"x && y\" := (andb2 x y).\n\nDefinition andb3 (b1:bool)(b2:bool)(b3:bool) : bool :=\n match b1 with\n | false => false\n | true => andb2 b2 b3\n end.\n\nExample test_andb31:(andb3 true true true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb32:(andb3 false true false) = false.\nProof. simpl. reflexivity. Qed.\n\n\nModule NatPlayground.\n\nInductive nat : Type :=\n | O\n | S (n:nat).\nEnd NatPlayground.\n\nFixpoint evenb (n:nat) : bool :=\n match n with\n | O => true\n | S O => false\n | S (S n') => evenb n'\n end.\n\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\nModule NatPlayground2.\n\nFixpoint plus (n m :nat) : nat :=\n match n with\n | O => m\n | S n' => S (plus n' m)\n end.\n\nFixpoint mult (n m : nat) : nat :=\n match n with\n | O => O\n | S n' => plus m (mult n' m)\n end.\nFixpoint minus (n m:nat) : nat :=\n match n, m with\n | O , _ => O\n | S _ , O => n\n | S n', S m' => minus n' m'\n end.\nEnd NatPlayground2.\nCompute (mult 3 2).\n\nFixpoint exp (base power : nat) : nat :=\n match power with\n | O => S O\n | S p => mult base (exp base p)\n end.\n\nNotation \"x + y\" := (plus x y)\n (at level 50, left associativity)\n : nat_scope.\nNotation \"x - y\" := (minus x y)\n (at level 50, left associativity)\n : nat_scope.\nNotation \"x * y\" := (mult x y)\n (at level 40, left associativity)\n : nat_scope.\n\n(*n的阶乘*)\nFixpoint factorial (n:nat) : nat :=\n match n with\n | O => S O\n | S n' => n * (factorial n')\n end.\n\nExample test_factorial1 : (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\n\nFixpoint eqb (n m : nat) : bool :=\n match n with\n | O => match m with\n | O => true\n | S m' => false\n end\n | S n' => match m with\n | O => false\n | S m' => eqb n' m'\n end\n end.\n\nFixpoint leb (n m : nat) : bool :=\n match n with\n | O => true\n | S n' =>\n match m with\n | O => false\n | S m' => leb n' m'\n end\n end.\n\nFixpoint ltb (n m : nat) : bool :=\n match n with\n | O => match m with\n | S m' => true\n | O => false\n end\n | S n'=> match m with\n | O => false\n | S m' => ltb n' m'\n end\n end.\n\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\nNotation \"x n + n = m + m.\nProof. intros n m. intros H. rewrite <-H. reflexivity. Qed.\n\nTheorem plus_id_exercise : forall n m o : nat,\n n = m -> m = o -> n + m = m + o.\nProof.\n intros n m o.\n intros H1.\n intros H2.\n rewrite H1, H2.\n reflexivity. Qed.\n\nTheorem mult_0_plus : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n rewrite -> plus_O_n.\n reflexivity. Qed.\n\nTheorem mult_S_1 : forall n m : nat,\n m = S n -> m * (1+n) = m*m.\nProof.\n intros n m.\n intros H1.\n rewrite H1.\n reflexivity.\n Qed.\n\nTheorem andb_commutative : forall b c, andb b c = andb c b.\nProof.\n intros b c. destruct b eqn:Eb.\n - destruct c eqn:Ec.\n + reflexivity.\n + reflexivity.\n - destruct c eqn:Ec.\n + reflexivity.\n + reflexivity.\nQed.\n\nTheorem andb3_exchange :\n forall b c d, andb (andb b c) d = andb (andb b d) c.\nProof.\n intros b c d. destruct b eqn:Eb.\n - destruct c eqn:Ec.\n { destruct d eqn:Ed.\n - reflexivity.\n - reflexivity. }\n { destruct d eqn:Ed.\n - reflexivity.\n - reflexivity. }\n - destruct c eqn:Ec.\n { destruct d eqn:Ed.\n - reflexivity.\n - reflexivity. }\n { destruct d eqn:Ed.\n - reflexivity.\n - reflexivity. }\nQed.\n\nTheorem andb_true_elim2 : forall b c : bool,\n andb2 b c = true -> c = true.\nProof.\n intros. destruct b eqn : Eb.\n - apply H.\n - destruct c eqn : Ec.\n + reflexivity.\n + rewrite<- H. simpl. reflexivity.\nQed.\n\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n 0 =? (n + 1) = false.\nProof.\n intros [|n'].\n - reflexivity.\n - reflexivity.\nQed.", "meta": {"author": "fbw867294173", "repo": "Coq", "sha": "e5d34d5d72e8ce00ed08100498a6267031707518", "save_path": "github-repos/coq/fbw867294173-Coq", "path": "github-repos/coq/fbw867294173-Coq/Coq-e5d34d5d72e8ce00ed08100498a6267031707518/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.918480237330998, "lm_q1q2_score": 0.868699777906291}} {"text": "(* --- Homework 1, Part 2: Introduction to Coq, continued with Frap --- *)\n\n(*\n * In this part of the homework, we get some practice with lists and other data structures\n * and use Frap tactics.\n *\n * Step through this file with CoqIDE (or another IDE for Coq), and complete the problems.\n * (Search for \"PROBLEM\" to be sure you find them all.)\n *\n * Throughout, we include the approximate lines of code (LOC) or number of tactics\n * for each of our solutions to these problems. These are rough guidelines to help\n * you figure out if you are getting off-track.\n *\n * There is no penalty for writing a shorter or longer solution! However, if you find\n * yourself writing a much longer solution, see if you can figure out a simpler way.\n *\n *)\n\n(* --- Making sure Frap is installed --- *)\n\n(*\n * PROBLEM 0 [0 points, 0 LOC]\n * Set up Frap as described in README.md\n *\n * Once Coq is installed according to directions, you should be able to step over\n * the following line in your IDE.\n *)\n\nRequire Import Frap.\nSet Implicit Arguments.\n\n(* --- More arithmetic --- *)\n\n(* This module creates a namespace where we can travel back in time to part 1.\n * Later in part 2, we're going to start using the Coq standard library version of\n * nat, so we hide our own definitions in this namespace so we can close it later.\n *)\nModule leftover_from_part_1.\n\n(*\n * Here are some definitions again from part 1 of the homework.\n *)\nInductive nat : Type :=\n| O : nat\n| S : nat -> nat.\n\nFixpoint add (n1 : nat) (n2 : nat) : nat :=\n match n1 with\n | O => n2\n | S m1 => S (add m1 n2)\n end.\n\nFixpoint mult (n1 : nat) (n2 : nat) : nat :=\n match n1 with\n | O => O\n | S m1 => add n2 (mult m1 n2)\n end.\n\n(*\n * PROBLEM 1 [8 points, ~10 tactics, plus 3-4 helper lemmas, each needing <10 tactics]\n * Prove that multiplication is commutative, as stated by the lemma below.\n *\n * This was a challenge problem on part 1. If you already did it, feel free to\n * copy-paste your solution here.\n *\n * Hints from last time are reproduced below.\n *\n * Hint: Proceed by induction.\n *\n * Hint: Don't use more than one induction inside a single proof. Instead, figure out\n * lemmas that might be useful, and then prove those separately (by induction, probably).\n *\n * Hint: It might be useful to review all the lemmas about `add` in part 1.\n * Feel free to copy them over if you need to use them. You might need to state and prove\n * some analogous lemmas about `mult`.\n *\n * Hint: In order to prove your helpers about `mult`, you might need 1 or 2 additional\n * facts about `add`. Try to keep these simple, based on facts you know from math, and\n * prove them by induction.\n *)\n\nLemma add_one_2nd_arg:\n forall n1 n2,\n S (add n1 n2) = add n1 (S n2).\nProof.\n induction n1; intro n2.\n - simpl. reflexivity.\n - simpl. rewrite IHn1. reflexivity.\nQed.\n\nLemma add_swap:\n forall n1 n2 n3,\n add n1 (add n2 n3) = add n2 (add n1 n3).\nProof.\n induction n1; intro n2.\n - simpl. reflexivity.\n - simpl. intro n3. rewrite IHn1. rewrite add_one_2nd_arg. reflexivity.\nQed.\n\nLemma mult_zero:\n forall n1,\n mult n1 O = O.\nProof.\n induction n1.\n - simpl. reflexivity.\n - simpl. rewrite IHn1. reflexivity.\nQed.\n\nLemma mult_add_one:\n forall n1 n2,\n add n1 (mult n1 n2) = mult n1 (S n2).\nProof.\n induction n1; intro n2.\n - simpl. reflexivity.\n - simpl. rewrite add_swap. rewrite IHn1. reflexivity.\nQed.\n\nLemma mult_comm :\n forall n1 n2,\n mult n1 n2 = mult n2 n1.\nProof.\n induction n1; intro n2.\n - simpl. rewrite mult_zero. reflexivity.\n - simpl. rewrite IHn1. rewrite mult_add_one. reflexivity.\nQed.\n\n(*\n * PROBLEM 2 [10 points, 5-10 tactics, plus 1-3 helper lemmas, each needing 5-10 tactics]\n * State and prove that the `mult` function is associative.\n *\n * Hint: Feel free to look up what associative means.\n *\n * Hint: You'll probably need 1-2 more lemmas about mult and/or add.\n *)\n(*\n * PROBLEM 2 [10 points, 5-10 tactics, plus 1-3 helper lemmas, each needing 5-10 tactics]\n * State and prove that the `mult` function is associative.\n *\n * Hint: Feel free to look up what associative means.\n *\n * Hint: You'll probably need 1-2 more lemmas about mult and/or add.\n *)\n\nLemma add_assoc :\n forall n1 n2 n3,\n add n1 (add n2 n3) = add (add n1 n2) n3.\nProof.\n intros.\n induct n1.\n - simplify. reflexivity.\n - simplify. rewrite IHn1. reflexivity.\nQed.\n\nLemma add_S :\n forall n1 n2,\n add n1 (S n2) = S (add n1 n2).\nProof.\n induction n1; intro n2; simpl.\n - reflexivity.\n - rewrite IHn1. reflexivity.\nQed.\n\nLemma add_O :\n forall n1,\n add n1 O = n1.\nProof.\n intros.\n induct n1.\n - simplify. reflexivity.\n - simplify. rewrite IHn1. reflexivity.\nQed.\n\nLemma add_comm :\n forall n1 n2,\n add n1 n2 = add n2 n1.\nProof.\n induction n1; intro n2; simpl.\n - rewrite add_O. reflexivity.\n - rewrite add_S. rewrite IHn1. reflexivity.\nQed.\n\nLemma add_four_swap_middle :\n forall n1 n2 n3 n4,\n add (add n1 n2) (add n3 n4) = add (add n1 n3) (add n2 n4).\nProof.\n intros.\n rewrite <- (add_assoc n1).\n rewrite -> (add_assoc n2).\n rewrite -> (add_comm n2).\n rewrite <- (add_assoc n3).\n rewrite -> (add_assoc n1).\n reflexivity.\nQed.\n\nLemma mult_dist :\n forall n1 n2 n3,\n mult n1 (add n2 n3) = add (mult n1 n2) (mult n1 n3).\nProof.\n intros.\n induct n1.\n - simplify. reflexivity.\n - simplify. rewrite IHn1. rewrite add_four_swap_middle. reflexivity.\nQed.\n\nLemma mult_assoc :\n forall n1 n2 n3,\n mult n1 (mult n2 n3) = mult (mult n1 n2) n3.\nProof.\n intros.\n induct n1.\n - simplify. reflexivity.\n - simplify.\n rewrite IHn1.\n rewrite (mult_comm (add n2 (mult n1 n2)) n3).\n rewrite mult_dist.\n rewrite (mult_comm n3 n2).\n rewrite (mult_comm n3 (mult n1 n2)).\n reflexivity.\nQed.\n\nEnd leftover_from_part_1. (* close the namespace *)\n\n(*\n * Now that you've seen how nat, add, and mult are defined under the hood,\n * from now on we'll use the versions in Coq's standard library. These come\n * with nice notations like `1 + 3 * 4`, and with lots of free lemmas.\n *\n * There are also some useful tactics for working with arithmetic. Please\n * see FRAP section 2.4 for a discussion.\n *\n * Here are some automated proofs that the Coq standard library versions\n * of add and mult are commutative. (These lemmas are also in the standard\n * library, but we prove them from scratch just to demonstrate the tactics.)\n *)\n\nLemma add_comm_again :\n forall a b, a + b = b + a.\nProof.\n intros.\n linear_arithmetic.\nQed.\n\nLemma mult_comm_again :\n forall a b, a * b = b * a.\nProof.\n intros.\n Fail linear_arithmetic. (* doesn't work!! *)\n ring. (* works!! *)\nQed.\n\n(*\n * PROBLEM 3 [8 points, 2 clear yes/no answers and ~4 sentences of explanation]\n * Answer the following in ~1 sentence each. If the bullet point starts with a yes/no question,\n * be sure to state your yes/no answer clearly before proceeding to explain.\n *\n * - Why does `linear_arithmetic` succeed on `add_comm_again`, but fail on `mult_comm_again`?\n Linear_arithmetic supports only addition. It supports multiplication by constants. \n\n * - Why does `ring` succeed on `mult_comm_again`?\n Ring is used to normalize any ring structure(i.e. structures having rings and semi-rings\n like x(3+yx+25(1−z))+zx). A ring in a basic sense satisfies\n all the properties of addition and multiplication. The basic use of ring is to simplify \n ring expressions, so that the user does not have to deal manually with the \n theorems of associativity and commutativity. In a ring structure, associativity and \n distributivity of multiplication is supported.\n\n * - Will `ring` succeed on `add_comm_again`? Why or why not?\n It will succeed. In ring structure addition is commutative and associative.\n\n * - Is `ring` always more powerful than `linear_arithmetic`? Why or why not?\n I think 'ring' is a superset of linear arithmetic. So it should be more powerful than\n linear_arithmetic always.\n *)\n\n\n(* --- Curry-Howard practice --- *)\n\nModule curry_howard.\n(*\n * In lecture, we looked at an inductive definition of the types `True` and `False`,\n * and talked about how they encode logical ideas as types.\n *\n * One of the deep connections in type theory is between logic and programming.\n * In fact, there are programming analogues to `True` and `False`.\n *)\n\nInductive unit : Type :=\n| tt : unit.\n\nInductive empty : Type :=\n.\n\n(*\n * PROBLEM 4 [5 points, 1-2 sentences]\n * Explain in your own words the relationship between `unit` and `True`, and between\n * `empty` and `False`.\n unit is just any type. Whenever a label \"tt\" occurs we specify it as true.\n \"empty\" is a type which does not match to anything. So we cannot create false \n from anything.\n *)\n\n(*\n * Here are two ways of defining the identity function on `unit`.\n *)\n\nDefinition unit_id1 (x : unit) : unit := x. (* first way: just return the argument *)\nDefinition unit_id2 (x : unit) : unit :=\n match x with (* second way: take the argument apart and put it back together again *)\n | tt => tt\n end.\n\n(*\n * PROBLEM 5 [5 points, ~3 tactics]\n * Prove that the two definition of the identity function on `unit` are the same\n * by proving the following lemma.\n *)\nLemma unit_id_same :\n forall x,\n unit_id1 x = unit_id2 x.\nProof.\n intros.\n rewrite unit_id1.\n rewrite unit_id2.\n reflexivity.\nQed.\n\n(*\n * By analogy, we can also present two different proofs that True implies True.\n *)\nLemma True_implies_True1 :\n True -> True.\nProof.\n intro H. (* first way: just take the evidence of True and use it directly *)\n apply H.\nQed.\n\nLemma True_implies_True2 :\n True -> True.\nProof.\n intro H. (* second way: take apart the evidence of True and put it back together *)\n cases H.\n exact I.\nQed.\n\n(*\n * We can ask Coq to print definitions using the `Print` command. This works\n * not only for things defined with Definition/Fixpoint, but also for things\n * defined via Lemma/Theorem.\n *\n * Coq prints things in a \"de-sugared\" form, with more type annotations, but\n * usually it's pretty easy to see how it corresponds to what you wrote.\n *)\n\nPrint unit_id1.\n(*\n * This command prints `fun x : unit => x`, which is syntax for a function\n * that takes an argument `x` of type `unit` and just returns it, which\n * is exactly what we wrote in the definition of `unit_id1`.\n *)\n\n\n(*\n * We can also ask Coq to print the underlying proof term for the lemma\n * `True_implies_True1`.\n *)\nPrint True_implies_True1.\n\n(*\n * We can similarly print the definitions for the second versions.\n *)\nPrint unit_id2.\nPrint True_implies_True2.\n\n(*\n * PROBLEM 6 [8 points, 2 proofs, each with <5 tactics, and 2 definitions, each with <5 LOC]\n * Prove that False implies False in two different ways, one that just takes\n * the evidence of False and uses it directly, and one which takes it apart\n * and puts it back together again.\n *\n * For each proof, also print its proof term using the Print command. If you\n * see anything interesting or surprising, write a comment here. (worth 0 pts)\n *\n * Then, define two identity functions on `empty`, one which just returns its argument,\n * and one which takes its argument apart and puts it back together again.\n *\n * Hint: If you're stuck on the definitions, you can work by analogy to the proof terms\n * you saw by using the Print command on your proofs.\n *)\nLemma False_implies_False1 :\n False -> False.\nProof.\n intro H. (* first way: just take the evidence of True and use it directly *)\n apply H.\nQed.\n\nLemma False_implies_False2 :\n False -> False.\nProof.\n intro H. (* second way: take apart the evidence of True and put it back together *)\n cases H.\nQed.\n\nPrint False_implies_False1.\nPrint False_implies_False2.\n\nDefinition empty_id1 (x : empty) : empty := x. (* first way: just return the argument *)\nDefinition empty_id2 (x : empty) : empty := (* second way: take the argument apart *)\n match x with\n end.\n\nEnd curry_howard.\n\n(* --- List practice --- *)\n\n(* Here are some copied definitions from FRAP. *)\nInductive list (A : Type) : Type :=\n| nil\n| cons (hd : A) (tl : list A).\n\nArguments nil [A].\nInfix \"::\" := cons.\nNotation \"[ ]\" := nil.\nNotation \"[ x1 ; .. ; xN ]\" := (cons x1 (.. (cons xN nil) ..)).\n\nFixpoint length {A} (ls : list A) : nat :=\n match ls with\n | nil => 0\n | _ :: ls' => 1 + length ls'\n end.\n\nFixpoint app {A} (ls1 ls2 : list A) : list A :=\n match ls1 with\n | nil => ls2\n | x :: ls1' => x :: app ls1' ls2\n end.\nInfix \"++\" := app.\n\nFixpoint rev {A} (ls : list A) : list A :=\n match ls with\n | nil => nil\n | x :: ls' => rev ls' ++ [x]\n end.\n\nFixpoint rev_append {A} (ls acc : list A) : list A :=\n match ls with\n | nil => acc\n | x :: ls' => rev_append ls' (x :: acc)\n end.\n\nDefinition rev' {A} (ls : list A) : list A :=\n rev_append ls [].\n\n(*\n * PROBLEM 7 [12 points, ~6 tactics plus 1 copy-pasted helper lemma from lecture]\n * Prove the following theorem about the length of a reversed list.\n *\n * Hint: Proceed by induction on l.\n *\n * Hint: You'll need a helper lemma from lecture. Feel free to copy-paste it\n * when you find it.\n *)\n\nTheorem length_app : forall A (ls1 ls2 : list A),\n length (ls1 ++ ls2) = length ls1 + length ls2.\nProof.\n induct ls1; simplify; equality.\nQed.\n\nLemma length_rev :\n forall A (l : list A),\n length (rev l) = length l.\nProof.\n induct l.\n - simplify. reflexivity.\n - simplify. rewrite length_app. rewrite IHl. simplify. linear_arithmetic.\nQed.\n\n(*\n * PROBLEM 8 [10 points, (1 alternate proof and a few sentences comparing to Adam's proof)\n * OR (an explanation of how to come up with rev_append_ok)]\n * Go back to rev'_ok and proceed directly by induction on `ls` and assume you did\n * not have access to the lemma rev_append_ok (or had not thought of it yet).\n *\n * Can you find an alternative proof? If so, provide it, and also explain what makes it\n * better/worse/different from Adam's proof. If you can't find an alternative (or if\n * you strongly dislike all the alternatives you can find), instead explain how\n * you might \"come up\" with the lemma rev_append_ok based on your experience getting\n * stuck during a direct proof.\n *)\n\n(* The proof below works, but is more complex and less intuitive than Adam's proof.\n The natural approach to the proof -- the one I, at least, would come up with just\n on instinct -- would involve rev_append_ok. The proof here \"worked backward\" in\n a sense -- note the step where it applies a reverse rewrite of the inductive\n hypothesis in the rev'_ok proof.\n \n On the other hand, inverting the theorem itself might have made this a more\n natural-feeling approach. *)\nLemma app_assoc :\n forall A (ls1 : list A) (ls2 : list A) (ls3 : list A),\n (ls1 ++ ls2) ++ ls3 = ls1 ++ (ls2 ++ ls3).\nProof.\n intros.\n induct ls1.\n - simplify. reflexivity.\n - simplify. rewrite IHls1. reflexivity.\nQed.\n\nLemma rev_append_empty_acc :\n forall A (ls1 : list A) (ls2 : list A),\n rev_append ls1 ls2 = rev_append ls1 [] ++ ls2.\nProof.\n intros.\n induct ls1.\n - simplify. reflexivity.\n - simplify.\n rewrite IHls1.\n rewrite (IHls1 [hd]).\n rewrite app_assoc.\n simplify.\n reflexivity.\nQed.\n\nTheorem rev'_ok :\n forall A (ls : list A),\n rev' ls = rev ls.\nProof.\n induct ls.\n - simplify. reflexivity.\n - simplify.\n rewrite <- IHls.\n unfold rev'.\n simplify.\n rewrite rev_append_empty_acc.\n reflexivity.\nQed.\n\n(* --- Binary Tree practice --- *)\n\n(* More definitions copied from FRAP. *)\nInductive tree (A : Type) : Type :=\n| Leaf\n| Node : tree A -> A -> tree A -> tree A.\nArguments Leaf [A].\n\nFixpoint reverse {A} (t : tree A) : tree A :=\n match t with\n | Leaf => Leaf\n | Node l d r => Node (reverse r) d (reverse l)\n end.\n\n(*\n * Here is a function that adds up all the elements of a list of nats.\n *)\nFixpoint sum_list (l : list nat) : nat :=\n match l with\n | [] => 0\n | x :: xs => x + sum_list xs\n end. \n\n(*\n * PROBLEM 9 [5 points, ~5 LOC]\n * Define a function that adds up all the elements of a tree of nats.\n *)\nFixpoint sum_tree (t : tree nat) : nat :=\n match t with\n | Leaf => 0\n | Node l d r => (sum_tree l) + d + (sum_tree r) \n end.\n\n(*\n * PROBLEM 10 [5 points, ~5 tactics]\n * Prove that `reverse` has no effect on the sum of the elements in a tree.\n *)\nLemma sum_tree_reverse :\n forall t,\n sum_tree (reverse t) = sum_tree t.\nProof.\n intros. induct t.\n - simplify. reflexivity.\n - simplify. rewrite IHt1. rewrite IHt2. linear_arithmetic.\nQed.\n\n(*\n * PROBLEM 11 [12 points, 5-10 tactics, plus 1 helper lemma needing ~5 tactics]\n * Prove the following similar lemma about `sum_list` and `rev`.\n *\n * Hint: Proceed by induction on l.\n *\n * Hint: You'll need a helper lemma about sum_list.\n *)\n\nLemma sum_list_app :\n forall l1 l2,\n sum_list (l1 ++ l2) = sum_list l1 + sum_list l2.\nProof.\n intros. induct l1.\n - simplify. reflexivity.\n - simplify. rewrite IHl1. ring.\nQed.\n\nLemma sum_list_rev :\n forall l,\n sum_list (rev l) = sum_list l.\nProof.\n intros. induct l.\n - simplify. reflexivity.\n - simplify. rewrite sum_list_app. simplify. rewrite IHl. ring.\nQed.\n\n(* --- Syntax practice --- *)\n\nModule ArithWithConstants.\n(* Copied from FRAP. *)\nInductive arith : Set :=\n| Const (n : nat)\n| Plus (e1 e2 : arith)\n| Times (e1 e2 : arith).\n\n(*\n * Here's a function that kind of sums up the constants in the syntax tree,\n * just like sum_tree did in the previous section. The difference is that\n * at a `Times` node, we multiply the values instead of adding them.\n *)\nFixpoint kinda_sum (e : arith) : nat :=\n match e with\n | Const n => n\n | Plus e1 e2 => kinda_sum e1 + kinda_sum e2\n | Times e1 e2 => kinda_sum e1 * kinda_sum e2\n end.\n\nCompute kinda_sum (Plus (Const 1) (Const 1)). (* 2 *)\nCompute kinda_sum (Times (Const 2) (Const 3)). (* 6 *)\n\n(* From FRAP. *)\nFixpoint commuter (e : arith) : arith :=\n match e with\n | Const _ => e\n | Plus e1 e2 => Plus (commuter e2) (commuter e1)\n | Times e1 e2 => Times (commuter e2) (commuter e1)\n end.\n\n(*\n * PROBLEM 12 [12 points, 5-10 tactics]\n * Prove the following theorem about kinda_sum and commuter.\n *)\nLemma kind_sum_commuter :\n forall e,\n kinda_sum e = kinda_sum (commuter e).\nProof.\n intros. induct e.\n - simplify. reflexivity.\n - simplify. rewrite IHe1. rewrite IHe2. ring.\n - simplify. rewrite IHe1. rewrite IHe2. ring.\nQed.\n\n\n(* --- The End --- *)\n\n(*\n * This is the end of part 2 of homework 1.\n *\n * To submit your homework, please follow the instructions at the end of the\n * README.md file in this directory.\n *\n * Please also see the README.md file to read about how we will grade this homework.\n *)\n\n(* --- Challenge problem --- *)\n\n(*\n * There's one more challenge problem below, which you can try if you like.\n * It will not be worth any points on this homework, or any future one,\n * but you will get to continue to play the video game called Coq.\n *\n * You already have all the techniques you need to solve it, but it is slightly\n * longer than the previous problems.\n *)\n\n(*\n * We can define a version of constant folding from FRAP, but for arithmetic\n * without variables.\n *)\n\nFixpoint constantFold (e : arith) : arith :=\n match e with\n | Const _ => e\n | Plus e1 e2 =>\n let e1' := constantFold e1 in\n let e2' := constantFold e2 in\n match e1', e2' with\n | Const n1, Const n2 => Const (n1 + n2)\n | Const 0, _ => e2'\n | _, Const 0 => e1'\n | _, _ => Plus e1' e2'\n end\n | Times e1 e2 =>\n let e1' := constantFold e1 in\n let e2' := constantFold e2 in\n match e1', e2' with\n | Const n1, Const n2 => Const (n1 * n2)\n | Const 1, _ => e2'\n | _, Const 1 => e1'\n | Const 0, _ => Const 0\n | _, Const 0 => Const 0\n | _, _ => Times e1' e2'\n end\n end.\n\n(*\n * PROBLEM 13 [0 points, ~15 tactics if taking advantage of `repeat match goal`,\n * many more tactics otherwise]\n *\n * Hint: You may want to copy some useful `repeat match goal` techniques from\n * the other FRAP proofs about constantFold.\n *)\nLemma kinda_sum_constantFold :\n forall e,\n kinda_sum (constantFold e) = kinda_sum e.\nProof.\n (* YOUR CODE HERE *)\nAdmitted. (* Change to Qed when done *)\n\nEnd ArithWithConstants.\n", "meta": {"author": "KartikeyaBh", "repo": "principles_of_programming_languages", "sha": "7070e90d127e4e9c3c7c69d899e42a5a51747c86", "save_path": "github-repos/coq/KartikeyaBh-principles_of_programming_languages", "path": "github-repos/coq/KartikeyaBh-principles_of_programming_languages/principles_of_programming_languages-7070e90d127e4e9c3c7c69d899e42a5a51747c86/HW1_and_reading1/HW1Part2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.9399133544545811, "lm_q1q2_score": 0.8686132458628635}} {"text": "\n(** ** Определение натуральных чисел *)\n\nModule NatNumbers.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat\n.\n\nCheck nat.\nCheck O.\nCheck S.\nCheck (S O).\nCheck (S (S O)).\n\nDefinition pred (n : nat) : nat :=\nmatch n with\n| O => O\n| S m => m\nend.\n\nCompute pred (S (S (S (S O)))).\n (* = S (S (S O))\n     : nat *)\nCompute pred O.\n\n\nEnd NatNumbers.\n\nCompute (S (S (S (S O)))).\nCompute pred (S (S (S (S O)))).\n (* = 4 \n : nat *)\n\nCheck pred (S (S (S (S O)))).\n (* ===> 4 : nat *)\n\nPrint NatNumbers.pred.\n\nDefinition minustwo (n : nat) : nat :=\nmatch n with\n| O => O\n| S O => O\n| S (S m) => m\nend.\n\nCheck minustwo.\n\nCompute (minustwo 5).\n (* ===> 2 : nat *)\n\n\nCheck S.\nCheck pred.\nCheck minustwo.\n\nFixpoint evenb (n : nat) : bool :=\nmatch n with\n| O \t=> true\n| S O \t=> false\n| S (S m) \t=> evenb m\nend.\n\nDefinition oddb (n : nat) : bool := negb (evenb n).\n\nExample test_oddb1 : \n oddb 1 = true.\nProof. \n reflexivity.\nQed.\nExample test_oddb2 :\n oddb 4 = false.\nProof.\n reflexivity.\nQed.\n\nModule NatNumbers2.\n\nFixpoint plus n m :=\nmatch n with\n| O => m\n| S k => S (plus k m)\nend.\n\nCompute (plus 3 2).\n\nFixpoint mult (n m : nat) : nat :=\nmatch n with\n| O => O\n| S k => plus m (mult k m)\nend.\n\nExample test_mult1 : \n (mult 3 3) = 9.\nProof.\n reflexivity.\nQed.\n\nFixpoint minus (n m : nat) : nat :=\nmatch n, m with\n| O , _ => O\n| S _ , O => n\n| S n', S m' => minus n' m'\nend.\n\nEnd NatNumbers2.\n\nFixpoint exp (n m : nat) : nat :=\nmatch m with\n| O => S O\n| S p => mult n (exp n p)\nend.\n\n\nFixpoint factorial (n : nat) : nat :=\n (* написать определени факторила *)\nmatch n with\n| O => S O\n| S p => mult n (factorial p)\nend.\n\n\n\nExample test_factorial1 :\n (factorial 3) = (plus 2 4).\nProof. \n reflexivity. \nQed.\n\nExample test_factorial2 :\n (factorial 5) = (mult 10 12).\nProof. \n reflexivity. \nQed.\n\nNotation \"x + y\" := (plus x y)\n (at level 50, left associativity)\n : nat_scope.\nNotation \"x - y\" := (minus x y)\n (at level 50, left associativity)\n : nat_scope.\nNotation \"x * y\" := (mult x y)\n (at level 40, left associativity)\n : nat_scope.\n\nCompute (2 + 3 * 4).\n\nCheck ((0 + 1) + 1).\n\n\nFixpoint beq_nat (n m : nat) : bool :=\n match n with\n | O \t => \tmatch m with\n\t\t\t\t | O => true\n \t\t | S m' => false\n \t\t end\n | S n'\t=>\tmatch m with\n \t| O => false\n \t| S m' => beq_nat n' m'\n \tend\n end.\n\nFixpoint leb (n m : nat) : bool :=\nmatch n with\n| O => true\n| S n' =>\tmatch m with\n \t\t | O => false\n \t\t| S m' => leb n' m'\n \t end\nend.\n\nExample test_leb1 :\n (leb 2 2) = true.\nProof.\n simpl.\n reflexivity. \nQed.\nExample test_leb2 :\n (leb 2 4) = true.\nProof. \n simpl.\n reflexivity.\nQed.\nExample test_leb3 :\n (leb 4 2) = false.\nProof.\n simpl.\n reflexivity. \nQed.\n\n(*\n\nDefinition blt_nat (n m : nat) : bool :=\n (* написать фуекцию не используя рекурсию *)\n\nExample test_blt_nat1 :\n (blt_nat 2 2) = false.\n (* проверить функцию *)\n\nExample test_blt_nat2 :\n (blt_nat 2 4) = true.\n (* проверить функцию *)\n\nExample test_blt_nat3 :\n (blt_nat 4 2) = false.\n (* проверить функцию *)\n*)\n\n(* ################################################################# *)\n(** Доказательство простых теорем о натуральных числах *)\n\nTheorem plus_O_n : \n forall n : nat, \n 0 + n = n.\nProof.\n intros n. \n simpl. \n reflexivity. \nQed.\n\nTheorem plus_1_l : \n forall n : nat, \n 1 + n = S n.\nProof.\n intros n. \n reflexivity. \nQed.\n\nTheorem mult_0_l : \n forall n:nat, \n 0 * n = 0.\nProof.\n intros n. \n reflexivity. \nQed.\n\nTheorem plus_id_example : \n forall n m : nat,\n n = m ->\n n + n = m + m.\nProof.\n intros * H.\n rewrite H.\n reflexivity. \nQed.\n\n\n(** Упраженение *)\n\nTheorem plus_id_exercise : \n forall n m o : nat,\n n = m -> \n m = o -> \n n + m = m + o.\nProof.\nintros *.\nintros H1 H2.\nrewrite H1.\nrewrite H2.\nreflexivity.\nQed.\n\n\nTheorem mult_0_plus : \n forall n m : nat,\n (0 + n) * m = n * m.\nProof.\nintros *.\nreflexivity.\nQed.\n\nTheorem mult_S_1 : \n forall n m : nat,\n m = S n ->\n m * (1 + n) = m * m.\nProof.\nintros *.\nintros H.\nrewrite H.\nreflexivity.\nQed.\n\n\nTheorem plus_1_neq_0_firsttry : \n forall n : nat,\n beq_nat (n + 1) 0 = false.\nProof.\n intros n.\n simpl.\nAbort.\n\nTheorem plus_1_neq_0 : \n forall n : nat,\n beq_nat (n + 1) 0 = false.\nProof.\n intros n. \n destruct n as [| m ].\n - reflexivity.\n - reflexivity.\nQed.\n\nTheorem negb_involutive : \n forall b : bool,\n negb (negb b) = b.\nProof.\n intros b.\n destruct b.\n - reflexivity.\n - reflexivity.\nQed.\n\n\nTheorem andb_commutative : \n forall b c, \n andb b c = andb c b.\nProof.\n intros b c. \n destruct b.\n - destruct c.\n + reflexivity.\n + reflexivity.\n - destruct c.\n + reflexivity.\n + reflexivity.\nQed.\n\nTheorem andb_commutative' : \n forall b c, \n andb b c = andb c b.\nProof.\n intros b c. \n destruct b.\n { destruct c.\n { reflexivity. }\n { reflexivity. } }\n { destruct c.\n { reflexivity. }\n { reflexivity. } }\nQed.\n\n\nTheorem andb3_exchange :\n forall b c d, \n andb (andb b c) d = andb (andb b d) c.\nProof.\n intros b c d. \n destruct b.\n - destruct c.\n { destruct d.\n - reflexivity.\n - reflexivity. }\n { destruct d.\n - reflexivity.\n - reflexivity. }\n - destruct c.\n { destruct d.\n - reflexivity.\n - reflexivity. }\n { destruct d.\n - reflexivity.\n - reflexivity. }\nQed.\n\nTheorem plus_1_neq_0' : \n forall n : nat,\n beq_nat (n + 1) 0 = false.\nProof.\n intros [| n ].\n - reflexivity.\n - reflexivity. \nQed.\n\nTheorem andb_commutative'' :\n forall b c, \n andb b c = andb c b.\nProof.\n intros [] [].\n - reflexivity.\n - reflexivity.\n - reflexivity.\n - reflexivity.\nQed.\n\n(** Упражнение *)\n\nTheorem andb_true_elim2 : \n forall b c : bool,\n andb b c = true -> \n c = true.\nProof.\nintros [] [] H; rewrite <- H; reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1 : \n forall n : nat,\n beq_nat 0 (n + 1) = false.\nProof.\n intros n. \n destruct n as [| m ].\n - reflexivity.\n - reflexivity.\nQed.\n\n(* пример неудачной функции *)\n\n(*\nFixpoint plusx (n m : nat) : nat :=\n match n with\n | O => m\n | S p => S (plusx (pred n) m)\n end.\n*)\n\n(** Упражнения *)\n\nTheorem identity_fn_applied_twice :\n forall (f : bool -> bool),\n (forall (x : bool), f x = x) ->\n forall (b : bool), f (f b) = b.\nProof.\n intros * H b.\n repeat rewrite (H b). \n reflexivity.\nQed.\n\nTheorem negation_fn_applied_twice :\n forall (f : bool -> bool),\n (forall (x : bool), f x = negb x) ->\n forall (b : bool), f (f b) = b.\nProof.\n intros * H1 b.\n rewrite (H1 b).\n rewrite (H1 (negb b)).\n case b; reflexivity.\n (* построить доказательство *)\nQed.\nTheorem andb_eq_orb :\n forall (b c : bool),\n (andb b c = orb b c) ->\n b = c.\nProof.\n intros * H.\n case b, c; simpl in H;try reflexivity; rewrite H; reflexivity.\n\n (* построить доказательство *)\nQed.", "meta": {"author": "Buratinox", "repo": "CoqBook", "sha": "39047256c43afa4b491f4a0408e03ed7e78d1806", "save_path": "github-repos/coq/Buratinox-CoqBook", "path": "github-repos/coq/Buratinox-CoqBook/CoqBook-39047256c43afa4b491f4a0408e03ed7e78d1806/02_nat_definition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701655, "lm_q2_score": 0.9273632861110772, "lm_q1q2_score": 0.8682763380182956}} {"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\n\nModule NatList.\n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as in this definition: *)\n\nInductive natprod : Type :=\n pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\n(** We can construct an element of [natprod] like this: *)\n\nCheck (pair 3 5).\n\n(** *** *)\n\n(** Here are two simple function definitions for extracting the\n first and second components of a pair. (The definitions also\n illustrate how to do pattern matching on two-argument\n constructors.) *)\n\nDefinition fst (p : natprod) : nat :=\n match p with\n | pair x y => x\n end.\nDefinition snd (p : natprod) : nat :=\n match p with\n | pair x y => y\n end.\n\nEval compute in (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** *** *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this notation is provided as part of the standard\n library): *)\n\nEval compute in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n match p with\n | (x,y) => x\n end.\nDefinition snd' (p : natprod) : nat :=\n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n match p with\n | (x,y) => (y,x)\n end.\n\n(** *** *)\n\n(** Let's try and prove a few simple facts about pairs. If we\n state the lemmas in a particular (and slightly peculiar) way, we\n can prove them with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** Note that [reflexivity] is not enough if we state the lemma in a\n more natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** *** *)\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct].\n\n Notice that, unlike for [nat]s, [destruct] doesn't generate an\n extra subgoal here. That's because [natprod]s can only be\n constructed in one way. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p. destruct p as [n m]. reflexivity. Qed.\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros p. destruct p as [n m]. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n describe the type of _lists_ of numbers like this: \"A list is\n either the empty list or else a pair of a number and another\n list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n\n(** *** *)\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following two declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n but in case you are interested, here is roughly what's going on.\n\n The [right associativity] annotation tells Coq how to parenthesize\n expressions involving several uses of [::] so that, for example,\n the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\nNotation \"x + y\" := (plus x y)\n (at level 50, left associativity).\n The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (By the way, it's worth noting in passing that expressions like \"[1\n + 2 :: [3]]\" can be a little confusing when you read them in a .v\n file. The inner brackets, around 3, indicate a list, but the outer\n brackets, which are invisible in the HTML rendering, are there to\n instruct the \"coqdoc\" tool that the bracketed part should be\n displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(** *** Repeat *)\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(** *** Length *)\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(** *** Append *)\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\").\n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\n(** *** Head (with default) and Tail *)\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => match h with\n | 0 => nonzeros t\n | n => n :: nonzeros t\n end\n end.\n\n\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => match (oddb h) with\n | true => h :: oddmembers t\n | false => oddmembers t\n end\n end.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\n reflexivity. Qed.\n\nDefinition countoddmembers (l:natlist) : nat :=\n length (oddmembers l).\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\n reflexivity. Qed.\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\n reflexivity. Qed.\nExample test_countoddmembers3: countoddmembers nil = 0.\n reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\nFixpoint alternate (l1 : natlist) := fix alternate_r (l2 : natlist) :=\n match l1, l2 with\n | nil, nil => nil\n | nil, h2 :: t2 => h2 :: alternate_r t2 (* l1 does not reduce in this case, use inner fixpoint *)\n | h1 :: t1, nil => h1 :: alternate t1 l2\n | h1 :: t1, h2 :: t2 => h1 :: h2 :: alternate t1 t2\n end.\n\nExample test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n reflexivity. Qed.\nExample test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].\n reflexivity. Qed.\nExample test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].\n reflexivity. Qed.\nExample test_alternate4: alternate [] [20;30] = [20;30].\n reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n multiple times instead of just once. One reasonable\n implementation of bags is to represent a bag of numbers as a\n list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat :=\n match s with\n | nil => 0\n | n :: t => match (beq_nat n v) with\n | true => S (count v t)\n | false => count v t\n end\n end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\n reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\n reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\n reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := cons v s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\n reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\n reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool := negb (beq_nat 0 (count v s)).\n\nExample test_member1: member 1 [1;4;1] = true.\n reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\n reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n (* When remove_one is applied to a bag without the number to remove,\n it should return the same bag unchanged. *)\n match s with\n | nil => nil\n | n :: t => match (beq_nat n v) with\n | true => t\n | false => n :: (remove_one v t)\n end\n end.\n\nExample test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n reflexivity. Qed.\nExample test_remove_one2: count 5 (remove_one 5 [2;1;4;1]) = 0.\n reflexivity. Qed.\nExample test_remove_one3: count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n reflexivity. Qed.\nExample test_remove_one4: count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | n :: t => if (beq_nat n v) then remove_all v t\n else n :: (remove_all v t)\n end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\n reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n match s1 with\n | nil => true\n | v :: t1 => if (member v s2) then subset t1 (remove_one v s2)\n else false\n end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\n reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\n reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (bag_theorem) *)\n(** Write down an interesting theorem about bags involving the\n functions [count] and [add], and prove it. Note that, since this\n problem is somewhat open-ended, it's possible that you may come up\n with a theorem which is true, but whose proof requires techniques\n you haven't learned yet. Feel free to ask for help if you get\n stuck! *)\n\nTheorem list_add_length_increases:\n forall (l : natlist) (v : nat),\n S (length l) = length (add v l).\nProof.\n reflexivity.\nQed.\n\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match position\n in the definition of [app], allowing the match itself to be\n simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n l'\".\n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proofs will not get you very far! It is\n very important to work through the details of each one, using Coq\n and thinking about what each step of the proof achieves.\n Otherwise it is more or less guaranteed that the exercises will\n make no sense. *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n perhaps a little less familiar than standard natural number\n induction, but the basic idea is equally simple. Each [Inductive]\n declaration defines a set of data values that can be built up from\n the declared constructors: a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to a number; a\n list can be either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two things together establish the\n truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n intros l1 l2 l3. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons n l1'\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n static written document -- it is easy to see what's going on if\n you are reading the proof in an interactive Coq session and you\n can see the current goal and context at each point, but this state\n is not visible in the written-down parts of the Coq proof. So a\n natural-language proof -- one written for human readers -- will\n need to include more explicit signposts; in particular, it will\n help the reader stay oriented if we remind them exactly what the\n induction hypothesis is in the second case. *)\n\n(** *** Informal version *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n (the induction hypothesis). We must show\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]]\n By the definition of [++], this follows from\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n which is immediate from the induction hypothesis. []\n*)\n\n(** *** Another example *)\n(**\n Here is a similar example to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist,\n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n\n(** *** Reversing a list *)\n(** For a slightly more involved example of an inductive proof\n over lists, suppose we define a \"cons on the right\" function\n [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist :=\n match l with\n | nil => [v]\n | h :: t => h :: (snoc t v)\n end.\n\n(** ... and use it to define a list-reversing function [rev]\n like this: *)\n\nFixpoint rev (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => snoc (rev t) h\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** *** Proofs about reverse *)\n(** Now let's prove some more list theorems using our newly\n defined [snoc] and [rev]. For something a little more challenging\n than the inductive proofs we've seen so far, let's prove that\n reversing a list does not change its length. Our first attempt at\n this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n :: l'\".\n (* This is the tricky case. Let's begin as usual\n by simplifying. *)\n simpl.\n (* Now we seem to be stuck: the goal is an equality\n involving [snoc], but we don't have any equations\n in either the immediate context or the global\n environment that have anything to do with [snoc]!\n\n We can make a little progress by using the IH to\n rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation about [snoc] that would have\n enabled us to make progress and prove it as a separate lemma.\n*)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n length (snoc l n) = S (length l).\nProof.\n intros n l. induction l as [| n' l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n' l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed.\n\n(**\n Note that we make the lemma as _general_ as possible: in particular,\n we quantify over _all_ [natlist]s, not just those that result\n from an application of [rev]. This should seem natural,\n because the truth of the goal clearly doesn't depend on\n the list having been reversed. Moreover, it is much easier\n to prove the more general property.\n*)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons\".\n simpl. rewrite -> length_snoc.\n rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n _Theorem_: For all numbers [n] and lists [l],\n [length (snoc l n) = S (length l)].\n\n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (snoc [] n) = S (length []),\n which follows directly from the definitions of\n [length] and [snoc].\n\n - Next, suppose [l = n'::l'], with\n length (snoc l' n) = S (length l').\n We must show\n length (snoc (n' :: l') n) = S (length (n' :: l')).\n By the definitions of [length] and [snoc], this\n follows from\n S (length (snoc l' n)) = S (S (length l')),\n]]\n which is immediate from the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (rev []) = length [],\n which follows directly from the definitions of [length]\n and [rev].\n\n - Next, suppose [l = n::l'], with\n length (rev l') = length l'.\n We must show\n length (rev (n :: l')) = length (n :: l').\n By the definition of [rev], this follows from\n length (snoc (rev l') n) = S (length l')\n which, by the previous lemma, is the same as\n S (length (rev l')) = S (length l').\n This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n and pedantic. After the first few, we might find it easier to\n follow proofs that give fewer details (since we can easily work\n them out in our own minds or on scratch paper if necessary) and\n just highlight the non-obvious steps. In this more compressed\n style, the above proof might look more like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that\n length (snoc l n) = S (length l)\n for any [l]. This follows by a straightforward induction on [l].\n The main property now follows by another straightforward\n induction on [l], using the observation together with the\n induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and on how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for\n present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, using [rewrite], and later we will see other ways\n of reusing previous theorems. But in order to refer to a theorem,\n we need to know its name, and remembering the names of all the\n theorems we might ever want to use can become quite difficult! It\n is often hard even to remember what theorems have been proven,\n much less what they are named.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following to\n see a list of theorems that we have proved about [rev]: *)\n\n(* SearchAbout rev. *)\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the course; it can save you a lot of time! *)\n\n(** Also, if you are using ProofGeneral, you can run [SearchAbout]\n with [C-c C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist,\n l ++ [] = l.\nProof.\n intros l. induction l as [|v l'].\n Case \"l = []\". reflexivity.\n Case \"l = v :: l'\". simpl. rewrite IHl'. reflexivity.\nQed.\n\nTheorem rev_snoc : forall n : nat, forall l : natlist,\n rev (snoc l n) = n :: rev l.\nProof.\n intros n l. induction l as [|h l'].\n Case \"l = []\". reflexivity.\n Case \"l = h::l'\". simpl. rewrite IHl'. reflexivity.\nQed.\n\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n induction l as [|v l'].\n Case \"l = []\". reflexivity.\n Case \"l = v::l'\". simpl. rewrite rev_snoc. rewrite IHl'. reflexivity.\nQed.\n\n(** There is a short solution to the next exercise. If you find\n yourself getting tangled up, step back and try to look for a\n simpler way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros l1 l2 l3 l4. rewrite app_assoc. rewrite app_assoc. reflexivity.\nQed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n snoc l n = l ++ [n].\nProof.\n intros l n. induction l as [|v l'].\n Case \"l = []\". reflexivity.\n Case \"l = v::l'\". simpl. rewrite IHl'. reflexivity.\nQed.\n\nTheorem distr_rev : forall l1 l2 : natlist,\n rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n intros l1 l2. induction l1 as [|v l'].\n Case \"l1 = []\". simpl. rewrite app_nil_end. reflexivity.\n Case \"l1 = v::l'\". simpl. rewrite IHl'. rewrite snoc_append. rewrite snoc_append. rewrite app_assoc. reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros l1 l2. induction l1 as [|v l'].\n Case \"l1 = []\". reflexivity.\n Case \"l1 = v::l'\". induction v as [|v'].\n SCase \"v = 0\". simpl. rewrite IHl'. reflexivity.\n SCase \"v = S v'\". simpl. rewrite IHl'. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n match l1, l2 with\n | nil, nil => true\n | h1 :: t1, h2 :: t2 => if (beq_nat h1 h2) then (beq_natlist t1 t2) else false\n | _, _ => false\n end.\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\n reflexivity. Qed.\nExample test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\n reflexivity. Qed.\nExample test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.\n reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\n intros l. induction l as [|v l'].\n Case \"l = []\". reflexivity.\n Case \"l = v::l'\". simpl. rewrite <- beq_nat_refl. rewrite IHl'. reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 2 stars (list_design) *)\n(** Design exercise:\n - Write down a non-trivial theorem involving [cons]\n ([::]), [snoc], and [app] ([++]).\n - Prove it. *)\n\nTheorem app_cons_snoc_sandwiched : forall (l1 l2 : natlist) (v : nat),\n l1 ++ (v :: l2) = (snoc l1 v) ++ l2.\nProof.\n intros l1 l2 v. induction l1 as [|v1 t1].\n Case \"l1 = []\". simpl. reflexivity.\n Case \"l1 = v1::t1\". simpl. rewrite IHt1. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n definitions about bags earlier in the file. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n intros s. simpl. reflexivity.\nQed.\n\n(** The following lemma about [ble_nat] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n ble_nat n (S n) = true.\nProof.\n intros n. induction n as [| n'].\n Case \"0\".\n simpl. reflexivity.\n Case \"S n'\".\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n induction s as [|v s'].\n Case \"s = []\". simpl. reflexivity.\n Case \"s = v::s'\". destruct v as [|v'].\n SCase \"v = 0\". simpl. rewrite ble_n_Sn. reflexivity.\n SCase \"v = S n'\". simpl. rewrite IHs'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *)\n(** Write down an interesting theorem about bags involving the\n functions [count] and [sum], and prove it.*)\nTheorem sum_maintains_count : forall (s1 s2 : bag) (n : nat),\n count n (sum s1 s2) = count n s1 + count n s2.\nProof.\n intros s1 s2 n. induction s1 as [|v s'].\n Case \"s = []\". simpl. reflexivity.\n Case \"s = v::s'\". simpl. destruct (beq_nat v n).\n SCase \"true\". simpl. rewrite IHs'. reflexivity.\n SCase \"false\". rewrite IHs'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nThere is a hard way and an easy way to solve this exercise.\n*)\nTheorem rev_injective : forall (l1 l2 : natlist),\n rev l1 = rev l2 -> l1 = l2.\nProof.\n intros l1 l2 H. rewrite <- rev_involutive. rewrite <- H. rewrite rev_involutive. reflexivity.\nQed.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n(** One use of [natoption] is as a way of returning \"error\n codes\" from functions. For example, suppose we want to write a\n function that returns the [n]th element of some list. If we give\n it type [nat -> natlist -> nat], then we'll have to return some\n number when the list is too short! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with\n | true => a\n | false => index_bad (pred n) l'\n end\n end.\n\n(** *** *)\n(** On the other hand, if we give it type [nat -> natlist ->\n natoption], then we can return [None] when the list is too short\n and [Some a] when the list has enough members and [a] appears at\n position [n]. *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption.\n\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None\n | a :: l' => match beq_nat n O with\n | true => Some a\n | false => index (pred n) l'\n end\n end.\n\nExample test_index1 : index 0 [4;5;6;7] = Some 4.\nProof. reflexivity. Qed.\nExample test_index2 : index 3 [4;5;6;7] = Some 7.\nProof. reflexivity. Qed.\nExample test_index3 : index 10 [4;5;6;7] = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n small feature of Coq's programming language: conditional\n expressions... *)\n\n(** *** *)\n\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None\n | a :: l' => if beq_nat n O then Some a else index' (pred n) l'\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_opt (l : natlist) : natoption :=\n match l with\n | nil => None\n | h :: t => Some h\n end.\n\nExample test_hd_opt1 : hd_opt [] = None.\n reflexivity. Qed.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\n reflexivity. Qed.\n\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\n reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_opt l).\nProof.\n intros l default. destruct l as [|v l'].\n Case \"l = []\". simpl. reflexivity.\n Case \"l = v::l'\". reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Dictionaries *)\n\n(** As a final illustration of how fundamental data structures\n can be defined in Coq, here is the declaration of a simple\n [dictionary] data type, using numbers for both the keys and the\n values stored under these keys. (That is, a dictionary represents\n a finite map from numbers to numbers.) *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n | empty : dictionary\n | record : nat -> nat -> dictionary -> dictionary.\n\n(** This declaration can be read: \"There are two ways to construct a\n [dictionary]: either using the constructor [empty] to represent an\n empty dictionary, or by applying the constructor [record] to\n a key, a value, and an existing [dictionary] to construct a\n [dictionary] with an additional key to value mapping.\" *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n (record key value d).\n\n(** Here is a function [find] that searches a [dictionary] for a\n given key. It evaluates evaluates to [None] if the key was not\n found and [Some val] if the key was mapped to [val] in the\n dictionary. If the same key is mapped to multiple values, [find]\n will return the first one it finds. *)\n\nFixpoint find (key : nat) (d : dictionary) : natoption :=\n match d with\n | empty => None\n | record k v d' => if (beq_nat key k)\n then (Some v)\n else (find key d')\n end.\n\n\n\n(** **** Exercise: 1 star (dictionary_invariant1) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n (find k (insert k v d)) = Some v.\nProof.\n intros d k v. simpl. rewrite <- beq_nat_refl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),\n beq_nat m n = false -> find m d = find m (insert n o d).\nProof.\n intros d m n o H. simpl. rewrite H. reflexivity.\nQed.\n(** [] *)\n\nEnd Dictionary.\n\nEnd NatList.\n\n(* $Date: 2014-01-28 13:19:45 -0500 (Tue, 28 Jan 2014) $ *)\n", "meta": {"author": "IgnoredAmbience", "repo": "software-foundations", "sha": "e1e75f8bdfd83979b13f5ce7574659c7925a6cf6", "save_path": "github-repos/coq/IgnoredAmbience-software-foundations", "path": "github-repos/coq/IgnoredAmbience-software-foundations/software-foundations-e1e75f8bdfd83979b13f5ce7574659c7925a6cf6/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240160063031, "lm_q2_score": 0.9252299550303293, "lm_q1q2_score": 0.8679804411423838}} {"text": "Require Import Coq.Arith.Arith.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\n(* A monoid is a type equipped with an append operation and an empty element\nthat \"does nothing\" with respect to the append operation. It turns out that\nmonoids are a very useful and general abstract data type.\n\nIn Coq, we can add \"proof obligations\" to this datatype, that show that an\ninstance of monoid behaves the right way. In particular, we want the empty\nvalue to behave like unit, and append must be associative. *)\nRecord Monoid (A : Type) := {\n\n (* Empty element is an instance of A. *)\n empty : A;\n\n (* The append binary operation. *)\n append : A -> A -> A;\n\n (* The proof obligations (i.e., a formal specification). *)\n left_identity : forall m, append empty m = m;\n right_identity : forall m, append m empty = m;\n assoc : forall m n o, append m (append n o) = append (append m n) o;\n}.\n\n(* Natural numbers form a monoid under addition, with 0 as empty element. *)\nProgram Definition NatAddMonoid : Monoid nat := {|\n empty := 0;\n append := plus;\n|}.\n\n(* Coq can prove left_identity (that is, forall n, 0 + n = n) and\nright_identity (forall n, n + 0 = n) automatically, but it fails on assoc so\nwe need to help. To satisify this obligation we have to prove that\nforall m n o, m + (n + o) = (m + n) + o.*)\nNext Obligation. apply Nat.add_assoc. Qed.\n\n(* Natural numbers also form a monoid under multiplication, with 1 as the\nempty element. *)\nProgram Definition NatMultMonoid : Monoid nat := {|\n empty := 1;\n append := mult;\n|}.\nNext Obligation. apply Nat.mul_1_r. Qed.\nNext Obligation. apply Nat.mul_assoc. Qed.\n\n(* Next we define a (very simple) algorithm on monoids. The key idea is that\nreduce will work for *any* monoid, without knowing anything beyond the\nabstract Monoid specification.\n\nMoreover, in Coq we can use our monoid facts (identity and assoc) to *prove*\nreduce will behave as per a specification without knowing anything else about\nany particular monoid.\n\nIt's like saying, \"give me a monoid, and I will give you a reduce operation on\nthat monoid. And if you can prove your monoid really does behave like a\nmonoid, then I will prove that reduce will behave like reduce ought to.\"\n*)\nSection Reduce.\n Variable A : Type.\n Variable m : Monoid A.\n (* It might help to think of m as *evidence* that A implements Monoid. *)\n\n Fixpoint reduce (xs : list A) : A :=\n match xs with\n | [] => empty _ m\n | x::xs' => append _ m x (reduce xs')\n end.\n\n Theorem reduce_one :\n forall x, reduce [x] = x.\n Proof.\n intros x.\n simpl.\n apply (right_identity _ m).\n Qed.\n\n Theorem reduce_app :\n forall l1 l2,\n reduce (l1 ++ l2) = append _ m (reduce l1) (reduce l2).\n Proof.\n intros l1 l2.\n induction l1; simpl.\n - symmetry.\n apply (left_identity _ m).\n - rewrite IHl1.\n apply (assoc _ m).\n Qed.\nEnd Reduce.\n\n(* Using the abstract idea of reduce, along with our concrete monoid instance\nof natural numbers under addition, it is very easy to define summation... *)\nDefinition sum : list nat -> nat := reduce _ NatAddMonoid.\nCompute (sum [1;2;3;4;5]).\n\n(* ... and to prove useful, concrete things about how it behaves. *)\nTheorem sum_app :\n forall ns ms, sum (ns ++ ms) = sum ns + sum ms.\nProof.\n (* This is just an instance of our reduce_app proof from above. *)\n exact (reduce_app _ NatAddMonoid).\nQed.\n\n(* Same idea but for product. *)\nDefinition product : list nat -> nat := reduce _ NatMultMonoid.\nCompute (product [1;2;3;4;5]).\n\nTheorem product_app :\n forall ns ms, product (ns ++ ms) = product ns * product ms.\nProof.\n exact (reduce_app _ NatMultMonoid).\nQed.\n\n\n(* One more example. Lists of elements drawn from some arbitrary type form a\nmonoid under concatenation. This definition has to be parametric in the list\nelement type. We are effectively defining a *family* of monoids here -- for\nevery type A, the type list A is a monoid. *)\nProgram Definition ListMonoid (A : Type) : Monoid (list A) := {|\n empty := [];\n append := @app A;\n|}.\n\nNext Obligation. apply app_nil_r. Qed.\nNext Obligation. apply app_assoc. Qed.\n\n(* Flatten takes a list of lists and combines them all into one list. *)\nDefinition flatten {A : Type} : list (list A) -> list A :=\n reduce _ (ListMonoid _).\n\nCompute (flatten [[1;2;3]; [4;5]; []; [6;7;8;9;10]]).\n\n\n(* Exercise: come up with a monoid instance for bool (as with nat, which we\nsaw had instances for both add and mult, for bool there's more than one\npossible instance). What would be a good function name for reduce on your\ninstance? *)\n\n(** FILL IN HERE\nProgram Definition BoolMonoid : Monoid bool := {|\n empty := *a boolean value* ;\n append := *a binary operation on bool* ;\n|}.\n\nNext Obligation. ****\n\nDefinition **** : list bool -> bool := reduce _ BoolMonoid.\n*)\n", "meta": {"author": "ghulette", "repo": "coq-abstract-datatypes", "sha": "58bdbc6a01530402803bdc74a617d00d39df7dfc", "save_path": "github-repos/coq/ghulette-coq-abstract-datatypes", "path": "github-repos/coq/ghulette-coq-abstract-datatypes/coq-abstract-datatypes-58bdbc6a01530402803bdc74a617d00d39df7dfc/Monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.9207896824119662, "lm_q1q2_score": 0.8678504674585439}} {"text": "Require Import Arith List Bool.\n\n(* EXAMPLES *) \n\n(* The following function takes two arguments a and b\nwhich are numbers of type nat and returns b + 2 * (a + b) *)\nDefinition f_ex (a b : nat) := b + 2 * (a + b).\n\n(* When p is a pair, you can access its components by the \"pattern-matching\"\n construct illustrated in the following function. *)\n\nDefinition add_pair_components (p : nat * nat) :=\n match p with (a, b) => a + b end.\n\n(* f_ex is a function with two arguments. add_pair_components is a\n function with one argument, which is a pair. *)\n\n(* END OF EXAMPLES *)\n\n(* 1/ Define a function that takes two numbers as arguments and returns\n the sum of the squares of these numbers. *)\n\nDefinition f1_1 (x y : nat) : nat := x * x + y * y.\n\n(* 2/ Define a function that takes 5 arguments a b c d e, which are all\n numbers and returns the sum of all these numbers. *)\n\nDefinition f1_2 (a b c d e : nat) := a + b + c + d + e.\n\n(* 3/ Define a function named add5 that takes a number as argument and returns\n this number plus 5. *)\n\nDefinition add5 (x : nat) := x + 5.\n\n(* The following should return 8 *)\nCompute add5 3.\n\n(* The following commands make it possible to find pre-defined functions *)\n\n\n(* 4/ Write a function swap of type list nat -> list nat such that\n swap (a::b::l) = (b::a::l) and\n swap l' = l' if l' has less than 2 elements. *)\n\nDefinition swap (l : list nat) : list nat :=\n match l with\n a::b::l => b::a::l\n | _ => l\n end.\n\n(* 5/ Write a function proc2 of type list nat -> nat, such that\n proc2 (a::b::l) = (b + 3) and\n proc2 l' = 0 if l' has less than 2 elements.\n\n In other words, proc2 only processes the 2nd argument of the list and\n returns that number plus 3. If there is no second argument to the list,\n proc2 returns 0. *)\n\nDefinition proc2 (l : list nat) : nat :=\n match l with\n a::b::l => b + 3\n | _ => 0\n end.\n\n(* 6/ Write a function ms of type list nat -> list nat such that\n ms (a::b::...::nil) = a+2::b+2::...::nil\n For instance\n ms (2::3::5::nil) = (4::5::7::nil) *) \n\nFixpoint ms (l : list nat) : list nat :=\n match l with\n a::l' => a + 2 :: ms l'\n | nil => nil\n end.\n\n(* 7/ Write a function sorted of type list nat -> bool, such that\n sorted l = true exactly when the natural numbers in\n l are in increasing order. *)\nLocate leb.\nFixpoint sorted (l : list nat) : bool :=\n match l with\n a::l' =>\n match l' with b::_ =>\n if Nat.leb a b then sorted l' else false | _ => true end\n | nil => true\n end.\n\n(* 8/ Write a function p2 of type nat -> nat such that \n p2 n = 2 ^ n *)\n\nFixpoint p2 (n : nat) :=\n match n with 0 => 1 | S p => 2 * p2 p end.\n\n(* 9/ Write a function salt of type nat -> nat -> nat such that\n salt x n = x ^ n - x^ (n-1) + x^(n-2) .... + 1 or -1, if x <> 0,\n depending on the parity of n, thus\n salt x 3 = x^3 - x^2 + x - 1\n salt x 4 = x^4 - x^3 + x^2 - x + 1\n salt 2 3 = 5\n\n You may have to define auxiliary functions. *)\n\nFixpoint even n :=\n match n with 0 => true | 1 => false | S (S p) => even p end.\n\nFixpoint salt (x n : nat) :=\n match n with\n 0 => 1\n | S p => if even n then x * salt x p + 1 else x * salt x p - 1\n end.\n\n\n\nFixpoint pow x n :=\n match n with 0 => 1 | S p => x * pow x p end.\n\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch2_types_expressions/SRC/sol1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833653, "lm_q2_score": 0.9111797148356994, "lm_q1q2_score": 0.8673184654565328}} {"text": "Inductive nat : Set :=\n | O : nat\n | S : nat->nat.\nCheck nat.\nCheck O.\nCheck S.\n\nReset nat.\nPrint nat.\n\n\nPrint le.\n\nTheorem zero_leq_three: 0 <= 3.\n\nProof.\n constructor 2.\n constructor 2.\n constructor 2.\n constructor 1.\n\nQed.\n\nPrint zero_leq_three.\n\n\nLemma zero_leq_three': 0 <= 3.\n repeat constructor.\nQed.\n\n\nLemma zero_lt_three : 0 < 3.\nProof.\n unfold lt.\n repeat constructor.\nQed.\n\n\nRequire Import List.\n\nPrint list.\n\nCheck list.\n\nCheck (nil (A:=nat)).\n\nCheck (nil (A:= nat -> nat)).\n\nCheck (fun A: Set => (cons (A:=A))).\n\nCheck (cons 3 (cons 2 nil)).\n\n\n\n\nRequire Import Bvector.\n\nPrint vector.\n\nCheck (Vnil nat).\n\nCheck (fun (A:Set)(a:A)=> Vcons _ a _ (Vnil _)).\n\nCheck (Vcons _ 5 _ (Vcons _ 3 _ (Vnil _))).\n\n\n\n\n\n\n\n\n\n\n\n\n\nLemma eq_3_3 : 2 + 1 = 3.\nProof.\n reflexivity.\nQed.\nPrint eq_3_3.\n\nLemma eq_proof_proof : refl_equal (2*6) = refl_equal (3*4).\nProof.\n reflexivity.\nQed.\nPrint eq_proof_proof.\n\nLemma eq_lt_le : ( 2 < 4) = (3 <= 4).\nProof.\n reflexivity.\nQed.\n\nLemma eq_nat_nat : nat = nat.\nProof.\n reflexivity.\nQed.\n\nLemma eq_Set_Set : Set = Set.\nProof.\n reflexivity.\nQed.\n\nLemma eq_Type_Type : Type = Type.\nProof.\n reflexivity.\nQed.\n\n\nCheck (2 + 1 = 3).\n\n\nCheck (Type = Type).\n\nGoal Type = Type.\nreflexivity.\nQed.\n\n\nPrint or.\n\nPrint and.\n\n\nPrint sumbool.\n\nPrint ex.\n\nRequire Import ZArith.\nRequire Import Compare_dec.\n\nCheck le_lt_dec.\n\nDefinition max (n p :nat) := match le_lt_dec n p with\n | left _ => p\n | right _ => n\n end.\n\nTheorem le_max : forall n p, n <= p -> max n p = p.\nProof.\n intros n p ; unfold max ; case (le_lt_dec n p); simpl.\n trivial.\n intros; absurd (p < p); eauto with arith.\nQed.\n\nExtraction max.\n\n\n\n\n\n\nInductive tree(A:Set) : Set :=\n node : A -> forest A -> tree A\nwith\n forest (A: Set) : Set :=\n nochild : forest A |\n addchild : tree A -> forest A -> forest A.\n\n\n\n\n\nInductive\n even : nat->Prop :=\n evenO : even O |\n evenS : forall n, odd n -> even (S n)\nwith\n odd : nat->Prop :=\n oddS : forall n, even n -> odd (S n).\n\nLemma odd_49 : odd (7 * 7).\n simpl; repeat constructor.\nQed.\n\n\n\nDefinition nat_case :=\n fun (Q : Type)(g0 : Q)(g1 : nat -> Q)(n:nat) =>\n match n return Q with\n | 0 => g0\n | S p => g1 p\n end.\n\nEval simpl in (nat_case nat 0 (fun p => p) 34).\n\nEval simpl in (fun g0 g1 => nat_case nat g0 g1 34).\n\nEval simpl in (fun g0 g1 => nat_case nat g0 g1 0).\n\n\nDefinition pred (n:nat) := match n with O => O | S m => m end.\n\nEval simpl in pred 56.\n\nEval simpl in pred 0.\n\nEval simpl in fun p => pred (S p).\n\n\nDefinition xorb (b1 b2:bool) :=\nmatch b1, b2 with\n | false, true => true\n | true, false => true\n | _ , _ => false\nend.\n\n\n Definition pred_spec (n:nat) := {m:nat | n=0 /\\ m=0 \\/ n = S m}.\n\n\n Definition predecessor : forall n:nat, pred_spec n.\n intro n;case n.\n unfold pred_spec;exists 0;auto.\n unfold pred_spec; intro n0;exists n0; auto.\n Defined.\n\nPrint predecessor.\n\nExtraction predecessor.\n\nTheorem nat_expand :\n forall n:nat, n = match n with 0 => 0 | S p => S p end.\n intro n;case n;simpl;auto.\nQed.\n\nCheck (fun p:False => match p return 2=3 with end).\n\nTheorem fromFalse : False -> 0=1.\n intro absurd.\n contradiction.\nQed.\n\nSection equality_elimination.\n Variables (A: Type)\n (a b : A)\n (p : a = b)\n (Q : A -> Type).\n Check (fun H : Q a =>\n match p in (eq _ y) return Q y with\n refl_equal => H\n end).\n\nEnd equality_elimination.\n\n\nTheorem trans : forall n m p:nat, n=m -> m=p -> n=p.\nProof.\n intros n m p eqnm.\n case eqnm.\n trivial.\nQed.\n\nLemma Rw : forall x y: nat, y = y * x -> y * x * x = y.\n intros x y e; do 2 rewrite <- e.\n reflexivity.\nQed.\n\n\nRequire Import Arith.\n\nCheck mult_1_l.\n(*\nmult_1_l\n : forall n : nat, 1 * n = n\n*)\n\nCheck mult_plus_distr_r.\n(*\nmult_plus_distr_r\n : forall n m p : nat, (n + m) * p = n * p + m * p\n\n*)\n\nLemma mult_distr_S : forall n p : nat, n * p + p = (S n)* p.\n simpl;auto with arith.\nQed.\n\nLemma four_n : forall n:nat, n+n+n+n = 4*n.\n intro n;rewrite <- (mult_1_l n).\n\n Undo.\n intro n; pattern n at 1.\n\n\n rewrite <- mult_1_l.\n repeat rewrite mult_distr_S.\n trivial.\nQed.\n\n\nSection Le_case_analysis.\n Variables (n p : nat)\n (H : n <= p)\n (Q : nat -> Prop)\n (H0 : Q n)\n (HS : forall m, n <= m -> Q (S m)).\n Check (\n match H in (_ <= q) return (Q q) with\n | le_n => H0\n | le_S m Hm => HS m Hm\n end\n ).\n\n\nEnd Le_case_analysis.\n\n\nLemma predecessor_of_positive : forall n, 1 <= n -> exists p:nat, n = S p.\nProof.\n intros n H; case H.\n exists 0; trivial.\n intros m Hm; exists m;trivial.\nQed.\n\nDefinition Vtail_total\n (A : Set) (n : nat) (v : vector A n) : vector A (pred n):=\nmatch v in (vector _ n0) return (vector A (pred n0)) with\n| Vnil => Vnil A\n| Vcons _ n0 v0 => v0\nend.\n\nDefinition Vtail' (A:Set)(n:nat)(v:vector A n) : vector A (pred n).\n case v.\n simpl.\n exact (Vnil A).\n simpl.\n auto.\nDefined.\n\n(*\nInductive Lambda : Set :=\n lambda : (Lambda -> False) -> Lambda.\n\n\nError: Non strictly positive occurrence of \"Lambda\" in\n \"(Lambda -> False) -> Lambda\"\n\n*)\n\nSection Paradox.\n Variable Lambda : Set.\n Variable lambda : (Lambda -> False) ->Lambda.\n\n Variable matchL : Lambda -> forall Q:Prop, ((Lambda ->False) -> Q) -> Q.\n (*\n understand matchL Q l (fun h : Lambda -> False => t)\n\n as match l return Q with lambda h => t end\n *)\n\n Definition application (f x: Lambda) :False :=\n matchL f False (fun h => h x).\n\n Definition Delta : Lambda := lambda (fun x : Lambda => application x x).\n\n Definition loop : False := application Delta Delta.\n\n Theorem two_is_three : 2 = 3.\n Proof.\n elim loop.\n Qed.\n\nEnd Paradox.\n\n\nRequire Import ZArith.\n\n\n\nInductive itree : Set :=\n| ileaf : itree\n| inode : Z-> (nat -> itree) -> itree.\n\nDefinition isingle l := inode l (fun i => ileaf).\n\nDefinition t1 := inode 0 (fun n => isingle (Z_of_nat (2*n))).\n\nDefinition t2 := inode 0\n (fun n : nat =>\n inode (Z_of_nat n)\n (fun p => isingle (Z_of_nat (n*p)))).\n\n\nInductive itree_le : itree-> itree -> Prop :=\n | le_leaf : forall t, itree_le ileaf t\n | le_node : forall l l' s s',\n Zle l l' ->\n (forall i, exists j:nat, itree_le (s i) (s' j)) ->\n itree_le (inode l s) (inode l' s').\n\n\nTheorem itree_le_trans :\n forall t t', itree_le t t' ->\n forall t'', itree_le t' t'' -> itree_le t t''.\n induction t.\n constructor 1.\n\n intros t'; case t'.\n inversion 1.\n intros z0 i0 H0.\n intro t'';case t''.\n inversion 1.\n intros.\n inversion_clear H1.\n constructor 2.\n inversion_clear H0;eauto with zarith.\n inversion_clear H0.\n intro i2; case (H4 i2).\n intros.\n generalize (H i2 _ H0).\n intros.\n case (H3 x);intros.\n generalize (H5 _ H6).\n exists x0;auto.\nQed.\n\n\n\nInductive itree_le' : itree-> itree -> Prop :=\n | le_leaf' : forall t, itree_le' ileaf t\n | le_node' : forall l l' s s' g,\n Zle l l' ->\n (forall i, itree_le' (s i) (s' (g i))) ->\n itree_le' (inode l s) (inode l' s').\n\n\n\n\n\nLemma t1_le_t2 : itree_le t1 t2.\n unfold t1, t2.\n constructor.\n auto with zarith.\n intro i; exists (2 * i).\n unfold isingle.\n constructor.\n auto with zarith.\n exists i;constructor.\nQed.\n\n\n\nLemma t1_le'_t2 : itree_le' t1 t2.\n unfold t1, t2.\n constructor 2 with (fun i : nat => 2 * i).\n auto with zarith.\n unfold isingle;\n intro i ; constructor 2 with (fun i :nat => i).\n auto with zarith.\n constructor .\nQed.\n\n\nRequire Import List.\n\nInductive ltree (A:Set) : Set :=\n lnode : A -> list (ltree A) -> ltree A.\n\nInductive prop : Prop :=\n prop_intro : Prop -> prop.\n\nLemma prop_inject: prop.\nProof prop_intro prop.\n\n\nInductive ex_Prop (P : Prop -> Prop) : Prop :=\n exP_intro : forall X : Prop, P X -> ex_Prop P.\n\nLemma ex_Prop_inhabitant : ex_Prop (fun P => P -> P).\nProof.\n exists (ex_Prop (fun P => P -> P)).\n trivial.\nQed.\n\n\n\n\n(*\n\nCheck (fun (P:Prop->Prop)(p: ex_Prop P) =>\n match p with exP_intro X HX => X end).\nError:\nIncorrect elimination of \"p\" in the inductive type\n\"ex_Prop\", the return type has sort \"Type\" while it should be\n\"Prop\"\n\nElimination of an inductive object of sort \"Prop\"\nis not allowed on a predicate in sort \"Type\"\nbecause proofs can be eliminated only to build proofs\n\n*)\n\n(*\nCheck (match prop_inject with (prop_intro P p) => P end).\n\nError:\nIncorrect elimination of \"prop_inject\" in the inductive type\n\"prop\", the return type has sort \"Type\" while it should be\n\"Prop\"\n\nElimination of an inductive object of sort \"Prop\"\nis not allowed on a predicate in sort \"Type\"\nbecause proofs can be eliminated only to build proofs\n\n*)\nPrint prop_inject.\n\n(*\nprop_inject =\nprop_inject = prop_intro prop (fun H : prop => H)\n : prop\n*)\n\n\nInductive typ : Type :=\n typ_intro : Type -> typ.\n\nDefinition typ_inject: typ.\nsplit.\nexact typ.\n(*\nDefined.\n\nError: Universe Inconsistency.\n*)\nAbort.\n(*\n\nInductive aSet : Set :=\n aSet_intro: Set -> aSet.\n\n\nUser error: Large non-propositional inductive types must be in Type\n\n*)\n\nInductive ex_Set (P : Set -> Prop) : Type :=\n exS_intro : forall X : Set, P X -> ex_Set P.\n\n\nInductive comes_from_the_left (P Q:Prop): P \\/ Q -> Prop :=\n c1 : forall p, comes_from_the_left P Q (or_introl (A:=P) Q p).\n\nGoal (comes_from_the_left _ _ (or_introl True I)).\nsplit.\nQed.\n\nGoal ~(comes_from_the_left _ _ (or_intror True I)).\n red;inversion 1.\n (* discriminate H0.\n *)\nAbort.\n\nReset comes_from_the_left.\n\n(*\n\n\n\n\n\n\n Definition comes_from_the_left (P Q:Prop)(H:P \\/ Q): Prop :=\n match H with\n | or_introl p => True\n | or_intror q => False\n end.\n\nError:\nIncorrect elimination of \"H\" in the inductive type\n\"or\", the return type has sort \"Type\" while it should be\n\"Prop\"\n\nElimination of an inductive object of sort \"Prop\"\nis not allowed on a predicate in sort \"Type\"\nbecause proofs can be eliminated only to build proofs\n\n*)\n\nDefinition comes_from_the_left_sumbool\n (P Q:Prop)(x:{P}+{Q}): Prop :=\n match x with\n | left p => True\n | right q => False\n end.\n\n\n\n\nClose Scope Z_scope.\n\n\n\n\n\nTheorem S_is_not_O : forall n, S n <> 0.\n\nDefinition Is_zero (x:nat):= match x with\n | 0 => True\n | _ => False\n end.\n Lemma O_is_zero : forall m, m = 0 -> Is_zero m.\n Proof.\n intros m H; subst m.\n (*\n ============================\n Is_zero 0\n *)\n simpl;trivial.\n Qed.\n\n red; intros n Hn.\n apply O_is_zero with (m := S n).\n assumption.\nQed.\n\nTheorem disc2 : forall n, S (S n) <> 1.\nProof.\n intros n Hn; discriminate.\nQed.\n\n\nTheorem disc3 : forall n, S (S n) = 0 -> forall Q:Prop, Q.\nProof.\n intros n Hn Q.\n discriminate.\nQed.\n\n\n\nTheorem inj_succ : forall n m, S n = S m -> n = m.\nProof.\n\n\nLemma inj_pred : forall n m, n = m -> pred n = pred m.\nProof.\n intros n m eq_n_m.\n rewrite eq_n_m.\n trivial.\nQed.\n\n intros n m eq_Sn_Sm.\n apply inj_pred with (n:= S n) (m := S m); assumption.\nQed.\n\nLemma list_inject : forall (A:Set)(a b :A)(l l':list A),\n a :: b :: l = b :: a :: l' -> a = b /\\ l = l'.\nProof.\n intros A a b l l' e.\n injection e.\n auto.\nQed.\n\n\nTheorem not_le_Sn_0 : forall n:nat, ~ (S n <= 0).\nProof.\n red; intros n H.\n case H.\nUndo.\n\nLemma not_le_Sn_0_with_constraints :\n forall n p , S n <= p -> p = 0 -> False.\nProof.\n intros n p H; case H ;\n intros; discriminate.\nQed.\n\neapply not_le_Sn_0_with_constraints; eauto.\nQed.\n\n\nTheorem not_le_Sn_0' : forall n:nat, ~ (S n <= 0).\nProof.\n red; intros n H ; inversion H.\nQed.\n\nDerive Inversion le_Sn_0_inv with (forall n :nat, S n <= 0).\nCheck le_Sn_0_inv.\n\nTheorem le_Sn_0'' : forall n p : nat, ~ S n <= 0 .\nProof.\n intros n p H;\n inversion H using le_Sn_0_inv.\nQed.\n\nDerive Inversion_clear le_Sn_0_inv' with (forall n :nat, S n <= 0).\nCheck le_Sn_0_inv'.\n\n\nTheorem le_reverse_rules :\n forall n m:nat, n <= m ->\n n = m \\/\n exists p, n <= p /\\ m = S p.\nProof.\n intros n m H; inversion H.\n left;trivial.\n right; exists m0; split; trivial.\nRestart.\n intros n m H; inversion_clear H.\n left;trivial.\n right; exists m0; split; trivial.\nQed.\n\nInductive ArithExp : Set :=\n Zero : ArithExp\n | Succ : ArithExp -> ArithExp\n | Plus : ArithExp -> ArithExp -> ArithExp.\n\nInductive RewriteRel : ArithExp -> ArithExp -> Prop :=\n RewSucc : forall e1 e2 :ArithExp,\n RewriteRel e1 e2 -> RewriteRel (Succ e1) (Succ e2)\n | RewPlus0 : forall e:ArithExp,\n RewriteRel (Plus Zero e) e\n | RewPlusS : forall e1 e2:ArithExp,\n RewriteRel e1 e2 ->\n RewriteRel (Plus (Succ e1) e2) (Succ (Plus e1 e2)).\n\n\n\nFixpoint plus (n p:nat) {struct n} : nat :=\n match n with\n | 0 => p\n | S m => S (plus m p)\n end.\n\nFixpoint plus' (n p:nat) {struct p} : nat :=\n match p with\n | 0 => n\n | S q => S (plus' n q)\n end.\n\nFixpoint plus'' (n p:nat) {struct n} : nat :=\n match n with\n | 0 => p\n | S m => plus'' m (S p)\n end.\n\n\nFixpoint even_test (n:nat) : bool :=\n match n\n with 0 => true\n | 1 => false\n | S (S p) => even_test p\n end.\n\n\nReset even_test.\n\nFixpoint even_test (n:nat) : bool :=\n match n\n with\n | 0 => true\n | S p => odd_test p\n end\nwith odd_test (n:nat) : bool :=\n match n\n with\n | 0 => false\n | S p => even_test p\n end.\n\n\n\nEval simpl in even_test.\n\n\n\nEval simpl in (fun x : nat => even_test x).\n\nEval simpl in (fun x : nat => plus 5 x).\nEval simpl in (fun x : nat => even_test (plus 5 x)).\n\nEval simpl in (fun x : nat => even_test (plus x 5)).\n\n\nSection Principle_of_Induction.\nVariable P : nat -> Prop.\nHypothesis base_case : P 0.\nHypothesis inductive_step : forall n:nat, P n -> P (S n).\nFixpoint nat_ind (n:nat) : (P n) :=\n match n return P n with\n | 0 => base_case\n | S m => inductive_step m (nat_ind m)\n end.\n\nEnd Principle_of_Induction.\n\nScheme Even_induction := Minimality for even Sort Prop\nwith Odd_induction := Minimality for odd Sort Prop.\n\nTheorem even_plus_four : forall n:nat, even n -> even (4+n).\nProof.\n intros n H.\n elim H using Even_induction with (P0 := fun n => odd (4+n));\n simpl;repeat constructor;assumption.\nQed.\n\n\nSection Principle_of_Double_Induction.\nVariable P : nat -> nat ->Prop.\nHypothesis base_case1 : forall x:nat, P 0 x.\nHypothesis base_case2 : forall x:nat, P (S x) 0.\nHypothesis inductive_step : forall n m:nat, P n m -> P (S n) (S m).\nFixpoint nat_double_ind (n m:nat){struct n} : P n m :=\n match n, m return P n m with\n | 0 , x => base_case1 x\n | (S x), 0 => base_case2 x\n | (S x), (S y) => inductive_step x y (nat_double_ind x y)\n end.\nEnd Principle_of_Double_Induction.\n\nSection Principle_of_Double_Recursion.\nVariable P : nat -> nat -> Set.\nHypothesis base_case1 : forall x:nat, P 0 x.\nHypothesis base_case2 : forall x:nat, P (S x) 0.\nHypothesis inductive_step : forall n m:nat, P n m -> P (S n) (S m).\nFixpoint nat_double_rec (n m:nat){struct n} : P n m :=\n match n, m return P n m with\n | 0 , x => base_case1 x\n | (S x), 0 => base_case2 x\n | (S x), (S y) => inductive_step x y (nat_double_rec x y)\n end.\nEnd Principle_of_Double_Recursion.\n\nDefinition min : nat -> nat -> nat :=\n nat_double_rec (fun (x y:nat) => nat)\n (fun (x:nat) => 0)\n (fun (y:nat) => 0)\n (fun (x y r:nat) => S r).\n\nEval compute in (min 5 8).\nEval compute in (min 8 5).\n\n\n\nLemma not_circular : forall n:nat, n <> S n.\nProof.\n intro n.\n apply nat_ind with (P:= fun n => n <> S n).\n discriminate.\n red; intros n0 Hn0 eqn0Sn0;injection eqn0Sn0;trivial.\nQed.\n\nDefinition eq_nat_dec : forall n p:nat , {n=p}+{n <> p}.\nProof.\n intros n p.\n apply nat_double_rec with (P:= fun (n q:nat) => {q=p}+{q <> p}).\nUndo.\n pattern p,n.\n elim n using nat_double_rec.\n destruct x; auto.\n destruct x; auto.\n intros n0 m H; case H.\n intro eq; rewrite eq ; auto.\n intro neg; right; red ; injection 1; auto.\nDefined.\n\nDefinition eq_nat_dec' : forall n p:nat, {n=p}+{n <> p}.\n decide equality.\nDefined.\n\nPrint Acc.\n\n\nRequire Import Minus.\n\n(*\nFixpoint div (x y:nat){struct x}: nat :=\n if eq_nat_dec x 0\n then 0\n else if eq_nat_dec y 0\n then x\n else S (div (x-y) y).\n\nError:\nRecursive definition of div is ill-formed.\nIn environment\ndiv : nat -> nat -> nat\nx : nat\ny : nat\n_ : x <> 0\n_ : y <> 0\n\nRecursive call to div has principal argument equal to\n\"x - y\"\ninstead of a subterm of x\n\n*)\n\nLemma minus_smaller_S: forall x y:nat, x - y < S x.\nProof.\n intros x y; pattern y, x;\n elim x using nat_double_ind.\n destruct x0; auto with arith.\n simpl; auto with arith.\n simpl; auto with arith.\nQed.\n\nLemma minus_smaller_positive : forall x y:nat, x <>0 -> y <> 0 ->\n x - y < x.\nProof.\n destruct x; destruct y;\n ( simpl;intros; apply minus_smaller_S ||\n intros; absurd (0=0); auto).\nQed.\n\nDefinition minus_decrease : forall x y:nat, Acc lt x ->\n x <> 0 ->\n y <> 0 ->\n Acc lt (x-y).\nProof.\n intros x y H; case H.\n intros Hz posz posy.\n apply Hz; apply minus_smaller_positive; assumption.\nDefined.\n\nPrint minus_decrease.\n\n\n\nFixpoint div_aux (x y:nat)(H: Acc lt x):nat.\n refine (if eq_nat_dec x 0\n then 0\n else if eq_nat_dec y 0\n then y\n else div_aux (x-y) y _).\n apply (minus_decrease x y H);assumption.\nDefined.\n\n\nPrint div_aux.\n(*\ndiv_aux =\n(fix div_aux (x y : nat) (H : Acc lt x) {struct H} : nat :=\n match eq_nat_dec x 0 with\n | left _ => 0\n | right _ =>\n match eq_nat_dec y 0 with\n | left _ => y\n | right _0 => div_aux (x - y) y (minus_decrease x y H _ _0)\n end\n end)\n : forall x : nat, nat -> Acc lt x -> nat\n*)\n\nRequire Import Wf_nat.\nDefinition div x y := div_aux x y (lt_wf x).\n\nExtraction div.\n(*\nlet div x y =\n div_aux x y\n*)\n\nExtraction div_aux.\n\n(*\nlet rec div_aux x y =\n match eq_nat_dec x O with\n | Left -> O\n | Right ->\n (match eq_nat_dec y O with\n | Left -> y\n | Right -> div_aux (minus x y) y)\n*)\n\nLemma vector0_is_vnil : forall (A:Set)(v:vector A 0), v = Vnil A.\nProof.\n intros A v;inversion v.\nAbort.\n\n(*\n Lemma vector0_is_vnil_aux : forall (A:Set)(n:nat)(v:vector A n),\n n= 0 -> v = Vnil A.\n\nToplevel input, characters 40281-40287\n> Lemma vector0_is_vnil_aux : forall (A:Set)(n:nat)(v:vector A n), n= 0 -> v = Vnil A.\n> ^^^^^^\nError: In environment\nA : Set\nn : nat\nv : vector A n\ne : n = 0\nThe term \"Vnil A\" has type \"vector A 0\" while it is expected to have type\n \"vector A n\"\n*)\n Require Import JMeq.\n\nLemma vector0_is_vnil_aux : forall (A:Set)(n:nat)(v:vector A n),\n n= 0 -> JMeq v (Vnil A).\nProof.\n destruct v.\n auto.\n intro; discriminate.\nQed.\n\nLemma vector0_is_vnil : forall (A:Set)(v:vector A 0), v = Vnil A.\nProof.\n intros a v;apply JMeq_eq.\n apply vector0_is_vnil_aux.\n trivial.\nQed.\n\n\nImplicit Arguments Vcons [A n].\nImplicit Arguments Vnil [A].\nImplicit Arguments Vhead [A n].\nImplicit Arguments Vtail [A n].\n\nDefinition Vid : forall (A : Type)(n:nat), vector A n -> vector A n.\nProof.\n destruct n; intro v.\n exact Vnil.\n exact (Vcons (Vhead v) (Vtail v)).\nDefined.\n\nEval simpl in (fun (A:Set)(v:vector A 0) => (Vid _ _ v)).\n\nEval simpl in (fun (A:Set)(v:vector A 0) => v).\n\n\n\nLemma Vid_eq : forall (n:nat) (A:Type)(v:vector A n), v=(Vid _ n v).\nProof.\n destruct v.\n reflexivity.\n reflexivity.\nDefined.\n\nTheorem zero_nil : forall A (v:vector A 0), v = Vnil.\nProof.\n intros.\n change (Vnil (A:=A)) with (Vid _ 0 v).\n apply Vid_eq.\nDefined.\n\n\nTheorem decomp :\n forall (A : Set) (n : nat) (v : vector A (S n)),\n v = Vcons (Vhead v) (Vtail v).\nProof.\n intros.\n change (Vcons (Vhead v) (Vtail v)) with (Vid _ (S n) v).\n apply Vid_eq.\nDefined.\n\n\n\nDefinition vector_double_rect :\n forall (A:Set) (P: forall (n:nat),(vector A n)->(vector A n) -> Type),\n P 0 Vnil Vnil ->\n (forall n (v1 v2 : vector A n) a b, P n v1 v2 ->\n P (S n) (Vcons a v1) (Vcons b v2)) ->\n forall n (v1 v2 : vector A n), P n v1 v2.\n induction n.\n intros; rewrite (zero_nil _ v1); rewrite (zero_nil _ v2).\n auto.\n intros v1 v2; rewrite (decomp _ _ v1);rewrite (decomp _ _ v2).\n apply X0; auto.\nDefined.\n\nRequire Import Bool.\n\nDefinition bitwise_or n v1 v2 : vector bool n :=\n vector_double_rect bool (fun n v1 v2 => vector bool n)\n Vnil\n (fun n v1 v2 a b r => Vcons (orb a b) r) n v1 v2.\n\n\nFixpoint vector_nth (A:Set)(n:nat)(p:nat)(v:vector A p){struct v}\n : option A :=\n match n,v with\n _ , Vnil => None\n | 0 , Vcons b _ _ => Some b\n | S n', Vcons _ p' v' => vector_nth A n' p' v'\n end.\n\nImplicit Arguments vector_nth [A p].\n\n\nLemma nth_bitwise : forall (n:nat) (v1 v2: vector bool n) i a b,\n vector_nth i v1 = Some a ->\n vector_nth i v2 = Some b ->\n vector_nth i (bitwise_or _ v1 v2) = Some (orb a b).\nProof.\n intros n v1 v2; pattern n,v1,v2.\n apply vector_double_rect.\n simpl.\n destruct i; discriminate 1.\n destruct i; simpl;auto.\n injection 1; injection 2;intros; subst a; subst b; auto.\nQed.\n\n Set Implicit Arguments.\n\n CoInductive Stream (A:Set) : Set :=\n | Cons : A -> Stream A -> Stream A.\n\n CoInductive LList (A: Set) : Set :=\n | LNil : LList A\n | LCons : A -> LList A -> LList A.\n\n\n\n\n\n Definition head (A:Set)(s : Stream A) := match s with Cons a s' => a end.\n\n Definition tail (A : Set)(s : Stream A) :=\n match s with Cons a s' => s' end.\n\n CoFixpoint repeat (A:Set)(a:A) : Stream A := Cons a (repeat a).\n\n CoFixpoint iterate (A: Set)(f: A -> A)(a : A) : Stream A:=\n Cons a (iterate f (f a)).\n\n CoFixpoint map (A B:Set)(f: A -> B)(s : Stream A) : Stream B:=\n match s with Cons a tl => Cons (f a) (map f tl) end.\n\nEval simpl in (fun (A:Set)(a:A) => repeat a).\n\nEval simpl in (fun (A:Set)(a:A) => head (repeat a)).\n\n\nCoInductive EqSt (A: Set) : Stream A -> Stream A -> Prop :=\n eqst : forall s1 s2: Stream A,\n head s1 = head s2 ->\n EqSt (tail s1) (tail s2) ->\n EqSt s1 s2.\n\n\nSection Parks_Principle.\nVariable A : Set.\nVariable R : Stream A -> Stream A -> Prop.\nHypothesis bisim1 : forall s1 s2:Stream A, R s1 s2 ->\n head s1 = head s2.\nHypothesis bisim2 : forall s1 s2:Stream A, R s1 s2 ->\n R (tail s1) (tail s2).\n\nCoFixpoint park_ppl : forall s1 s2:Stream A, R s1 s2 ->\n EqSt s1 s2 :=\n fun s1 s2 (p : R s1 s2) =>\n eqst s1 s2 (bisim1 p)\n (park_ppl (bisim2 p)).\nEnd Parks_Principle.\n\n\nTheorem map_iterate : forall (A:Set)(f:A->A)(x:A),\n EqSt (iterate f (f x)) (map f (iterate f x)).\nProof.\n intros A f x.\n apply park_ppl with\n (R:= fun s1 s2 => exists x: A,\n s1 = iterate f (f x) /\\ s2 = map f (iterate f x)).\n\n intros s1 s2 (x0,(eqs1,eqs2));rewrite eqs1;rewrite eqs2;reflexivity.\n intros s1 s2 (x0,(eqs1,eqs2)).\n exists (f x0);split;[rewrite eqs1|rewrite eqs2]; reflexivity.\n exists x;split; reflexivity.\nQed.\n\nLtac infiniteproof f :=\n cofix f; constructor; [clear f| simpl; try (apply f; clear f)].\n\n\nTheorem map_iterate' : forall (A:Set)(f:A->A)(x:A),\n EqSt (iterate f (f x)) (map f (iterate f x)).\ninfiniteproof map_iterate'.\n reflexivity.\nQed.\n\n\nImplicit Arguments LNil [A].\n\nLemma Lnil_not_Lcons : forall (A:Set)(a:A)(l:LList A),\n LNil <> (LCons a l).\n intros;discriminate.\nQed.\n\nLemma injection_demo : forall (A:Set)(a b : A)(l l': LList A),\n LCons a (LCons b l) = LCons b (LCons a l') ->\n a = b /\\ l = l'.\nProof.\n intros A a b l l' e; injection e; auto.\nQed.\n\n\nInductive Finite (A:Set) : LList A -> Prop :=\n| Lnil_fin : Finite (LNil (A:=A))\n| Lcons_fin : forall a l, Finite l -> Finite (LCons a l).\n\nCoInductive Infinite (A:Set) : LList A -> Prop :=\n| LCons_inf : forall a l, Infinite l -> Infinite (LCons a l).\n\nLemma LNil_not_Infinite : forall (A:Set), ~ Infinite (LNil (A:=A)).\nProof.\n intros A H;inversion H.\nQed.\n\nLemma Finite_not_Infinite : forall (A:Set)(l:LList A),\n Finite l -> ~ Infinite l.\nProof.\n intros A l H; elim H.\n apply LNil_not_Infinite.\n intros a l0 F0 I0' I1.\n case I0'; inversion_clear I1.\n trivial.\nQed.\n\nLemma Not_Finite_Infinite : forall (A:Set)(l:LList A),\n ~ Finite l -> Infinite l.\nProof.\n cofix H.\n destruct l.\n intro; absurd (Finite (LNil (A:=A)));[auto|constructor].\n constructor.\n apply H.\n red; intro H1;case H0.\n constructor.\n trivial.\nQed.\n\n\n\n\n", "meta": {"author": "JasonGross", "repo": "category-coq-experience-tests", "sha": "f9949ede618788fd051fe8327f997ee683388e49", "save_path": "github-repos/coq/JasonGross-category-coq-experience-tests", "path": "github-repos/coq/JasonGross-category-coq-experience-tests/category-coq-experience-tests-f9949ede618788fd051fe8327f997ee683388e49/coq/coq-8.3pl5-foundations/test-suite/success/RecTutorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.9284088079835904, "lm_q1q2_score": 0.8666053848837798}} {"text": "\n(* \n\nthis is a treatment of the water holding histogram problem found in\nhttps://www.youtube.com/watch?v=ftcIcn8AmSY\n\n *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Strings.String.\nRequire Import Nat.\nRequire Import List.\n\nImport ListNotations.\n\n(* Let's first define the type of our histogram *)\nDefinition histogram := list nat.\n\nDefinition max_nat (x1 x2 : nat) : nat :=\n if (leb x1 x2) then x2 else x1.\n\nDefinition min_nat (x1 x2 : nat) : nat :=\n if (leb x1 x2) then x1 else x2.\n\n(* define a low level utility function for the left to right sweep *)\nFixpoint left_to_right_sweep' (max : nat) (h : histogram) : list nat :=\n match h with\n | [] => []\n | x :: xs => (max_nat max x) :: (left_to_right_sweep' (max_nat max x) xs)\n end.\n\n(* define the left to right sweep function that returns, for each\nelement of the histogram the highest bar starting from the left. *)\nDefinition left_to_right_sweep (h : histogram) : list nat :=\n left_to_right_sweep' 0 h.\n\n(* define the right to left sweep function that returns, for each\nelement of the histogram the highest bar starting from the right *)\nDefinition right_to_left_sweep (h : histogram) : list nat :=\n rev (left_to_right_sweep (rev h)).\n\nCompute left_to_right_sweep [1 ; 2; 1; 4; 2; 1].\nCompute right_to_left_sweep [1 ; 2; 1; 4; 2; 1].\n\n(* Next, define some utility functions like zip *)\nFixpoint zip (l1 l2 : list nat) : list (nat * nat) :=\n match l1 with\n | [] => []\n | x :: xs => match l2 with\n | [] => []\n | y :: ys => (x, y) :: zip xs ys\n end\n end.\n\nCompute (zip [1; 2; 3; 4] [5; 6; 7; 8]).\n\n(* define a low level utility function useful for computing the water\nlevel *)\nFixpoint water_level' (levels : list (nat * nat)) : list nat :=\n match levels with\n | [] => []\n | (l, r) :: xs => (min_nat l r) :: water_level' xs\n end.\n\n(* now compute the water level *)\nDefinition water_level (h : histogram) : list nat :=\n let lr := left_to_right_sweep h in\n let rr := right_to_left_sweep h in\n let lrs := zip lr rr in\n water_level' lrs.\n\n(* Here is the example from the youtube video *)\nDefinition example := [2;6;3;5;2;8;1;4;2;2;5;3;5;7;4;1].\n\n(* for a particular bar and water level, how much water is there *)\nDefinition how_much_water (bar_and_water : (nat * nat)) : nat :=\n match bar_and_water with\n | (bar, water) => if (leb bar water) then water - bar else 0\n end.\n\n(* This function computes the total amount of water carried by a\nhistogram by just computing the amount of water carried by each bar.\n*)\nDefinition amount_of_water (bars : histogram) : nat :=\n let water := water_level bars in\n let bars_and_water := zip bars water in\n fold_left add (map how_much_water bars_and_water) 0.\n\n(* This should evaluate to 35. *)\nCompute amount_of_water example.\n\n(* Ok, now we'll work on the bitonic data structure representation.\nThis is the second development in the talk. *)\n\nDefinition height_width_list := list (nat * nat).\n\nFixpoint hw_list_eq (x y : height_width_list) : bool :=\n let lx := List.length x in\n let ly := List.length y in\n if (beq_nat lx ly)\n then match x with\n | (x1, x2) :: xs =>\n match y with\n | (y1, y2) :: ys => if (andb (beq_nat x1 y1) (beq_nat x2 y2)) \n then hw_list_eq xs ys\n else false\n | [] => true\n end\n | [] => true\n end\n else false.\n\nCompute hw_list_eq [(1, 2) ; (3, 4)] [(1, 2) ; (3, 4)].\nCompute hw_list_eq [(1, 4) ; (3, 4)] [(1, 2) ; (3, 4)].\nCompute hw_list_eq [(1, 2) ; (3, 4) ; (5, 6)] [(1, 2) ; (3, 4)].\n\n(* Define the glob data structure as in the video *)\nRecord glob : Set := mkGlob {\n left : height_width_list;\n h : nat;\n w : nat;\n right : height_width_list;\n water : nat }.\n\nDefinition initial_glob := mkGlob [] 0 0 [] 0.\n\nDefinition make_singleton_glob (h : nat) : glob :=\n mkGlob [] h 1 [] 0.\n\n(* The width function calculates the width of a list of height width\npairs. This is on the slide of utility functions. *)\nFixpoint width (hw : height_width_list) : nat :=\n match hw with\n | [] => 0\n | (h, w) :: xs => w + (width xs)\n end.\n\n(* The fill function computes how much water can be held at a\nparticular water height for a set of height width pairs. *)\nFixpoint fill (hw : height_width_list) (water_height : nat) : nat :=\n match hw with\n | [] => 0\n | (h, w) :: xs => (w * (water_height - h)) + (fill xs water_height)\n end.\n\n(* The function half is the \"split\" function that will divide a list\nof height width pairs into two lists. *)\nDefinition half (l : height_width_list) : (height_width_list * height_width_list) :=\n let n := length l in\n (firstn (n / 2) l, skipn (n / 2) l).\n\nCompute half [ (0, 1) ; (2, 3) ; (4, 5) ; (6, 7) ].\n\n(* OK, now we are going to implement the three way split. This is\ndefined in the video. *)\nFixpoint three_way_split (gas : nat) (x : height_width_list) (m : nat) : (height_width_list * option nat * height_width_list) :=\n match gas with\n | 0 => ([], None, [])\n | S g => match x with\n | [] => ([], None, [])\n | [ l ] => let (a, b) := l in\n if (Nat.leb a m)\n then ([l], None, [])\n else if (Nat.ltb m a)\n then ([], None, [l])\n else ([], Some b, [])\n | l :: ls => let (y, z) := half x in\n let (n, w) := hd (0, 0) z in\n if (Nat.ltb m n)\n then let '(p, q, r) := three_way_split g y m in\n (p, q, r ++ z)\n else let '(p, q, r) := three_way_split g z m in\n (y ++ p, q, r)\n end\n end.\n\n(* Next we define the oplus operator from the video. *)\nDefinition oplus (gas : nat) (x y : glob) : glob :=\n if (Nat.ltb (h x) (h y))\n then let '(lss, eql, gtr) := three_way_split gas (left y) (h x) in\n mkGlob ( (left x) ++ [(h x, (w x) + (width (right x)) + (width lss))] ++ gtr )\n (h y)\n (w y)\n (right y)\n ( (water x) + \n (fill (right x) (h x)) +\n (fill lss (h x)) +\n (water y) )\n else if (Nat.ltb (h y) (h x))\n then let '(lss, eql, gtr) := three_way_split gas (right x) (h y) in\n mkGlob (left x)\n (h x)\n (w x) \n ( (right y) ++ [(h y, (width lss) + (width (left y)) + (w y))] ++ gtr )\n ( (water x) + (fill lss (h y)) + (fill (left y) (h y)) + (water y) )\n else mkGlob (left x)\n (h x)\n ( (w x) + (width (right x)) + (width (left y)) + (w y) )\n (right y)\n ( (water x) + (fill (right x) (h x)) + (fill (left y) (h x)) + (water y) ).\n\n(* And we define a notation for oplus *)\nNotation \"x @ y\" :=\n (oplus 1000 x y)\n (at level 50,\n left associativity).\n\n(* Now let's do some testing of the oplus. First we need to generate\nall of the initial globs *)\n\nDefinition globs_start (w : histogram) : list glob :=\n List.map make_singleton_glob w.\n\n(* Create the starting list of singleton globs from the example from the video *)\nDefinition start : list glob :=\n globs_start example.\n\nCompute start.\n\n(* Now, for testing, break out every glob *)\nDefinition x1 : glob := List.hd initial_glob start.\nDefinition x2 : glob := List.nth 1 start initial_glob.\nDefinition x3 : glob := List.nth 2 start initial_glob.\nDefinition x4 : glob := List.nth 3 start initial_glob.\nDefinition x5 : glob := List.nth 4 start initial_glob.\nDefinition x6 : glob := List.nth 5 start initial_glob.\nDefinition x7 : glob := List.nth 6 start initial_glob.\nDefinition x8 : glob := List.nth 7 start initial_glob.\nDefinition x9 : glob := List.nth 8 start initial_glob.\nDefinition x10 : glob := List.nth 9 start initial_glob.\nDefinition x11 : glob := List.nth 10 start initial_glob.\nDefinition x12 : glob := List.nth 11 start initial_glob.\nDefinition x13 : glob := List.nth 12 start initial_glob.\nDefinition x14 : glob := List.nth 13 start initial_glob.\nDefinition x15 : glob := List.nth 14 start initial_glob.\nDefinition x16 : glob := List.nth 15 start initial_glob.\n\n(* Now do some simple tests of the oplus operator *)\nCompute (x1 @ x2).\nCompute (x1 @ x2 @ x3 @ x4 @ x5).\nCompute (x1 @ x2 @ x3 @ x4 @ x5 @ x6 @ x7 @ x8 @\n x9 @ x10 @ x11 @ x12 @ x13 @ x14 @ x15 @ x16).\n\n(* Now testing the three-case bitonic glob slide. Here is test #1. *)\nDefinition one_l : glob :=\n (make_singleton_glob 1) @ (make_singleton_glob 3) @ (make_singleton_glob 4) @ (make_singleton_glob 2).\n \nDefinition one_r : glob :=\n (make_singleton_glob 1) @ (make_singleton_glob 2) @ (make_singleton_glob 3) @ (make_singleton_glob 2).\n\nCompute (one_l @ one_r).\n\n(* Here is test #2 of the oplus operator *)\nDefinition two_l : glob :=\n (make_singleton_glob 1) @ (make_singleton_glob 2) @ (make_singleton_glob 3) @ (make_singleton_glob 2).\n \nDefinition two_r : glob :=\n (make_singleton_glob 1) @ (make_singleton_glob 4) @ (make_singleton_glob 5) @ (make_singleton_glob 2).\n\nCompute (two_l @ two_r).\n\n(* Here is test #3 of the oplus operator *)\nDefinition three_l : glob :=\n (make_singleton_glob 1) @ (make_singleton_glob 2) @ (make_singleton_glob 3) @ (make_singleton_glob 2).\n \nDefinition three_r : glob :=\n (make_singleton_glob 1) @ (make_singleton_glob 2) @ (make_singleton_glob 3) @ (make_singleton_glob 2).\n\nCompute (three_l @ three_r).\n\n(* OK, it looks like the glob stuff is working *)\n\n(* Now let's try asking if the oplus operator is associative *)\nTheorem oplus_assoc : forall (x y z : glob),\n x @ (y @ z) = (x @ y) @ z.\nProof.\n Admitted.\n\n(* Now, let's work on the quickchick support *)\n\nSet Warnings \"-extraction-opaque-accessed,-extraction\".\nSet Warnings \"-notation-overridden,-parsing\".\n\nFrom QuickChick Require Import QuickChick.\n\n(* Do a quickchick that the simple sequential solution returns the\nsame amount of water as the oplus version. *)\n\nDefinition oplus_water (h : histogram) : nat :=\n let gs := globs_start h in\n let final := List.fold_left (oplus 1000) gs initial_glob in\n water final.\n\nDefinition equiv_solutions_p (h : histogram) : bool :=\n beq_nat (amount_of_water h) (oplus_water h).\n\nQuickChick\n (forAll (vectorOf 32 (choose (0, 20))) equiv_solutions_p).\n\n(* Now we know the oplus and simple sequential versions return\nthe same value. *)\n\n(* Let's test the oplus to see if it associative *)\n\nDefinition glob_eq (x y : glob) : bool :=\n match x with\n | {| left := xleft; h := xh; w := xw; right := xright; water := xwater |} =>\n match y with\n | {| left := yleft; h := yh; w := yw; right := yright; water := ywater |} =>\n List.fold_left (andb) [ (hw_list_eq xleft yleft) ;\n (beq_nat xh yh) ;\n (beq_nat xw yw) ;\n (hw_list_eq xright yright) ;\n (beq_nat xwater ywater) ] true\n end\n end.\n\nDefinition oplus_assoc_p (globs : (glob * glob * glob)) : bool :=\n match globs with\n | (x, y, z) =>\n glob_eq (x @ (y @ z)) ((x @ y) @ z)\n end.\n\n(* First, let's define useful generators. This generator returns a\nlist of singleton globs *)\nDefinition genStartState : G (list glob) :=\n bindGen (vectorOf 8 (choose (0, 20)))\n (fun xs => returnGen (globs_start xs)).\n\n(* This generator creates a glob *)\nDefinition genGlob : G glob :=\n bindGen genStartState\n (fun start => returnGen (fold_left (oplus 1000) start initial_glob)).\n\n(* Now I want to derive a show function for globs *)\nDerive Show for glob.\nPrint showglob.\n\n(* TODO: work on shrinkers *)\n\n\n(* OK, let's put together a check. *)\nQuickChick\n (forAll\n (bindGen genGlob\n (fun x =>\n bindGen genGlob\n (fun y =>\n bindGen genGlob (fun z => returnGen (x, y, z))))) oplus_assoc_p).\n\n(* OK, now I have quickchicked two properties. The first is that the\nsimple sequential version returns the same value as the oplus. The\nsecond is that oplus is associative. So I think it is OK to start\ntrying to prove that the oplus operator is associative. *)\n\n\n\n", "meta": {"author": "andrewtron3000", "repo": "steele-coq", "sha": "c666776ea5097fb46895c0e9b7518830871ca24a", "save_path": "github-repos/coq/andrewtron3000-steele-coq", "path": "github-repos/coq/andrewtron3000-steele-coq/steele-coq-c666776ea5097fb46895c0e9b7518830871ca24a/main.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436404, "lm_q2_score": 0.9059898254600902, "lm_q1q2_score": 0.8655094150578874}} {"text": "(** * Lists: Working with Structured Data *)\n\nFrom LF Require Export Induction.\n\nModule NatList.\n\n\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one (as with [nybble], and here): *)\n\nInductive natprod : Type :=\n| pair (n1 n2 : nat).\n\n(** This declaration can be read: \"The one and only way to\n construct a pair of numbers is by applying the constructor [pair]\n to two arguments of type [nat].\" *)\n\nCheck (pair 3 5) : natprod.\n\n(** Here are simple functions for extracting the first and\n second components of a pair. *)\n\nDefinition fst (p : natprod) : nat :=\n match p with\n | pair x y => x\n end.\n\nDefinition snd (p : natprod) : nat :=\n match p with\n | pair x y => y\n end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs will be used heavily in what follows, it is nice\n to be able to write them with the standard mathematical notation\n [(x,y)] instead of [pair x y]. We can tell Coq to allow this with\n a [Notation] declaration. *)\n\n\nNotation \"( x , y )\" := (pair x y).\n\n\n(** The new notation can be used both in expressions and in pattern\n matches. *)\n\nCompute (fst (3,5)).\nCompute (snd ( 3, 5)).\n\nDefinition fst' (p : natprod) : nat :=\n match p with\n | (x,y) => x\n end.\n\nDefinition snd' (p : natprod) : nat :=\n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n match p with\n | (x,y) => (y,x)\n end.\n\n(** Note that pattern-matching on a pair (with parentheses: [(x, y)])\n is not to be confused with the \"multiple pattern\" syntax (with no\n parentheses: [x, y]) that we have seen previously. The above\n examples illustrate pattern matching on a pair with elements [x]\n and [y], whereas, for example, the definition of [minus] in\n [Basics] performs pattern matching on the values [n] and [m]:\n\n Fixpoint minus (n m : nat) : nat :=\n match n, m with\n | O , _ => O\n | S _ , O => n\n | S n', S m' => minus n' m'\n end.\n\n The distinction is minor, but it is worth knowing that they\n are not the same. For instance, the following definitions are\n ill-formed:\n\n (* Can't match on a pair with multiple patterns: *)\n Definition bad_fst (p : natprod) : nat :=\n match p with\n | x, y => x\n end.\n\n (* Can't match on multiple values with pair patterns: *)\n Definition bad_minus (n m : nat) : nat :=\n match n, m with\n | (O , _ ) => O\n | (S _ , O ) => n\n | (S n', S m') => bad_minus n' m'\n end.\n*)\n\n(** Now let's try to prove a few simple facts about pairs.\n\n If we state properties of pairs in a slightly peculiar way, we can\n sometimes complete their proofs with just reflexivity (and its\n built-in simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** Instead, we need to expose the structure of [p] so that\n [simpl] can perform the pattern match in [fst] and [snd]. We can\n do this with [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n\n(** Notice that, unlike its behavior with [nat]s, where it\n generates two subgoals, [destruct] generates just one subgoal\n here. That's because [natprod]s can only be constructed in one\n way. *)\n\n(** **** Exercise: 1 star, standard (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros. simpl. destruct p. simpl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros. destruct p. simpl. reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n type of _lists_ of numbers like this: \"A list is either the empty\n list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n | nil\n | cons (n : nat) (l : natlist).\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n declarations, but here is roughly what's going on in case you are\n interested. The \"[right associativity]\" annotation tells Coq how to\n parenthesize expressions involving multiple uses of [::] so that,\n for example, the next three declarations mean exactly the same\n thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The \"[at level 60]\" part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\n\n Notation \"x + y\" := (plus x y)\n (at level 50, left associativity).\n\n the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than\n [1 + (2 :: [3])].\n\n (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n you read them in a [.v] file. The inner brackets, around 3, indicate\n a list, but the outer brackets, which are invisible in the HTML\n rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n part should be displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** Next let's look at several functions for constructing and\n manipulating lists. First, the [repeat] function takes a number\n [n] and a [count] and returns a list of length [count] in which\n every element is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\nFixpoint repeat_tai (n count:nat) (acc: natlist) : natlist :=\n match count with\n | O => acc\n | S count' => repeat_tai n count' (n :: acc)\n end.\n\nCompute repeat_tai 3 2 [].\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Since [app] will be used extensively, it is again convenient\n to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first element (the\n \"tail\"). Since the empty list has no first element, we pass\n a default value to be returned in that case. *)\n\nDefinition hd (default : nat) (l : natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l : natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, standard, especially useful (list_funs) \n\n Complete the definitions of [nonzeros], [oddmembers], and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | [] => []\n | 0 :: t => nonzeros t\n | a :: t => a :: (nonzeros t)\n end.\n\n\nExample test_nonzeros:\n nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof.\n simpl.\n reflexivity.\nQed.\n\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | [] => []\n | h :: t => match oddb h with\n | true => h :: oddmembers t\n | false => oddmembers t\n end\n end.\n\n\nExample test_oddmembers:\n oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof.\n simpl. reflexivity.\nQed.\n\nDefinition countoddmembers (l:natlist) : nat :=\n (* This need [Fixpoint] *)\n (* match l with *)\n (* | [] => O *)\n (* | h :: d => match oddb h with *)\n (* | true => S (countoddmembers d) *)\n (* | false => countoddmembers *)\n (* end *)\n (* end. *)\n length ( oddmembers l ).\n\nExample test_countoddmembers1:\n countoddmembers [1;0;3;1;4;5] = 4.\nProof.\n simpl. reflexivity.\nQed.\n\nExample test_countoddmembers2:\n countoddmembers [0;2;4] = 0.\nProof.\n simpl. reflexivity.\nQed.\n\nExample test_countoddmembers3:\n countoddmembers nil = 0.\nProof.\n simpl. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) \n\n Complete the following definition of [alternate], which\n interleaves two lists into one, alternating between elements taken\n from the first list and elements from the second. See the tests\n below for more specific examples.\n\n (Note: one natural and elegant way of writing [alternate] will\n fail to satisfy Coq's requirement that all [Fixpoint] definitions\n be \"obviously terminating.\" If you find yourself in this rut,\n look for a slightly more verbose solution that considers elements\n of both lists at the same time. One possible solution involves\n defining a new kind of pairs, but this is not the only way.) *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n (* This solution cannot guess decreasing argument of fix *)\n (* match l1 with *)\n (* | [] => l2 *)\n (* | h :: m => h :: alternate l2 m *)\n\n (* Another solution Give defination by proof *)\n match l1, l2 with\n | [] , [] => []\n | [] , l2 => l2\n | l1 , [] => l1\n | h1::t1 , h2::t2 => h1::h2::(alternate t1 t2)\n end.\n\n\nExample test_alternate1:\n alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof.\n reflexivity.\nQed.\n\n\nExample test_alternate2:\n alternate [1] [4;5;6] = [1;4;5;6].\nProof.\n reflexivity.\nQed.\n\nExample test_alternate3:\n alternate [1;2;3] [4] = [1;4;2;3].\nProof.\n reflexivity.\nQed.\n\n\nExample test_alternate4:\n alternate [] [20;30] = [20;30].\nProof.\n reflexivity.\nQed.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n can appear multiple times rather than just once. One possible\n representation for a bag of numbers is as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, standard, especially useful (bag_functions) \n\n Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v : nat) (s : bag) : nat :=\n match s with\n | [] => O\n | h :: t => if h =? v then S(count v t) else (count v t)\n end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof.\n simpl.\n reflexivity.\nQed.\n\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof.\n simpl.\n reflexivity.\nQed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n the elements of [a] and of [b]. (Mathematicians usually define\n [union] on multisets a little bit differently -- using max instead\n of sum -- which is why we don't call this operation [union].) For\n [sum], we're giving you a header that does not give explicit names\n to the arguments. Moreover, it uses the keyword [Definition]\n instead of [Fixpoint], so even if you had names for the arguments,\n you wouldn't be able to process them recursively. The point of\n stating the question this way is to encourage you to think about\n whether [sum] can be implemented in another way -- perhaps by\n using one or more functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof.\n simpl.\n reflexivity.\nQed.\n\nDefinition add (v : nat) (s : bag) : bag :=\n v :: s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof.\n simpl.\n reflexivity.\nQed.\n\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof.\n simpl.\n reflexivity.\nQed.\n\nSearch \"mem\".\n\n(* I think it should be a Fixpoint *)\nFixpoint member (v : nat) (s : bag) : bool :=\n (* This definition [Fixpoint] *)\n match s with\n | [] => false\n | h::d => if h =? v then true else (member v d)\n end.\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (bag_more_functions) \n\n Here are some more [bag] functions for you to practice with. *)\n\n(** When [remove_one] is applied to a bag without the number to\n remove, it should return the same bag unchanged. (This exercise\n is optional, but students following the advanced track will need\n to fill in the definition of [remove_one] for a later\n exercise.) *)\n\nFixpoint remove_one (v : nat) (s : bag) : bag :=\n match s with\n | [] => []\n | h::t => if h =? v then t else h:: (remove_one v t)\n end.\n\nExample test_remove_one1:\n count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\n\nExample test_remove_one2:\n count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one3:\n count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\nExample test_remove_one4:\n count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n (* Similar to remove_one *)\n match s with\n | [] => []\n | h::t => if h =? v then (remove_all v t) else h:: (remove_all v t)\n end.\n\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. reflexivity. Qed.\n\nFixpoint subset (s1 : bag) (s2 : bag) : bool :=\n match s1 with\n | [] => true (* empty set is subset of any set *)\n | h::d => if (member h s2) then (subset d (remove_one h s2)) else false\n end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, especially useful (add_inc_count) \n\n Adding a value to a bag should increase the value's count by one.\n State that as a theorem and prove it. *)\n(*\nTheorem bag_theorem : ...\nProof.\n ...\nQed.\n *)\n\n(* Require Import Omega. *)\n(* Theorem add_inc_count : forall bg : bag ,forall num:nat, *)\n(* count num (num::bg) = (count num bg) + 1. *)\n(* Proof. *)\n(* Search \"eqb\". *)\n(* Print eqb_refl. *)\n(* Print count. *)\n(* Print bag. *)\n(* intros. destruct bg. *)\n(* - simpl. rewrite <- eqb_refl. reflexivity. *)\n(* - assert (n=num\\/ n <> num). *)\n(* omega. *)\n(* destruct H. *)\n(* rewrite H. *)\n(* simpl. rewrite <- eqb_refl. simpl. omega. *)\n(* simpl. rewrite <- eqb_refl. *)\n(* intuition. *)\n(* Show Proof. *)\n(* Qed. *)\n\n(* DO NOT MODIFY THE following line: *)\nDefinition manual_grade_for_add_inc_count : option (nat*string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, just the simplification performed by [reflexivity] is\n enough for this theorem... *)\n\nPrint app.\n\nTheorem nil_app : forall l : natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ...because the [[]] is substituted into the\n \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n the match) in the definition of [app], allowing the match itself\n to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons n l' *)\n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. We'll see how to do this next. *)\n\n(** (Micro-Sermon: As we get deeper into this material, simply\n _reading_ proof scripts will not get you very far! It is\n important to step through the details of each one using Coq and\n think about what each step achieves. Otherwise it is more or less\n guaranteed that the exercises will make no sense when you get to\n them. 'Nuff said.) *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n little less familiar than standard natural number induction, but\n the idea is equally simple. Each [Inductive] declaration defines\n a set of data values that can be built up using the declared\n constructors. For example, a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to another\n number; and a list can be either [nil] or [cons] applied to a\n number and a list. Moreover, applications of the declared\n constructors to one another are the _only_ possible shapes\n that elements of an inductively defined set can have.\n\n This last fact directly gives rise to a way of reasoning about\n inductively defined sets: a number is either [O] or else it is [S]\n applied to some _smaller_ number; a list is either [nil] or else\n it is [cons] applied to some number and some _smaller_ list;\n etc. So, if we have in mind some proposition [P] that mentions a\n list [l] and we want to argue that [P] holds for _all_ lists, we\n can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can always be broken down into smaller ones,\n eventually reaching [nil], these two arguments together establish\n the truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n simpl.\n reflexivity.\n - (* l1 = cons n l1' *)\n Print app.\n (* Unfold app we knwo that :: from inside to outside with the help of simpl *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n [as...] clause provided to the [induction] tactic gives a name to\n the induction hypothesis corresponding to the smaller list [l1']\n in the [cons] case.\n\n Once again, this Coq proof is not especially illuminating as a\n static document -- it is easy to see what's going on if you are\n reading the proof in an interactive Coq session and you can see\n the current goal and context at each point, but this state is not\n visible in the written-down parts of the Coq proof. So a\n natural-language proof -- one written for human readers -- will\n need to include more explicit signposts; in particular, it will\n help the reader stay oriented if we remind them exactly what the\n induction hypothesis is in the second case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n (the induction hypothesis). We must show\n\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n By the definition of [++], this follows from\n\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n which is immediate from the induction hypothesis. [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n lists, suppose we use [app] to define a list-reversing\n function [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => rev t ++ [h]\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** For something a bit more challenging than the proofs\n we've seen so far, let's prove that reversing a list does not\n change its length. Our first attempt gets stuck in the successor\n case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n reflexivity.\n - (* l = n :: l' *)\n (* This is the tricky case. Let's begin as usual\n by simplifying. *)\n simpl.\n (* Now we seem to be stuck: the goal is an equality\n involving [++], but we don't have any useful equations\n in either the immediate context or in the global\n environment! We can make a little progress by using\n the IH to rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n would have enabled us to make progress at the point where we got\n stuck and state it as a separate lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n simpl.\n reflexivity.\n - (* l1 = cons *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Note that, to make the lemma as general as possible, we\n quantify over _all_ [natlist]s, not just those that result from an\n application of [rev]. This should seem natural, because the truth\n of the goal clearly doesn't depend on the list having been\n reversed. Moreover, it is easier to prove the more general\n property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons *)\n simpl. rewrite -> app_length.\n simpl. rewrite -> IHl'. rewrite plus_comm.\n reflexivity.\nQed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n _Theorem_: For all lists [l1] and [l2],\n [length (l1 ++ l2) = length l1 + length l2].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n length ([] ++ l2) = length [] + length l2,\n\n which follows directly from the definitions of\n [length], [++], and [plus].\n\n - Next, suppose [l1 = n::l1'], with\n\n length (l1' ++ l2) = length l1' + length l2.\n\n We must show\n\n length ((n::l1') ++ l2) = length (n::l1') + length l2.\n\n This follows directly from the definitions of [length] and [++]\n together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n\n length (rev []) = length [],\n\n which follows directly from the definitions of [length]\n and [rev].\n\n - Next, suppose [l = n::l'], with\n\n length (rev l') = length l'.\n\n We must show\n\n length (rev (n :: l')) = length (n :: l').\n\n By the definition of [rev], this follows from\n\n length ((rev l') ++ [n]) = S (length l')\n\n which, by the previous lemma, is the same as\n\n length (rev l') + length [n] = S (length l').\n\n This follows directly from the induction hypothesis and the\n definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n After reading a couple like this, we might find it easier to\n follow proofs that give fewer details (which we can easily work\n out in our own minds or on scratch paper if necessary) and just\n highlight the non-obvious steps. In this more compressed style,\n the above proof might look like this: *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n for any [l], by a straightforward induction on [l]. The main\n property again follows by induction on [l], using the observation\n together with the induction hypothesis in the case where [l =\n n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and how similar the\n proof at hand is to ones that they will already be familiar with.\n The more pedantic style is a good default for our present\n purposes. *)\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, e.g., using [rewrite]. But in order to refer to a\n theorem, we need to know its name! Indeed, it is often hard even\n to remember what theorems have been proven, much less what they\n are called.\n\n Coq's [Search] command is quite helpful with this. Let's say\n you've forgotten the name of a theorem about [rev]. The command\n [Search rev] will cause Coq to display a list of all theorems\n involving [rev]. *)\n\nSearch rev.\n\n(** Or say you've forgotten the name of the theorem showing that plus\n is commutative. You can use a pattern to search for all theorems\n involving the equality of two additions. *)\n\nSearch (_ + _ = _ + _).\n\n(** You'll see a lot of results there, nearly all of them from the\n standard library. To restrict the results, you can search inside\n a particular module: *)\n\nSearch (_ + _ = _ + _) inside Induction.\n\n(** You can also make the search more precise by using variables in\n the search pattern instead of wildcards: *)\n\nSearch (?x + ?y = ?y + ?x).\n\n(** The question mark in front of the variable is needed to indicate\n that it is a variable in the search pattern, rather than a\n variable that is expected to be in scope currently. *)\n\n(** Keep [Search] in mind as you do the following exercises and\n throughout the rest of the book; it can save you a lot of time!\n\n Your IDE likely has its own functionality to help with searching.\n For example, in ProofGeneral, you can run [Search] with [C-c C-a\n C-a], and paste its response into your buffer with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars, standard (list_exercises) \n\n More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n l ++ [] = l.\nProof.\n induction l as [| l' n' IHl'].\n - simpl. reflexivity.\n - simpl. rewrite -> IHl'. reflexivity.\nQed.\n\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n intros. induction l1 as [| l1' n1' IHl1'].\n - simpl. rewrite -> app_nil_r. reflexivity.\n - simpl. rewrite -> IHl1'. rewrite -> app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n induction l as [| n' l' IHl'].\n - reflexivity.\n - simpl. Search (rev (?a ++ ?b)).\n rewrite -> rev_app_distr. rewrite IHl'. simpl. reflexivity.\nQed.\n\n(** There is a short solution to the next one. If you find yourself\n getting tangled up, step back and try to look for a simpler\n way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n (* We can also inductin l1 *)\n intros. simpl. rewrite -> app_assoc. rewrite -> app_assoc. reflexivity.\nQed.\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros.\n induction l1 as [| n1' l1' IHl1'].\n - simpl. reflexivity.\n - Search ((_ ::_) ++ _).\n destruct n1'.\n + simpl. rewrite -> IHl1'. reflexivity.\n + simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (eqblist)\n\n Fill in the definition of [eqblist], which compares\n lists of numbers for equality. Prove that [eqblist l l]\n yields [true] for every list [l]. *)\n\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n match l1,l2 with\n | [], [] => true\n (* && or match *)\n | a::ta , b::tb => match eqb a b with\n | true => eqblist ta tb\n | false => false\n end\n | _ , _ =>false\n end.\n\nExample test_eqblist1 :\n (eqblist nil nil = true).\nProof.\n simpl. reflexivity.\nQed.\n\nExample test_eqblist2 :\n eqblist [1;2;3] [1;2;3] = true.\nProof.\n simpl. reflexivity.\nQed.\n\nExample test_eqblist3 :\n eqblist [1;2;3] [1;2;4] = false.\nProof.\n simpl. reflexivity.\nQed.\n\nTheorem eqblist_refl : forall l:natlist,\n true = eqblist l l.\nProof.\n intros. induction l as [| n' l' IHl'].\n - simpl. reflexivity.\n - simpl.\n rewrite <- eqb_refl.\n rewrite <- IHl'.\n reflexivity.\nQed.\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** Here are a couple of little theorems to prove about your\n definitions about bags above. *)\n\n(** **** Exercise: 1 star, standard (count_member_nonzero) *)\n\nTheorem count_member_nonzero : forall (s : bag),\n 1 <=? (count 1 (1 :: s)) = true.\nProof.\n intros. simpl.\n reflexivity.\nQed.\n\n(** [] *)\n\n(** The following lemma about [leb] might help you in the next exercise. *)\n\nTheorem leb_n_Sn : forall n,\n n <=? (S n) = true.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* 0 *)\n simpl. reflexivity.\n - (* S n' *)\n simpl. rewrite IHn'. reflexivity. Qed.\n\n(** Before doing the next exercise, make sure you've filled in the\n definition of [remove_one] above. *)\n(** **** Exercise: 3 stars, advanced (remove_does_not_increase_count) *)\nTheorem remove_does_not_increase_count: forall (s : bag),\n (count 0 (remove_one 0 s)) <=? (count 0 s) = true.\nProof.\n induction s as [| n' s' IHs'].\n - simpl. reflexivity.\n - simpl. destruct n'.\n + simpl. rewrite -> leb_n_Sn. reflexivity.\n + simpl. rewrite -> IHs'. reflexivity.\nQed.\n\n(** [] *)\n(** **** Exercise: 3 stars, standard, optional (bag_count_sum) \n\n Write down an interesting theorem [bag_count_sum] about bags\n involving the functions [count] and [sum], and prove it using\n Coq. (You may find that the difficulty of the proof depends on\n how you defined [count]!) *)\nPrint count.\nTheorem bag_count_sum : forall(b1 b2: bag) (n : nat),\n count n (sum b1 b2) = (count n b1) + (count n b2).\nProof.\n intros.\n induction b1.\n - simpl. reflexivity.\n - simpl. rewrite -> IHb1.\n (* use case_eqn or destruct *)\n destruct (n0 =? n) as []eqn:?.\n (* case_eq (n0 =? n). *)\n + simpl. reflexivity.\n + reflexivity. \nQed.\n\n(** **** Exercise: 4 stars, advanced (rev_injective) \n\n Prove that the [rev] function is injective. There is a hard way\n and an easy way to do this. *)\n\nTheorem rev_a_rb : forall (l1 l2: natlist),\n l1 = rev l2 -> rev l1 = l2.\nProof.\n intros. rewrite H. rewrite -> rev_involutive. reflexivity.\nQed.\n\n(* Well... After I have proved it... not use it *)\nTheorem rev_injective_helper : forall (l1 l2 : natlist),\n l1 = l2 -> rev l1 = rev l2.\nProof.\n intros.\n destruct l1.\n - rewrite -> H. reflexivity.\n - rewrite -> H. reflexivity.\nQed.\n\n\n\n\nTheorem rev_injective : forall (l1 l2 : natlist),\n rev l1 = rev l2 -> l1 = l2.\nProof.\n intros.\n rewrite <- rev_involutive.\n rewrite <- H.\n rewrite -> rev_involutive.\n reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n element of some list. If we give it type [nat -> natlist -> nat],\n then we'll have to choose some number to return when the list is\n too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n match l with\n | nil => 42\n | a :: l' => match n with\n | 0 => a\n | S n' => nth_bad l' n'\n end\n end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n can't tell whether that value actually appears on the input\n without further processing. A better alternative is to change the\n return type of [nth_bad] to include an error value as a possible\n outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n | Some (n : nat)\n | None.\n\n(** We can then change the above definition of [nth_bad] to\n return [None] when the list is too short and [Some a] when the\n list has enough members and [a] appears at position [n]. We call\n this new function [nth_error] to indicate that it may result in an\n error. As we see here, constructors of inductive definitions can\n be capitalized. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => match n with\n | O => Some a\n | S n' => nth_error l' n'\n end\n end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n examples are elided. Click on a box if you want to see one.)\n\n This example is also an opportunity to introduce one more small\n feature of Coq's programming language: conditional\n expressions... *)\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => if n =? O then Some a\n else nth_error' l' (pred n)\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the [bool] type\n is not built in, Coq actually supports conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars, standard (hd_error) \n\n Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_error (l : natlist) : natoption :=\n match l with\n | nil => None\n | h :: t => Some h\n end.\n\nExample test_hd_error1 : hd_error [] = None.\nProof. simpl. reflexivity. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. simpl. reflexivity. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. simpl. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (option_elim_hd) \n\n This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_error l).\nProof.\n intros.\n destruct l.\n - simpl. reflexivity.\n - simpl. reflexivity.\nQed.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n Coq, here is a simple _partial map_ data type, analogous to the\n map or dictionary data structures found in most programming\n languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n | Id (n : nat).\n\n(** Internally, an [id] is just a number. Introducing a separate type\n by wrapping each nat with the tag [Id] makes definitions more\n readable and gives us more flexibility. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition eqb_id (x1 x2 : id) :=\n match x1, x2 with\n | Id n1, Id n2 => n1 =? n2\n end.\n\n(** **** Exercise: 1 star, standard (eqb_id_refl) *)\nTheorem eqb_id_refl : forall x, true = eqb_id x x.\nProof.\n intros. destruct x. simpl. rewrite <- eqb_refl. reflexivity.\nQed.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n\nInductive partial_map : Type :=\n | empty\n | record (i : id) (v : nat) (m : partial_map).\n\n(** This declaration can be read: \"There are two ways to construct a\n [partial_map]: either using the constructor [empty] to represent an\n empty partial map, or applying the constructor [record] to\n a key, a value, and an existing [partial_map] to construct a\n [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n partial map by shadowing it with a new one (or simply adds a new\n entry if the given key is not already present). *)\n\nDefinition update (d : partial_map)\n (x : id) (value : nat)\n : partial_map :=\n record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n key. It returns [None] if the key was not found and [Some val] if\n the key was associated with [val]. If the same key is mapped to\n multiple values, [find] will return the first one it\n encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n match d with\n | empty => None\n | record y v d' => if eqb_id x y\n then Some v\n else find x d'\n end.\n\n(** **** Exercise: 1 star, standard (update_eq) *)\nTheorem update_eq :\n forall (d : partial_map) (x : id) (v: nat),\n find x (update d x v) = Some v.\nProof.\n intros. simpl. Search \"eqb_id\". rewrite <- eqb_id_refl. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard (update_neq) *)\nTheorem update_neq :\n forall (d : partial_map) (x y : id) (o: nat),\n eqb_id x y = false -> find x (update d y o) = find x d.\nProof.\n intros. simpl. rewrite H. reflexivity.\nQed.\n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 stars, standard, optional (baz_num_elts) \n\n Consider the following inductive definition: *)\nInductive baz : Type :=\n | Baz1 (x : baz)\n | Baz2 (y : baz) (b : bool).\n\n(** How _many_ elements does the type [baz] have? (Explain in words,\n in a comment.) *)\n\n(* FILL IN HERE *)\n\n(* Infinity *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_baz_num_elts : option (nat*string) := None.\n(** [] *)\n\n(* 2020-09-09 20:51 *)\n", "meta": {"author": "Edwardzcn", "repo": "ocaml-exercise", "sha": "6df431973ce13f24c6d4ff739f6e6d83fae48656", "save_path": "github-repos/coq/Edwardzcn-ocaml-exercise", "path": "github-repos/coq/Edwardzcn-ocaml-exercise/ocaml-exercise-6df431973ce13f24c6d4ff739f6e6d83fae48656/SoftwareFoundation/lf/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.9407897455234431, "lm_q1q2_score": 0.8651902690952653}} {"text": "Section One.\n\n(* Source: http://www-sop.inria.fr/members/Enrico.Tassi/coqws15/coq-master1-1-exercises.v *)\n\nRequire Import Bool Arith List.\n\n(* 1. Define a recursive function that takes as input a list of numbers\n and returns the product of these numbers, *)\n\nFixpoint prodlist (ns : list nat) := unit.\n\nCompute prodlist nil.\nCompute prodlist (0 :: 3 :: 7 :: nil).\nCompute prodlist (3 :: 4 :: 2 :: nil).\n\n(* 2. Define a recursive function that takes a list of numbers and\n returns true if and only if this list contains the number 0.\n Hint: pattern match on both the list and the elements of the list. *)\n\nFixpoint has_a_0 (ns : list nat) := unit.\n\nCompute has_a_0 (2 :: 3 :: 0 :: 7 :: nil).\nCompute has_a_0 nil.\nCompute has_a_0 (3 :: 5 :: nil).\n\n(* 3. Define a recursive function that takes as input two numbers and\n returns true if and only if these two numbers are the same natural\n number (such a function already exists in the Coq libraries\n (function beq_nat, but how would you define such a function), using\n only pattern-matching and recursion. *)\n\nFixpoint beq (n m : nat) := unit.\n\nCompute beq 4 5.\nCompute beq 7 7.\n\n(* 4. Define a recursive function that takes a number n and a number\n a as input and returns a list of numbers containing n elements\n that are all a. *)\n\nFixpoint mklist (n a : nat) := unit.\n\nCompute mklist 3 0.\n\n(* 5. Define a function that takes a number n and a number a and returns\n the list of n elements a ::a + 1:: · · · ::a + n:: nil. *)\n\nFixpoint mklist1 (n a : nat) := unit.\n\nCompute mklist1 3 0.\n\n(* 6. Define a function that takes as input a natural number and returns\n an element of option nat containing the predecessor if it exists or\n None if the input is 0. *)\n\nFixpoint pred (n : nat) := unit.\n\nCompute pred 0.\nCompute pred 6.\n\n(* 7. Define a recursive function that takes as input a list of numbers\n and returns the length of this list. *)\n\nFixpoint length (ns : list nat) := unit.\n\nCompute length nil.\nCompute length (2 :: 3 :: nil).\n\n(* 8. Can you write a recursive function values that takes as input a\n function f of type nat -> nat, an initial value a of type nat\n and a count n of type nat and produces the list\n a :: f a :: f (f a) :: ... *)\n\nFixpoint fold (f : nat -> nat) (a : nat) (n : nat) := unit.\n\nCompute fold (fun x : nat => x) 0 5.\nCompute fold (fun x : nat => x + 1) 3 4.\nCompute fold S 3 4.\n\n(* 9. To every natural number, we can associate the list of its digits\n from right to left. For instance, 239 should be associated to the list\n 9::3::2::nil. We also consider that 0 can be mapped to nil. If l is\n such a list, we can consider the successor of a list of digits.\n For instance, the successor of 9::3::2::nil is 0::4::2.\n Define the algorithm on lists of natural numbers that computes the\n successor of that list. *)\n\nFixpoint lsucc (ns : list nat) : list nat := nil.\n\nCompute lsucc (3 :: 9 :: 1 :: nil).\nCompute lsucc (9 :: 3 :: 1 :: nil).\nCompute lsucc (9 :: 9 :: 1 :: nil).\nCompute lsucc nil.\nCompute lsucc (9 :: nil).\n\n(* 10. Assuming that lsuc is the function defined at the previous\n exercise, define the function nat_digits that maps every natural\n number to the corresponding list of digits (naive solutions are\n welcome, as long as they run). *)\n\nFixpoint nat_digits_aux (n : nat) := unit.\n\nDefinition nat_digits (n : nat) := unit.\n\nCompute nat_digits 2990.\n\n(* 11. In the same context as the previous two exercises, define a function\n value that maps every list of digits to the natural number it\n represents. Thus, value (9::3::2::nil) should compute to 239. *)\n\nFixpoint value (ns : list nat) := unit.\n\nCompute value (0 :: 2 :: 3 :: 4 :: nil).\n\n(* 12. In the same context as the previous exercises, define a function\n licit that tells whether a list of integers corresponds to the digits\n of natural number: no digit should be larger than 9. For instance,\n licit (9::3::2::0::nil) should compute to true and licit (239::nil)\n should compute to false. *)\n\nFixpoint licit (ns : list nat) := unit.\n\nCompute licit (9 :: 3 :: 2 :: 0 :: nil).\nCompute licit (239 :: nil).\n\n(* 13. In the same context as the previous exercises, define functions\n to add two lists of digits so that the result represents the sum of\n the numbers represented by the lists of digits. In other words\n addl (7::2::nil) (5::3::nil) should return 2::6::nil\n (Hint: you should implement the algorithm you learned in elementary\n school for adding numbers). *)\n\nFixpoint addl (ns ms : list nat) := unit.\n\nCompute addl (7 :: 2 :: nil) (5 :: 3 :: nil).\n\n(* 14. In the same context as the previous exercises, define a function\n for multiplying a list by a small natural number (by successive\n additions) and then a function mull for multiplying two lists of\n digits. *)\n\nFixpoint mulln (n : nat) (ms : list nat) := unit.\n\nCompute mulln 3 (2 :: 1 :: nil).\n\nFixpoint mull (ns ms : list nat) := unit.\n\nCompute 14 * 13.\nCompute mull (4 :: 1 :: nil) (3 :: 1 :: nil).\nCompute 437 * 25.\nCompute mull (7 :: 3 :: 4 :: nil) (5 :: 2 :: nil).\nCompute 97 * 75.\nCompute mull (7 :: 9 :: nil) (5 :: 7 :: nil).\n\nEnd One.\n", "meta": {"author": "vlopezj", "repo": "coq-course", "sha": "b7f3c44d73859ddad49a6edbfd3430283bcc251f", "save_path": "github-repos/coq/vlopezj-coq-course", "path": "github-repos/coq/vlopezj-coq-course/coq-course-b7f3c44d73859ddad49a6edbfd3430283bcc251f/exercises/1/ex1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.9230391611283337, "lm_q1q2_score": 0.8650822626969995}} {"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\nRequire Export Basics.\n\nModule NatList. \n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as in this definition: *)\n\nInductive natprod : Type :=\n pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\n(** We can construct an element of [natprod] like this: *)\n\nCheck (pair 3 5).\n\n(** *** *)\n\n(** Here are two simple function definitions for extracting the\n first and second components of a pair. (The definitions also\n illustrate how to do pattern matching on two-argument\n constructors.) *)\n\nDefinition fst (p : natprod) : nat := \n match p with\n | pair x y => x\n end.\nDefinition snd (p : natprod) : nat := \n match p with\n | pair x y => y\n end.\n\nEval compute in (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** *** *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this notation is provided as part of the standard\n library): *)\n\nEval compute in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat := \n match p with\n | (x,y) => x\n end.\nDefinition snd' (p : natprod) : nat := \n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod := \n match p with\n | (x,y) => (y,x)\n end.\n\n(** *** *)\n\n(** Let's try and prove a few simple facts about pairs. If we\n state the lemmas in a particular (and slightly peculiar) way, we\n can prove them with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** Note that [reflexivity] is not enough if we state the lemma in a\n more natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** *** *)\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct].\n\n Notice that, unlike for [nat]s, [destruct] doesn't generate an\n extra subgoal here. That's because [natprod]s can only be\n constructed in one way. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n describe the type of _lists_ of numbers like this: \"A list is\n either the empty list or else a pair of a number and another\n list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n\n(** *** *)\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following two declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n but in case you are interested, here is roughly what's going on.\n\n The [right associativity] annotation tells Coq how to parenthesize\n expressions involving several uses of [::] so that, for example,\n the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\nNotation \"x + y\" := (plus x y) \n (at level 50, left associativity).\n The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (By the way, it's worth noting in passing that expressions like \"[1\n + 2 :: [3]]\" can be a little confusing when you read them in a .v\n file. The inner brackets, around 3, indicate a list, but the outer\n brackets, which are invisible in the HTML rendering, are there to\n instruct the \"coqdoc\" tool that the bracketed part should be\n displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(** *** Repeat *)\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist := \n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(** *** Length *)\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat := \n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(** *** Append *)\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist := \n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y) \n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\"). \n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\n(** *** Head (with default) and Tail *)\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil \n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | nil => nil\n | 0 :: t => (nonzeros t)\n | h :: t => [h] ++ (nonzeros t)\n end.\n\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist := \n match l with\n | nil => nil\n | h :: t =>\n match (oddb h) with\n | true => h :: (oddmembers t)\n | false => oddmembers t\n end\n end.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\n Proof. simpl. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n length(oddmembers l).\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\n Proof. simpl. reflexivity. Qed.\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\n Proof. simpl. reflexivity. Qed.\nExample test_countoddmembers3: countoddmembers nil = 0.\n Proof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l2 with\n | nil => l1\n | h :: t => \n match l1 with\n | nil => l2\n | a :: b => a :: h :: (alternate b t)\n end\n end.\n\n\nExample test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n Proof. simpl. reflexivity. Qed.\nExample test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].\n Proof. simpl. reflexivity. Qed.\nExample test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].\n Proof. simpl. reflexivity. Qed.\nExample test_alternate4: alternate [] [20;30] = [20;30].\n Proof. simpl. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n multiple times instead of just once. One reasonable\n implementation of bags is to represent a bag of numbers as a\n list. *)\n\nDefinition bag := natlist. \n\n(** **** Exercise: 3 stars (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat := \n match s with\n | nil => 0\n | h :: t => if beq_nat v h then S(count v t) else (count v t)\n end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\n Proof. simpl. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\n Proof. simpl. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := \n alternate.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\n Proof. simpl. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := \n v :: s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\n Proof. simpl. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\n Proof. simpl. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool := \n negb(beq_nat (count v s) 0).\n\nExample test_member1: member 1 [1;4;1] = true.\n Proof. reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\n Proof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n (* When remove_one is applied to a bag without the number to remove,\n it should return the same bag unchanged. *)\n match s with\n | nil => nil\n | h :: t => if beq_nat v h then t else h ::(remove_one v t)\n end.\n\nExample test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n Proof. simpl. reflexivity. Qed.\nExample test_remove_one2: count 5 (remove_one 5 [2;1;4;1]) = 0.\n Proof. simpl. reflexivity. Qed.\nExample test_remove_one3: count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n Proof. simpl. reflexivity. Qed.\nExample test_remove_one4: count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n Proof. simpl. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | h :: t => if beq_nat v h then (remove_all v t) else h :: (remove_all v t)\n end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n Proof. simpl. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\n Proof. simpl. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n Proof. simpl. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n Proof. simpl. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n match s1 with\n | nil => true\n | h :: t => if (member h s2) then (subset t (remove_one h s2)) else false\n end.\n \n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\n Proof. simpl. reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\n Proof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (bag_theorem) *)\n(** Write down an interesting theorem about bags involving the\n functions [count] and [add], and prove it. Note that, since this\n problem is somewhat open-ended, it's possible that you may come up\n with a theorem which is true, but whose proof requires techniques\n you haven't learned yet. Feel free to ask for help if you get\n stuck! *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match position\n in the definition of [app], allowing the match itself to be\n simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n l'\". \n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proofs will not get you very far! It is\n very important to work through the details of each one, using Coq\n and thinking about what each step of the proof achieves.\n Otherwise it is more or less guaranteed that the exercises will\n make no sense. *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n perhaps a little less familiar than standard natural number\n induction, but the basic idea is equally simple. Each [Inductive]\n declaration defines a set of data values that can be built up from\n the declared constructors: a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to a number; a\n list can be either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two things together establish the\n truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist, \n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3). \nProof.\n intros l1 l2 l3. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons n l1'\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n static written document -- it is easy to see what's going on if\n you are reading the proof in an interactive Coq session and you\n can see the current goal and context at each point, but this state\n is not visible in the written-down parts of the Coq proof. So a\n natural-language proof -- one written for human readers -- will\n need to include more explicit signposts; in particular, it will\n help the reader stay oriented if we remind them exactly what the\n induction hypothesis is in the second case. *)\n\n(** *** Informal version *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3], \n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n (the induction hypothesis). We must show\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]] \n By the definition of [++], this follows from\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n which is immediate from the induction hypothesis. []\n*)\n\n(** *** Another example *)\n(**\n Here is a similar example to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist, \n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n\n(** *** Reversing a list *)\n(** For a slightly more involved example of an inductive proof\n over lists, suppose we define a \"cons on the right\" function\n [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist := \n match l with\n | nil => [v]\n | h :: t => h :: (snoc t v)\n end.\n\n(** ... and use it to define a list-reversing function [rev]\n like this: *)\n\nFixpoint rev (l:natlist) : natlist := \n match l with\n | nil => nil\n | h :: t => snoc (rev t) h\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** *** Proofs about reverse *)\n(** Now let's prove some more list theorems using our newly\n defined [snoc] and [rev]. For something a little more challenging\n than the inductive proofs we've seen so far, let's prove that\n reversing a list does not change its length. Our first attempt at\n this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n :: l'\".\n (* This is the tricky case. Let's begin as usual \n by simplifying. *)\n simpl. \n (* Now we seem to be stuck: the goal is an equality \n involving [snoc], but we don't have any equations \n in either the immediate context or the global \n environment that have anything to do with [snoc]! \n\n We can make a little progress by using the IH to \n rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation about [snoc] that would have\n enabled us to make progress and prove it as a separate lemma. \n*)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n length (snoc l n) = S (length l).\nProof.\n intros n l. induction l as [| n' l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n' l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed. \n\n(**\n Note that we make the lemma as _general_ as possible: in particular,\n we quantify over _all_ [natlist]s, not just those that result\n from an application of [rev]. This should seem natural, \n because the truth of the goal clearly doesn't depend on \n the list having been reversed. Moreover, it is much easier\n to prove the more general property. \n*)\n \n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons\".\n simpl. rewrite -> length_snoc. \n rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems: \n\n _Theorem_: For all numbers [n] and lists [l],\n [length (snoc l n) = S (length l)].\n \n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (snoc [] n) = S (length []),\n which follows directly from the definitions of\n [length] and [snoc].\n\n - Next, suppose [l = n'::l'], with\n length (snoc l' n) = S (length l').\n We must show\n length (snoc (n' :: l') n) = S (length (n' :: l')).\n By the definitions of [length] and [snoc], this\n follows from\n S (length (snoc l' n)) = S (S (length l')),\n]] \n which is immediate from the induction hypothesis. [] *)\n \n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n \n _Proof_: By induction on [l]. \n\n - First, suppose [l = []]. We must show\n length (rev []) = length [],\n which follows directly from the definitions of [length] \n and [rev].\n \n - Next, suppose [l = n::l'], with\n length (rev l') = length l'.\n We must show\n length (rev (n :: l')) = length (n :: l').\n By the definition of [rev], this follows from\n length (snoc (rev l') n) = S (length l')\n which, by the previous lemma, is the same as\n S (length (rev l')) = S (length l').\n This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n and pedantic. After the first few, we might find it easier to\n follow proofs that give fewer details (since we can easily work\n them out in our own minds or on scratch paper if necessary) and\n just highlight the non-obvious steps. In this more compressed\n style, the above proof might look more like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that\n length (snoc l n) = S (length l)\n for any [l]. This follows by a straightforward induction on [l].\n The main property now follows by another straightforward\n induction on [l], using the observation together with the\n induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and on how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for\n present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, using [rewrite], and later we will see other ways\n of reusing previous theorems. But in order to refer to a theorem,\n we need to know its name, and remembering the names of all the\n theorems we might ever want to use can become quite difficult! It\n is often hard even to remember what theorems have been proven,\n much less what they are named.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following to\n see a list of theorems that we have proved about [rev]: *)\n\n(* SearchAbout rev. *)\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the course; it can save you a lot of time! *)\n\n(** Also, if you are using ProofGeneral, you can run [SearchAbout]\n with [C-c C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist, \n l ++ [] = l. \nProof.\n (* FILL IN HERE *) Admitted.\n\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** There is a short solution to the next exercise. If you find\n yourself getting tangled up, step back and try to look for a\n simpler way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n snoc l n = l ++ [n].\nProof.\n (* FILL IN HERE *) Admitted.\n\n\nTheorem distr_rev : forall l1 l2 : natlist,\n rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n (* FILL IN HERE *) admit.\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\n (* FILL IN HERE *) Admitted.\nExample test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\n (* FILL IN HERE *) Admitted.\nExample test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.\n (* FILL IN HERE *) Admitted.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 2 stars (list_design) *)\n(** Design exercise: \n - Write down a non-trivial theorem involving [cons]\n ([::]), [snoc], and [app] ([++]). \n - Prove it. *) \n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n definitions about bags earlier in the file. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** The following lemma about [ble_nat] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n ble_nat n (S n) = true.\nProof.\n intros n. induction n as [| n'].\n Case \"0\". \n simpl. reflexivity.\n Case \"S n'\".\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *) \n(** Write down an interesting theorem about bags involving the\n functions [count] and [sum], and prove it.*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nThere is a hard way and an easy way to solve this exercise.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n\n(** One use of [natoption] is as a way of returning \"error\n codes\" from functions. For example, suppose we want to write a\n function that returns the [n]th element of some list. If we give\n it type [nat -> natlist -> nat], then we'll have to return some\n number when the list is too short! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with \n | true => a \n | false => index_bad (pred n) l' \n end\n end.\n\n(** *** *)\n(** On the other hand, if we give it type [nat -> natlist ->\n natoption], then we can return [None] when the list is too short\n and [Some a] when the list has enough members and [a] appears at\n position [n]. *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption. \n\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => match beq_nat n O with \n | true => Some a\n | false => index (pred n) l' \n end\n end.\n\nExample test_index1 : index 0 [4;5;6;7] = Some 4.\nProof. reflexivity. Qed.\nExample test_index2 : index 3 [4;5;6;7] = Some 7.\nProof. reflexivity. Qed.\nExample test_index3 : index 10 [4;5;6;7] = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n small feature of Coq's programming language: conditional\n expressions... *)\n\n(** *** *)\n\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => if beq_nat n O then Some a else index' (pred n) l'\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_opt (l : natlist) : natoption :=\n (* FILL IN HERE *) admit.\n\nExample test_hd_opt1 : hd_opt [] = None.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_opt l).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Dictionaries *)\n\n(** As a final illustration of how fundamental data structures\n can be defined in Coq, here is the declaration of a simple\n [dictionary] data type, using numbers for both the keys and the\n values stored under these keys. (That is, a dictionary represents\n a finite map from numbers to numbers.) *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n | empty : dictionary \n | record : nat -> nat -> dictionary -> dictionary. \n\n(** This declaration can be read: \"There are two ways to construct a\n [dictionary]: either using the constructor [empty] to represent an\n empty dictionary, or by applying the constructor [record] to\n a key, a value, and an existing [dictionary] to construct a\n [dictionary] with an additional key to value mapping.\" *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n (record key value d).\n\n(** Here is a function [find] that searches a [dictionary] for a\n given key. It evaluates evaluates to [None] if the key was not\n found and [Some val] if the key was mapped to [val] in the\n dictionary. If the same key is mapped to multiple values, [find]\n will return the first one it finds. *)\n\nFixpoint find (key : nat) (d : dictionary) : natoption := \n match d with \n | empty => None\n | record k v d' => if (beq_nat key k) \n then (Some v) \n else (find key d')\n end.\n\n\n\n(** **** Exercise: 1 star (dictionary_invariant1) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n (find k (insert k v d)) = Some v.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),\n beq_nat m n = false -> find m d = find m (insert n o d).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\nEnd Dictionary.\n\nEnd NatList.\n\n(* $Date: 2014-01-28 13:19:45 -0500 (Tue, 28 Jan 2014) $ *)\n\n", "meta": {"author": "Morales-BA", "repo": "csSoftFound_moralesb", "sha": "088c0f5780132649652593fdc3bee4766f011588", "save_path": "github-repos/coq/Morales-BA-csSoftFound_moralesb", "path": "github-repos/coq/Morales-BA-csSoftFound_moralesb/csSoftFound_moralesb-088c0f5780132649652593fdc3bee4766f011588/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.921921828955667, "lm_q1q2_score": 0.864877010218641}} {"text": "From LF Require Export Basics.\n\n\n(*\n * Let's prove that n + 0 = n for all n:nat.\n *)\nTheorem add_0_r : forall n:nat, n + 0 = n.\nProof. intros n. induction n as [|n' IHn'].\n- reflexivity.\n- simpl. rewrite -> IHn'. reflexivity.\nQed. \n\nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof. intros n m. induction n as [ | n' IHn'].\n- reflexivity.\n- simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nCheck add_0_r.\n\nTheorem add_comm : forall n m : nat,\n n + m = m + n.\nProof. intros n m. induction n as [|n' IHn'].\n- simpl. rewrite -> add_0_r. reflexivity.\n- simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.\nQed.\n(* ################################################################# *)\n(** * Proofs Within Proofs *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0+n = n).\n - simpl. reflexivity.\n - rewrite -> H. reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * TODO for you: Please practice Induction.v *)\n\n(* ################################################################# *)\n(** * Inductive Data Structures: Working with structured data *)\n\nInductive natprod : Type :=\n | pair (n1 n2 : nat).\n\n(** This declaration can be read: \"The one and only way to\n construct a pair of numbers of type natprod is by applying \n the constructor [pair] to two arguments of type [nat].\" *)\n\nCheck (pair 3 5) : natprod.\n\n(** Here are simple functions for extracting the first and\n second components of a pair. *)\n\nDefinition fst (p : natprod) : nat :=\n match p with\n | pair x y => x\n end.\n\nDefinition snd (p : natprod) : nat :=\n match p with\n | pair x y => y\n end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Convenient notation for pairs. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in pattern\n matches. *)\n\nCompute (fst (3,5)).\n\nDefinition swap_pair (p : natprod) : natprod :=\n match p with\n | (x,y) => (y,x)\n end.\n\n\nTheorem surjective_pairing : forall (p : natprod),\np = (fst p, snd p).\nProof. intros p. induction p.\nsimpl. reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\nInductive natlist : Type :=\n | nil\n | cons (n : nat) (l : natlist).\n\nCheck nil.\n\nCheck cons 3 (cons 2 nil).\n\nNotation \"x :: l\" := (cons x l)\n (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nCheck 1::2::nil.", "meta": {"author": "csci5535", "repo": "csci5535.github.io", "sha": "591108aa7b2c74a2a53f55cc80ad47ff7dd0f26d", "save_path": "github-repos/coq/csci5535-csci5535.github.io", "path": "github-repos/coq/csci5535-csci5535.github.io/csci5535.github.io-591108aa7b2c74a2a53f55cc80ad47ff7dd0f26d/coq/MyInduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.9425067228145365, "lm_q1q2_score": 0.8645639149920723}} {"text": "(** * MoreLogic: More on Logic in Coq *)\n\nRequire Export \"Prop\".\n\n(* ############################################################ *)\n(** * Existential Quantification *)\n\n(** Another critical logical connective is _existential\n quantification_. We can express it with the following\n definition: *)\n\nInductive ex (X:Type) (P : X->Prop) : Prop :=\n ex_intro : forall (witness:X), P witness -> ex X P.\n\n(** That is, [ex] is a family of propositions indexed by a type [X]\n and a property [P] over [X]. In order to give evidence for the\n assertion \"there exists an [x] for which the property [P] holds\"\n we must actually name a _witness_ -- a specific value [x] -- and\n then give evidence for [P x], i.e., evidence that [x] has the\n property [P].\n\n*)\n\n\n(** *** *)\n(** Coq's [Notation] facility can be used to introduce more\n familiar notation for writing existentially quantified\n propositions, exactly parallel to the built-in syntax for\n universally quantified propositions. Instead of writing [ex nat\n ev] to express the proposition that there exists some number that\n is even, for example, we can write [exists x:nat, ev x]. (It is\n not necessary to understand exactly how the [Notation] definition\n works.) *)\n\nNotation \"'exists' x , p\" := (ex _ (fun x => p))\n (at level 200, x ident, right associativity) : type_scope.\nNotation \"'exists' x : X , p\" := (ex _ (fun x:X => p))\n (at level 200, x ident, right associativity) : type_scope.\n\n(** *** *)\n(** We can use the usual set of tactics for\n manipulating existentials. For example, to prove an\n existential, we can [apply] the constructor [ex_intro]. Since the\n premise of [ex_intro] involves a variable ([witness]) that does\n not appear in its conclusion, we need to explicitly give its value\n when we use [apply]. *)\n\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof.\n apply ex_intro with (witness:=2).\n reflexivity. Qed.\n\n(** Note that we have to explicitly give the witness. *)\n\n(** *** *)\n(** Or, instead of writing [apply ex_intro with (witness:=e)] all the\n time, we can use the convenient shorthand [exists e], which means\n the same thing. *)\n\nExample exists_example_1' : exists n, n + (n * n) = 6.\nProof.\n exists 2.\n reflexivity. Qed.\n\n(** *** *)\n(** Conversely, if we have an existential hypothesis in the\n context, we can eliminate it with [inversion]. Note the use\n of the [as...] pattern to name the variable that Coq\n introduces to name the witness value and get evidence that\n the hypothesis holds for the witness. (If we don't\n explicitly choose one, Coq will just call it [witness], which\n makes proofs confusing.) *)\n\nTheorem exists_example_2 : forall n,\n (exists m, n = 4 + m) ->\n (exists o, n = 2 + o).\nProof.\n intros n H.\n inversion H as [m Hm].\n exists (2 + m).\n apply Hm. Qed.\n\n\n(** Here is another example of how to work with existentials. *)\nLemma exists_example_3 :\n exists (n:nat), even n /\\ beautiful n.\nProof.\n(* WORKED IN CLASS *)\n exists 8.\n split.\n unfold even. simpl. reflexivity.\n apply b_sum with (n:=3) (m:=5).\n apply b_3. apply b_5.\nQed.\n\n(** **** Exercise: 1 star, optional (english_exists) *)\n(** In English, what does the proposition\n ex nat (fun n => beautiful (S n))\n]]\n mean? *)\n\n(* FILL IN HERE *)\n\n(*\n*)\n(** **** Exercise: 1 star (dist_not_exists) *)\n(** Prove that \"[P] holds for all [x]\" implies \"there is no [x] for\n which [P] does not hold.\" *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (not_exists_dist) *)\n(** (The other direction of this theorem requires the classical \"law\n of the excluded middle\".) *)\n\nTheorem not_exists_dist :\n excluded_middle ->\n forall (X:Type) (P : X -> Prop),\n ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (dist_exists_or) *)\n(** Prove that existential quantification distributes over\n disjunction. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Evidence-Carrying Booleans *)\n\n(** So far we've seen two different forms of equality predicates:\n [eq], which produces a [Prop], and the type-specific forms, like\n [beq_nat], that produce [boolean] values. The former are more\n convenient to reason about, but we've relied on the latter to let\n us use equality tests in _computations_. While it is\n straightforward to write lemmas (e.g. [beq_nat_true] and\n [beq_nat_false]) that connect the two forms, using these lemmas\n quickly gets tedious. *)\n\n(** *** *)\n(** It turns out that we can get the benefits of both forms at once by\n using a construct called [sumbool]. *)\n\nInductive sumbool (A B : Prop) : Set :=\n | left : A -> sumbool A B\n | right : B -> sumbool A B.\n\nNotation \"{ A } + { B }\" := (sumbool A B) : type_scope.\n\n(** Think of [sumbool] as being like the [boolean] type, but instead\n of its values being just [true] and [false], they carry _evidence_\n of truth or falsity. This means that when we [destruct] them, we\n are left with the relevant evidence as a hypothesis -- just as\n with [or]. (In fact, the definition of [sumbool] is almost the\n same as for [or]. The only difference is that values of [sumbool]\n are declared to be in [Set] rather than in [Prop]; this is a\n technical distinction that allows us to compute with them.) *)\n\n(** *** *)\n\n(** Here's how we can define a [sumbool] for equality on [nat]s *)\n\nTheorem eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.\nProof.\n (* WORKED IN CLASS *)\n intros n.\n induction n as [|n'].\n Case \"n = 0\".\n intros m.\n destruct m as [|m'].\n SCase \"m = 0\".\n left. reflexivity.\n SCase \"m = S m'\".\n right. intros contra. inversion contra.\n Case \"n = S n'\".\n intros m.\n destruct m as [|m'].\n SCase \"m = 0\".\n right. intros contra. inversion contra.\n SCase \"m = S m'\".\n destruct IHn' with (m := m') as [eq | neq].\n left. apply f_equal. apply eq.\n right. intros Heq. inversion Heq as [Heq']. apply neq. apply Heq'.\nDefined.\n\n(** Read as a theorem, this says that equality on [nat]s is decidable:\n that is, given two [nat] values, we can always produce either\n evidence that they are equal or evidence that they are not. Read\n computationally, [eq_nat_dec] takes two [nat] values and returns a\n [sumbool] constructed with [left] if they are equal and [right] if\n they are not; this result can be tested with a [match] or, better,\n with an [if-then-else], just like a regular [boolean]. (Notice\n that we ended this proof with [Defined] rather than [Qed]. The\n only difference this makes is that the proof becomes\n _transparent_, meaning that its definition is available when Coq\n tries to do reductions, which is important for the computational\n interpretation.) *)\n\n(** *** *)\n(** Here's a simple example illustrating the advantages of the\n [sumbool] form. *)\n\nDefinition override' {X: Type} (f: nat->X) (k:nat) (x:X) : nat->X:=\n fun (k':nat) => if eq_nat_dec k k' then x else f k'.\n\nTheorem override_same' : forall (X:Type) x1 k1 k2 (f : nat->X),\n f k1 = x1 ->\n (override' f k1 x1) k2 = f k2.\nProof.\n intros X x1 k1 k2 f. intros Hx1.\n unfold override'.\n destruct (eq_nat_dec k1 k2). (* observe what appears as a hypothesis *)\n Case \"k1 = k2\".\n rewrite <- e.\n symmetry. apply Hx1.\n Case \"k1 <> k2\".\n reflexivity. Qed.\n\n(** Compare this to the more laborious proof (in MoreCoq.v) for the\n version of [override] defined using [beq_nat], where we had to use\n the auxiliary lemma [beq_nat_true] to convert a fact about\n booleans to a Prop. *)\n\n(** **** Exercise: 1 star (override_shadow') *)\nTheorem override_shadow' : forall (X:Type) x1 x2 k1 k2 (f : nat->X),\n (override' (override' f k1 x2) k1 x1) k2 = (override' f k1 x1) k2.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (all_forallb) *)\n(** Inductively define a property [all] of lists, parameterized by a\n type [X] and a property [P : X -> Prop], such that [all X P l]\n asserts that [P] is true for every element of the list [l]. *)\n\nInductive all (X : Type) (P : X -> Prop) : list X -> Prop :=\n (* FILL IN HERE *)\n.\n\n(** Recall the function [forallb], from the exercise\n [forall_exists_challenge] in chapter [Poly]: *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n match l with\n | [] => true\n | x :: l' => andb (test x) (forallb test l')\n end.\n\n(** Using the property [all], write down a specification for [forallb],\n and prove that it satisfies the specification. Try to make your\n specification as precise as possible.\n\n Are there any important properties of the function [forallb] which\n are not captured by your specification? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (filter_challenge) *)\n(** One of the main purposes of Coq is to prove that programs match\n their specifications. To this end, let's prove that our\n definition of [filter] matches a specification. Here is the\n specification, written out informally in English.\n\n Suppose we have a set [X], a function [test: X->bool], and a list\n [l] of type [list X]. Suppose further that [l] is an \"in-order\n merge\" of two lists, [l1] and [l2], such that every item in [l1]\n satisfies [test] and no item in [l2] satisfies test. Then [filter\n test l = l1].\n\n A list [l] is an \"in-order merge\" of [l1] and [l2] if it contains\n all the same elements as [l1] and [l2], in the same order as [l1]\n and [l2], but possibly interleaved. For example,\n [1,4,6,2,3]\n is an in-order merge of\n [1,6,2]\n and\n [4,3].\n Your job is to translate this specification into a Coq theorem and\n prove it. (Hint: You'll need to begin by defining what it means\n for one list to be a merge of two others. Do this with an\n inductive relation, not a [Fixpoint].) *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced, optional (filter_challenge_2) *)\n(** A different way to formally characterize the behavior of [filter]\n goes like this: Among all subsequences of [l] with the property\n that [test] evaluates to [true] on all their members, [filter test\n l] is the longest. Express this claim formally and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (no_repeats) *)\n(** The following inductively defined proposition... *)\n\nInductive appears_in {X:Type} (a:X) : list X -> Prop :=\n | ai_here : forall l, appears_in a (a::l)\n | ai_later : forall b l, appears_in a l -> appears_in a (b::l).\n\n(** ...gives us a precise way of saying that a value [a] appears at\n least once as a member of a list [l].\n\n Here's a pair of warm-ups about [appears_in].\n*)\n\nLemma appears_in_app : forall (X:Type) (xs ys : list X) (x:X),\n appears_in x (xs ++ ys) -> appears_in x xs \\/ appears_in x ys.\nProof.\n (* FILL IN HERE *) Admitted.\n\nLemma app_appears_in : forall (X:Type) (xs ys : list X) (x:X),\n appears_in x xs \\/ appears_in x ys -> appears_in x (xs ++ ys).\nProof.\n (* FILL IN HERE *) Admitted.\n\n\n(** Now use [appears_in] to define a proposition [disjoint X l1 l2],\n which should be provable exactly when [l1] and [l2] are\n lists (with elements of type X) that have no elements in common. *)\n\n(* FILL IN HERE *)\n\n(** Next, use [appears_in] to define an inductive proposition\n [no_repeats X l], which should be provable exactly when [l] is a\n list (with elements of type [X]) where every member is different\n from every other. For example, [no_repeats nat [1,2,3,4]] and\n [no_repeats bool []] should be provable, while [no_repeats nat\n [1,2,1]] and [no_repeats bool [true,true]] should not be. *)\n\n(* FILL IN HERE *)\n\n(** Finally, state and prove one or more interesting theorems relating\n [disjoint], [no_repeats] and [++] (list append). *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars (nostutter) *)\n(** Formulating inductive definitions of predicates is an important\n skill you'll need in this course. Try to solve this exercise\n without any help at all.\n\n We say that a list of numbers \"stutters\" if it repeats the same\n number consecutively. The predicate \"[nostutter mylist]\" means\n that [mylist] does not stutter. Formulate an inductive definition\n for [nostutter]. (This is different from the [no_repeats]\n predicate in the exercise above; the sequence [1;4;1] repeats but\n does not stutter.) *)\n\nInductive nostutter: list nat -> Prop :=\n (* FILL IN HERE *)\n.\n\n(** Make sure each of these tests succeeds, but you are free\n to change the proof if the given one doesn't work for you.\n Your definition might be different from mine and still correct,\n in which case the examples might need a different proof.\n\n The suggested proofs for the examples (in comments) use a number\n of tactics we haven't talked about, to try to make them robust\n with respect to different possible ways of defining [nostutter].\n You should be able to just uncomment and use them as-is, but if\n you prefer you can also prove each example with more basic\n tactics. *)\n\nExample test_nostutter_1: nostutter [3;1;4;1;5;6].\n(* FILL IN HERE *) Admitted.\n(*\n Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_2: nostutter [].\n(* FILL IN HERE *) Admitted.\n(*\n Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_3: nostutter [5].\n(* FILL IN HERE *) Admitted.\n(*\n Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_4: not (nostutter [3;1;1;4]).\n(* FILL IN HERE *) Admitted.\n(*\n Proof. intro.\n repeat match goal with\n h: nostutter _ |- _ => inversion h; clear h; subst\n end.\n contradiction H1; auto. Qed.\n*)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (pigeonhole principle) *)\n(** The \"pigeonhole principle\" states a basic fact about counting:\n if you distribute more than [n] items into [n] pigeonholes, some\n pigeonhole must contain at least two items. As is often the case,\n this apparently trivial fact about numbers requires non-trivial\n machinery to prove, but we now have enough... *)\n\n(** First a pair of useful lemmas (we already proved these for lists\n of naturals, but not for arbitrary lists). *)\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n length (l1 ++ l2) = length l1 + length l2.\nProof.\n (* FILL IN HERE *) Admitted.\n\nLemma appears_in_app_split : forall (X:Type) (x:X) (l:list X),\n appears_in x l ->\n exists l1, exists l2, l = l1 ++ (x::l2).\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** Now define a predicate [repeats] (analogous to [no_repeats] in the\n exercise above), such that [repeats X l] asserts that [l] contains\n at least one repeated element (of type [X]). *)\n\nInductive repeats {X:Type} : list X -> Prop :=\n (* FILL IN HERE *)\n.\n\n(** Now here's a way to formalize the pigeonhole principle. List [l2]\n represents a list of pigeonhole labels, and list [l1] represents\n the labels assigned to a list of items: if there are more items\n than labels, at least two items must have the same label. This\n proof is much easier if you use the [excluded_middle] hypothesis\n to show that [appears_in] is decidable, i.e. [forall x\n l, (appears_in x l) \\/ ~ (appears_in x l)]. However, it is also\n possible to make the proof go through _without_ assuming that\n [appears_in] is decidable; if you can manage to do this, you will\n not need the [excluded_middle] hypothesis. *)\n\nTheorem pigeonhole_principle: forall (X:Type) (l1 l2:list X),\n excluded_middle ->\n (forall x, appears_in x l1 -> appears_in x l2) ->\n length l2 < length l1 ->\n repeats l1.\nProof.\n intros X l1. induction l1 as [|x l1'].\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* FILL IN HERE *)\n\n\n(** $Date: 2014-12-31 16:01:37 -0500 (Wed, 31 Dec 2014) $ *)\n", "meta": {"author": "ftiasch", "repo": "sf", "sha": "63ed39b75232f93f18f302099dc6c7637dea02ad", "save_path": "github-repos/coq/ftiasch-sf", "path": "github-repos/coq/ftiasch-sf/sf-63ed39b75232f93f18f302099dc6c7637dea02ad/MoreLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012709406662, "lm_q2_score": 0.9136765169496871, "lm_q1q2_score": 0.8641564109596552}} {"text": "Module NatPlayground.\n\n Inductive nat : Type :=\n | O : nat\n | S : nat -> nat.\n\nDefinition pred (n : nat) : nat :=\n match n with\n | O => O\n | S n' => n'\n end.\n\nEnd NatPlayground.\n\nDefinition minustwo ( n : nat ) : nat :=\n match n with\n | O => O\n | S O => O\n | S ( S n') => n'\n end.\n\nFixpoint evenb ( n : nat) : bool :=\n match n with\n | O => true\n | S O => false\n | S (S n') => evenb n'\n end.\n\nDefinition oddb ( n : nat) : bool := negb ( evenb n).\n\nModule NatPlayground2.\n\n Fixpoint plus ( n : nat)( m : nat ) : nat :=\n match n with\n | O => m\n | S n' => S (plus n' m)\n end.\n\n Fixpoint mult ( n m : nat) : nat :=\n match n with\n | O => O\n | S n' => plus m (mult n' m)\n end.\n\n Fixpoint minus ( n m : nat) : nat :=\n match n,m with\n | O , _ => O\n | S _ , O => n\n | S n' , S m' => minus n' m'\n end.\n\n End NatPlayground2.\n\n Fixpoint exp ( base power : nat) : nat :=\n match power with\n | O => S O\n | S p => mult base (exp base p)\n end.\n\n Fixpoint factorial (n:nat) : nat :=\n match n with\n | O => 1\n | S n' => mult n (factorial n')\n end.\n\n Notation \"x + y\" := (plus x y)\n (at level 50, left associativity)\n : nat_scope.\n Notation \"x - y\" := (minus x y)\n (at level 50, left associativity)\n :nat_scope.\n Notation \" x * y\" :=(mult x y)\n (at level 40, left associativity)\n :nat_scope.\n\n Fixpoint beq_nat (n m : nat) :bool :=\n match n with\n | O => match m with\n | O => true\n | S m' => false\n end\n | S n' => match m with\n | O => false\n | S m' => beq_nat n' m'\n end\n end.\n\n Fixpoint leb (n m: nat) : bool :=\n match n with\n | O => true\n | S n' => match m with\n | O => false\n | S m' => leb n' m'\n end\n end.\n\n Example test_leb1: (leb 2 2) = true.\n Proof. simpl. reflexivity. Qed.\n Example test_leb2: (leb 1 4) = true.\n Proof. simpl. reflexivity. Qed.\n Example test_leb3: (leb 5 2) = false.\n Proof. simpl. reflexivity. Qed.\n\n Definition blt_nat (n m: nat) : bool :=\n match (leb n m) with\n | true =>(negb (beq_nat n m))\n | false => false\n end.\n\n Example test_blt_nat1: (blt_nat 2 2) =false.\n Proof. simpl. reflexivity. Qed. \n\n Theorem plus_O_n : forall n : nat, O + n = n.\n Proof.\n intros n. simpl. reflexivity. Qed.\n\n Theorem puls_1_1 : forall n: nat, 1 + n = S n.\n Proof.\n intros n. reflexivity. Qed.\n\n Theorem mult_0_1 : forall n: nat, 0 * n = 0.\n Proof.\n intros n. reflexivity. Qed.\n\n Theorem plus_id_example : forall n m : nat,\n n = m -> n + n = m + m.\n Proof.\n intros n m.\n intros H.\n rewrite -> H.\n reflexivity. Qed.\n\n Theorem plus_id_exercise: forall n m o: nat,\n n = m -> m = o -> n + m = m + o.\n Proof.\n intros n m o.\n intros H.\n rewrite -> H.\n intros H0.\n rewrite -> H0. \n reflexivity. Qed.\n\n Theorem mult_O_plus : forall n m: nat,\n (O + n) * m = n * m.\n Proof.\n intros n m.\n rewrite -> plus_O_n.\n reflexivity. Qed.\n\n Theorem mult_S_1 : forall n m: nat,\n m = S n -> m * (1 + n) = m * m.\n Proof.\n intros n m.\n intros H.\n rewrite -> H.\n reflexivity. Qed.\n\n Theorem plus_1_neq_O : forall n : nat,\n beq_nat ( n + 1) 0 =false.\n Proof.\n intros n. destruct n as [| n'].\n - reflexivity.\n - reflexivity. Qed.\n\n Theorem andb_commutative : forall b c, andb b c = andb c b.\n Proof.\n intros b c. destruct b.\n - destruct c.\n + reflexivity.\n + reflexivity.\n - destruct c.\n + reflexivity.\n + reflexivity.\n Qed.\n\n Theorem andb_true_elim2 : forall b c:bool,\n andb b c = true -> c = true.\n Proof.\n intros [] c.\n - simpl.\n congruence.\n - simpl.\n discriminate.\n Qed.\n \n \n Theorem zero__nbeq_plus_1 : forall n: nat,\n beq_nat 0 (n + 1)=false.\n Proof.\n intros [| n].\n - reflexivity.\n - reflexivity.\n Qed.\n \n (* Fixpoint tmp_rec ( n m : nat) : nat :=\n match n with\n | O => O\n | _ =>\n match m with\n | O => (tmp_rec (n + 1) (m + 1))\n | _ => (tmp_rec (minustwo n) O)\n end \n end. *)\n Theorem identity_fn_applied_twice :\n forall ( f : bool -> bool),\n (forall (x : bool), f x = x) ->\n forall (b : bool), f ( f b) = b.\n Proof.\n intros f x b.\n rewrite -> x.\n rewrite -> x.\n reflexivity.\n Qed.\n \n Theorem negation_fn_applied_twice :\n forall (f :bool -> bool),\n (forall (x : bool), f x = negb x) ->\n forall (b : bool), f ( f b) = b.\n Proof.\n intros f x b.\n rewrite -> x.\n rewrite -> x.\n destruct b.\n - reflexivity.\n - reflexivity.\n Qed.\n\n Theorem andb_eq_orb :\n forall ( b c :bool), (andb b c = orb b c) -> b =c.\n Proof.\n intros [] c.\n - simpl.\n congruence.\n - simpl.\n congruence.\n Qed.\n \n\n \n", "meta": {"author": "Hatsunespica", "repo": "Coq", "sha": "969145e20cb6525d324bd6b5b03cfcb6f7fefa8d", "save_path": "github-repos/coq/Hatsunespica-Coq", "path": "github-repos/coq/Hatsunespica-Coq/Coq-969145e20cb6525d324bd6b5b03cfcb6f7fefa8d/SF/basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.9184802462567087, "lm_q1q2_score": 0.8640967960005673}} {"text": "From mathcomp Require Import all_ssreflect.\n\n\n(** *** Exercise 1 :\n - Prove this statement by induction using big_nat_recr and big_geq\n - alternatively by using big_morph\n*)\n\nLemma sum_mull f (k n : nat) :\n k * (\\sum_(0 <= i < n) f i) = \\sum_(0 <= i < n) (k * f i).\nProof.\n(*D*)(* elim: n => [|n IH]; first by rewrite !big_geq. *)\n(*D*)(* by rewrite !big_nat_recr //= mulnDr IH. *)\n(*D*)by apply: (big_morph (fun n => k * n)) => // x y; rewrite mulnDr.\nQed.\n\n(** *** Exercise 2 :\n - Prove this statement by using big_morph\n*)\n\nLemma sum_mulr f (k n : nat) :\n (\\sum_(0 <= i < n) f i) * k = \\sum_(0 <= i < n) (f i * k).\nProof.\n(*D*)(* elim: n => [|n IH]; first by rewrite !big_geq. *)\n(*D*)(* by rewrite !big_nat_recr //= mulnDl IH. *)\n(*D*)by apply: (big_morph (fun n => n * k)) => // x y; rewrite mulnDl.\nQed.\n\n\n(** *** Exercise 3 :\n - Prove this statement by induction.\n - Relevant lemmas are\n - doubleS odd_double addn0 addnn mulnn\n - big_mkcond big_nat_recr big_geq\n*)\n\nLemma sum_odd n : \\sum_(0 <= i < n.*2 | odd i) i = n ^ 2.\nProof.\n(*D*)elim: n => [|n IHn]; first by rewrite big_geq.\n(*D*)rewrite doubleS big_mkcond 2?big_nat_recr // -big_mkcond /=.\n(*D*)rewrite {}IHn odd_double /= addn0 -addnn -!mulnn.\n(*D*)by rewrite mulSn mulnC mulSn addnA addSn addnC.\nQed.\n\n\n(** *** Exercise 4 :\n - Prove this statement by induction.\n - Relevant lemmas are\n - doubleD muln2 addn2 big_nat_recr big_geq\n*)\n\nLemma sum_gauss n : (\\sum_(0 <= i < n) i).*2 = n * n.-1.\nProof.\n(*D*)elim: n => [|n IH]; first by rewrite big_geq.\n(*D*)rewrite big_nat_recr //= doubleD {}IH.\n(*D*)case: n => [|n /=]; first by rewrite muln0.\n(*D*)by rewrite -muln2 -mulnDr addn2 mulnC.\nQed.\n\n\n(**\n In what follows we are going to mimic the proof of Gauss :\n\n<<\n 1 + 2 + ..... + n.-2 + n.-1\n + n.-1 + n.-2 + + 2 + 1\n\n = n.-1 * n\n>>\n\n**)\n\n\n(** *** Exercise 5 :\n - Prove this statement without induction.\n - Relevant lemma is big_nat_rev\n*)\n\nLemma sum_gauss_rev n : \\sum_(0 <= i < n) (n.-1 - i) = \\sum_(0 <= i < n) i.\nProof.\n(*D*)rewrite [RHS]big_nat_rev /=.\n(*D*)by case: n => //.\nQed.\n\n(** *** Exercise 6 :\n - Prove this statement without induction.\n - Relevant lemma is addnn\n*)\nLemma sum_gauss_double n : (\\sum_(0 <= i < n) i).*2 =\n \\sum_(0 <= i < n) i + \\sum_(0 <= i < n) (n.-1 - i).\nProof.\n(*D*)by rewrite sum_gauss_rev addnn.\nQed.\n\n\n(** *** Exercise 7 :\n - Prove this statement without induction.\n - Relevant lemma are big_split and eq_big_nat\n*)\n\nLemma sum_gaussD n :\n \\sum_(0 <= i < n) i + \\sum_(0 <= i < n) (n.-1 - i) =\n \\sum_(0 <= i < n) n.-1.\nProof.\n(*D*)rewrite -big_split /=.\n(*D*)apply: eq_big_nat => i Hi.\n(*D*)rewrite addnC subnK //.\n(*D*)by case: n Hi.\nQed.\n\n\n(** *** Exercise 8 :\n - Prove this statement without induction.\n - Relevant lemma are sum_nat_const_nat\n*)\n\nLemma sum_gauss_const n k : \\sum_(0 <= i < n) k = n * k.\nProof.\n(*D*)by rewrite sum_nat_const_nat subn0.\nQed.\n\n\n(** *** Exercise 9 :\n - Prove this statement using exercises 5-8\n*)\nLemma sum_gauss_alt1 n : (\\sum_(0 <= i < n) i).*2 = n * n.-1.\nProof.\n(*D*)by rewrite sum_gauss_double sum_gaussD sum_gauss_const.\nQed.\n\n\n(** *** Exercise 10 :\n - Prove this statement directly without using the lemmas\n - defined in exercises 5-9\n*)\n\nLemma sum_gauss_alt2 n : (\\sum_(0 <= i < n) i).*2 = n * n.-1.\nProof.\n(*D*)rewrite -addnn [X in X + _ = _]big_nat_rev -big_split /=.\n(*D*)rewrite -[X in _ = X * _]subn0 -sum_nat_const_nat.\n(*D*)apply: eq_big_nat => i.\n(*D*)by case: n => // n /andP[iP iLn]; rewrite [_ + _]subnK.\nQed.\n\n\n(** *** Now we try to prove the sum of squares.\n\n**)\n\n(** *** We first define the property for a function to be increasing\n**)\n\n\nDefinition fincr f := forall n, f n <= f n.+1.\n\n(** *** Exercise 11 :\n - Prove this statement by induction\n*)\n\nLemma fincrD f m n : fincr f -> f m <= f (n + m).\nProof.\n(*D*)move=> Hf; elim: n => // n H; exact: leq_trans H (Hf _).\nQed.\n\n\n(** *** Exercise 12 :\n - Prove this statement using exercise 11\n - Hint : subnK\n*)\n\nLemma fincr_leq f m n : fincr f -> m <= n -> f m <= f n.\nProof.\n(*D*)by move=> Hf Hn; rewrite -(subnK Hn) fincrD.\nQed.\n\n\n(** *** Exercise 13 :\n - Proof by induction\n - Hints : addnCA subnK fincr_leq big_geq\n*)\n\nLemma sum_consecutive n f :\n fincr f -> f n = \\sum_(0 <= i < n) (f i.+1 - f i) + f 0.\nProof.\n(*D*)move=> Hf.\n(*D*)elim: n => [|n IH]; first by rewrite big_geq.\n(*D*)by rewrite big_nat_recr //= addnAC -IH addnC subnK.\nQed.\n\n\n(** *** Exercise 14 :\n - Proof using the previous lemma\n - Hints : leq_exp2r\n*)\nLemma sum_consecutive_cube n :\n n^3 = \\sum_(0 <= i < n) (i.+1 ^ 3 - i ^ 3).\nProof.\n(*D*)rewrite (sum_consecutive _ (fun i => i ^ 3)) ?addn0 //.\n(*D*)by move=> m; rewrite leq_exp2r.\nQed.\n\n\n(** *** We give the proof of a technical result\n*)\n\nLtac sring :=\n rewrite !(expn1, expnS, =^~mul2n, mulSn, mulnS, addnS, addSn,\n mulnDr, mulnDl, add0n, addn0, muln0, addnA, mulnA);\n do ! congr (S _);\n do ! ((congr (_ + _); [idtac]) || (rewrite [in LHS]addnC ?[in LHS]addnA //)).\n\nLemma succ_cube n : n.+1 ^ 3 = n ^ 3 + (3 * n ^ 2 + 3 * n + 1).\nProof. sring. Qed.\n\n(** *** Exercise 15 :\n - Hints : big_split sum_mull sum_gauss sum_gauss_const\n*)\nLemma sum_sum3 n :\n \\sum_(0 <= i < n) (6 * i ^ 2 + 6 * i + 2) =\n 6 * (\\sum_(0 <= i < n) i ^ 2) + 3 * n * n.-1 + n.*2.\nProof.\n(*D*)rewrite big_split big_split /=.\n(*D*)rewrite -!sum_mull sum_gauss_const.\n(*D*)by rewrite -mulnA -sum_gauss // -mul2n mulnA muln2.\nQed.\n\n\n(** *** Exercise 16 :\n - Hints : big_split sum_mull sum_gauss sum_gauss_const\n*)\nLemma sum_sum4 n :\n (n ^ 3).*2 = 6 * (\\sum_(0 <= i < n) i ^ 2) + 3 * n * n.-1 + n.*2.\nProof.\n(*D*)rewrite sum_consecutive_cube -sum_sum3 -mul2n sum_mull.\n(*D*)apply: eq_big_nat => i Hi.\n(*D*)by rewrite succ_cube addKn 2!mulnDr !mulnA.\nQed.\n\n(** *** Another technical lemma\n*)\n\nLemma sum_tech n : (n ^ 3).*2 = n * n.-1 * n.-1.*2.+1 + 3 * n * n.-1 + n.*2.\nProof. by case: n => //= n1; sring. Qed.\n\n\n(** *** Exercise 17 :\n - Hint : addIn sum_sum4 sum_tech.\n*)\nLemma sum_square n : 6 * (\\sum_(0 <= i < n) i ^ 2) = n * n.-1 * n.-1.*2.+1.\nProof.\n(*D*)apply: (@addIn (3 * n * n.-1 + n.*2)).\n(*D*)by rewrite addnA -sum_sum4 sum_tech !addnA.\nQed.\n\n(** *** Exercise 18 :\n - Prove the theorem directly using only sum_gauss and the tactic sring.\n*)\nLemma sum_square_alt n : 6 * (\\sum_(0 <= i < n) i ^ 2) = n * n.-1 * n.-1.*2.+1.\nProof.\n(*D*)apply: (@addIn (3 * n * n.-1 + n.*2)).\n(*D*)rewrite addnA -[6]/(2 * 3) -!mulnA mul2n (big_morph _ (mulnDr _) (muln0 _)).\n(*D*)rewrite -{1}sum_gauss -doubleMr (big_morph _ (mulnDr _) (muln0 _)).\n(*D*)rewrite -{3}[n]muln1 -{3}[n]subn0 -sum_nat_const_nat.\n(*D*)rewrite -!doubleD -!big_split /=.\n(*D*)rewrite (eq_big_nat _ _ (_ : forall i, _ -> _ = i.+1 ^ 3 - i ^3)) => [|i H]; last first.\n(*D*) rewrite -[LHS](addKn (i ^ 3)); congr (_ - _).\n(*D*) by sring.\n(*D*)apply: etrans (_ : (n^3).*2 = _).\n(*D*) congr (_.*2).\n(*D*) elim: n => [|n IH]; first by rewrite big_geq.\n(*D*) by rewrite big_nat_recr //= IH addnC subnK // leq_exp2r.\n(*D*)by case: n => //= n1; sring.\nQed.\n", "meta": {"author": "gares", "repo": "COQWS18", "sha": "2d438b94357d4be0baf47808db111214f08db467", "save_path": "github-repos/coq/gares-COQWS18", "path": "github-repos/coq/gares-COQWS18/COQWS18-2d438b94357d4be0baf47808db111214f08db467/exercise7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.9304582583867416, "lm_q1q2_score": 0.8638456411650068}} {"text": "(** * Lists: Working with Structured Data *)\n\nAdd LoadPath \"/Users/Harry/Documents/Fall 2016/CSC 495/Software Foundations - Code\".\nRequire Export Induction.\nModule NatList.\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as here: *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is one way to construct\n a pair of numbers: by applying the constructor [pair] to two\n arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n(** Here are two simple functions for extracting the first and\n second components of a pair. The definitions also illustrate how\n to do pattern matching on two-argument constructors. *)\n\nDefinition fst (p : natprod) : nat :=\n match p with\n | pair x y => x\n end.\n\nDefinition snd (p : natprod) : nat :=\n match p with\n | pair x y => y\n end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this works because the pair notation is actually\n provided as part of the standard library): *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n match p with\n | (x,y) => x\n end.\n\nDefinition snd' (p : natprod) : nat :=\n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n match p with\n | (x,y) => (y,x)\n end.\n\n(** Let's try to prove a few simple facts about pairs.\n\n If we state things in a particular (and slightly peculiar) way, we\n can complete proofs with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** Notice that, unlike its behavior with [nat]s, [destruct]\n doesn't generate an extra subgoal here. That's because [natprod]s\n can only be constructed in one way. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p.\n destruct p.\n simpl.\n reflexivity.\nQed.\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n type of _lists_ of numbers like this: \"A list is either the empty\n list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n declarations, but in case you are interested, here is roughly\n what's going on. The [right associativity] annotation tells Coq\n how to parenthesize expressions involving several uses of [::] so\n that, for example, the next three declarations mean exactly the\n same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\n\n Notation \"x + y\" := (plus x y)\n (at level 50, left associativity).\n\n the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when \n you read them in a .v file. The inner brackets, around 3, indicate \n a list, but the outer brackets, which are invisible in the HTML \n rendering, are there to instruct the \"coqdoc\" tool that the bracketed \n part should be displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head (with default) and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\").\n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, recommended (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | nil => nil\n | 0 :: tl => nonzeros tl\n | hd :: tl => hd:: nonzeros tl\n end.\n\nExample test_nonzeros:\n nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof.\n reflexivity.\nQed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | nil => nil\n | n :: nx => match oddb n with\n | true => n :: oddmembers nx\n | false => oddmembers nx\n end\n end.\n\nExample test_oddmembers:\n oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof.\n simpl.\n reflexivity.\nQed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n match l with\n | nil => 0\n | hd ::tl => match (oddb hd) with\n | true => S (countoddmembers tl)\n | false => countoddmembers tl\n end\n end.\n\nExample test_countoddmembers1:\n countoddmembers [1;0;3;1;4;5] = 4.\nProof.\n simpl.\n reflexivity.\nQed.\n\nExample test_countoddmembers2:\n countoddmembers [0;2;4] = 0.\nProof.\n simpl.\n reflexivity.\nQed.\n\nExample test_countoddmembers3:\n countoddmembers nil = 0.\nProof.\n simpl.\n reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l1 with\n | [] => l2\n | hd1::tl1 => match l2 with\n | [] => l1\n | hd2 :: tl2 => hd1 :: hd2 :: (alternate tl1 tl2)\n end\n end.\nExample test_alternate1:\n alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof.\n simpl.\n reflexivity.\nQed.\n\nExample test_alternate2:\n alternate [1] [4;5;6] = [1;4;5;6].\nProof.\n simpl.\n reflexivity.\nQed.\n\nExample test_alternate3:\n alternate [1;2;3] [4] = [1;4;2;3].\nProof.\n simpl.\n reflexivity.\nQed.\n\nExample test_alternate4:\n alternate [] [20;30] = [20;30].\nProof.\n simpl.\n reflexivity.\nQed.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n can appear multiple times rather than just once. One possible\n implementation is to represent a bag of numbers as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, recommended (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat :=\n match s with\n | [] => 0\n | s :: sIn => \n match (beq_nat s v) with\n |true => count v sIn + 1 \n |false => count v sIn\n end\n end.\n \n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof.\n reflexivity.\nQed.\n\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof.\n reflexivity.\nQed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag :=\napp.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof.\n reflexivity.\nQed.\n\nDefinition add (v:nat) (s:bag) : bag :=\napp s [v].\n\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof.\n reflexivity.\nQed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof.\n reflexivity.\nQed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n match count v s with\n | 0 => false\n | s => true\n end.\n\nExample test_member1: member 1 [1;4;1] = true.\nProof.\n reflexivity.\nQed.\n\nExample test_member2: member 2 [1;4;1] = false.\nProof.\n reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with\n | [] => []\n | h::t => if (beq_nat h v) then (remove_all v t) else h::(remove_all v t)\n end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n (* FILL IN HERE *) Admitted.\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n (* When remove_one is applied to a bag without the number to remove,\n it should return the same bag unchanged. *)\n match s with\n | nil => nil\n | h :: t => match beq_nat h v with\n |true => remove_all v t\n |false => h :: remove_all v t \n end\n end.\n\nExample test_remove_one1:\n count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\n\nExample test_remove_one2:\n count 5 (remove_one 5 [2;1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\n\nExample test_remove_one3:\n count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n (* FILL IN HERE *) Admitted.\n\nExample test_remove_one4:\n count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n (* FILL IN HERE *) Admitted.\n\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n match s1 with \n |nil => true\n |h :: t => match beq_nat 0 (count h s2) with\n |true => false\n |false => subset t (remove_one h s1)\n end\n end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\n (* FILL IN HERE *) Admitted.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (bag_theorem) *)\n(** Write down an interesting theorem [bag_theorem] about bags\n involving the functions [count] and [add], and prove it. For\n this, replace the [admit] command below with the statement of your\n theorem. Note that, since this problem is somewhat open-ended,\n it's possible that you may come up with a theorem which is true,\n but whose proof requires techniques you haven't learned yet. Feel\n free to ask for help if you get stuck! *)\n\nTheorem bag_theorem :\n (* FILL IN HERE *) admit.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match\n \"scrutinee\" in the definition of [app], allowing the match itself\n to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons n l' *)\n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n It is important to work through the details of each one, using Coq\n and thinking about what each step achieves. Otherwise it is more\n or less guaranteed that the exercises will make no sense when you\n get to them. 'Nuff said. *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n little less familiar than standard natural number induction, but\n the idea is equally simple. Each [Inductive] declaration defines\n a set of data values that can be built up using the declared\n constructors: a boolean can be either [true] or [false]; a number\n can be either [O] or [S] applied to another number; a list can be\n either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two arguments together establish\n the truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons n l1' *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n [as...] clause provided to the [induction] tactic gives a name to\n the induction hypothesis corresponding to the smaller list [l1']\n in the [cons] case. Once again, this Coq proof is not especially\n illuminating as a static written document -- it is easy to see\n what's going on if you are reading the proof in an interactive Coq\n session and you can see the current goal and context at each\n point, but this state is not visible in the written-down parts of\n the Coq proof. So a natural-language proof -- one written for\n human readers -- will need to include more explicit signposts; in\n particular, it will help the reader stay oriented if we remind\n them exactly what the induction hypothesis is in the second\n case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n (the induction hypothesis). We must show\n\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n By the definition of [++], this follows from\n\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n which is immediate from the induction hypothesis. [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a list *)\n\n(** For a slightly more involved example of inductive proof over\n lists, suppose we use [app] to define a list-reversing function\n [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => rev t ++ [h]\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Proofs about reverse *)\n\n(** Now let's prove some theorems about our newly defined [rev].\n For something a bit more challenging than what we've seen, let's\n prove that reversing a list does not change its length. Our first\n attempt gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = [] *)\n reflexivity.\n - (* l = n :: l' *)\n (* This is the tricky case. Let's begin as usual\n by simplifying. *)\n simpl.\n (* Now we seem to be stuck: the goal is an equality\n involving [++], but we don't have any useful equations\n in either the immediate context or in the global\n environment! We can make a little progress by using\n the IH to rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n would have enabled us to make progress and prove it as a separate\n lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Note that, to make the lemma as general as possible, we\n quantify over _all_ [natlist]s, not just those that result from an\n application of [rev]. This should seem natural, because the truth\n of the goal clearly doesn't depend on the list having been\n reversed. Moreover, it is easier to prove the more general\n property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons *)\n simpl. rewrite -> app_length, plus_comm.\n rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n _Theorem_: For all lists [l1] and [l2],\n [length (l1 ++ l2) = length l1 + length l2].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n length ([] ++ l2) = length [] + length l2,\n\n which follows directly from the definitions of\n [length] and [++].\n\n - Next, suppose [l1 = n::l1'], with\n\n length (l1' ++ l2) = length l1' + length l2.\n\n We must show\n\n length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n This follows directly from the definitions of [length] and [++]\n together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n\n length (rev []) = length [],\n\n which follows directly from the definitions of [length]\n and [rev].\n\n - Next, suppose [l = n::l'], with\n\n length (rev l') = length l'.\n\n We must show\n\n length (rev (n :: l')) = length (n :: l').\n\n By the definition of [rev], this follows from\n\n length ((rev l') ++ [n]) = S (length l')\n\n which, by the previous lemma, is the same as\n\n length (rev l') + length [n] = S (length l').\n\n This follows directly from the induction hypothesis and the\n definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n After the first few, we might find it easier to follow proofs that\n give fewer details (which can easily work out in our own minds or\n on scratch paper if necessary) and just highlight the non-obvious\n steps. In this more compressed style, the above proof might look\n like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n for any [l] (this follows by a straightforward induction on [l]).\n The main property again follows by induction on [l], using the\n observation together with the induction hypothesis in the case\n where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for our\n present purposes. *)\n\n(* ================================================================= *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, e.g., using [rewrite]. But in order to refer to a\n theorem, we need to know its name! Indeed, it is often hard even\n to remember what theorems have been proven, much less what they\n are called.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following line \n to see a list of theorems that we have proved about [rev]: *)\n\n SearchAbout rev.\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the book; it can save you a lot of time!\n\n If you are using ProofGeneral, you can run [SearchAbout] with [C-c\n C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n l ++ [] = l.\nProof.\n intro l.\n induction l.\n - simpl. reflexivity.\n - simpl. rewrite -> IHl. simpl. reflexivity. \nQed.\n\n SearchAbout rev.\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\nAdmitted.\n(** There is a short solution to the next one. If you find yourself\n getting tangled up, step back and try to look for a simpler\n way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n\nAdmitted.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros l1 l2.\n induction l1 as [| n l1'].\n - reflexivity. \n - destruct n as [| n']. simpl. rewrite -> IHl1'. reflexivity. simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\nmatch l1 with\n| nil => match l2 with\n| nil => true\n| x => false\nend\n| v1 :: r1 => match l2 with\n| nil => false\n| v2 :: r2 => if beq_nat v1 v2 then beq_natlist r1 r2\nelse false\nend\nend.\n\nExample test_beq_natlist1 :\n (beq_natlist nil nil = true).\nProof. \n reflexivity.\nQed.\n\nExample test_beq_natlist2 :\n beq_natlist [1;2;3] [1;2;3] = true.\nProof. \n reflexivity.\nQed.\n\nExample test_beq_natlist3 :\n beq_natlist [1;2;3] [1;2;4] = false.\nProof. \n reflexivity.\nQed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\nAdmitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n definitions about bags earlier in the file. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n leb 1 (count 1 (1 :: s)) = true.\nProof.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The following lemma about [leb] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n leb n (S n) = true.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* 0 *)\n simpl. reflexivity.\n - (* S n' *)\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *)\n(** Write down an interesting theorem [bag_count_sum] about bags\n involving the functions [count] and [sum], and prove it.*)\n (* FILL IN HERE *)\n(** [] *)\n\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective -- that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\n(There is a hard way and an easy way to do this.) *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n element of some list. If we give it type [nat -> natlist -> nat],\n then we'll have to choose some number to return when the list is\n too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with\n | true => a\n | false => nth_bad l' (pred n)\n end\n end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n can't tell whether that value actually appears on the input\n without further processing. A better alternative is to change the\n return type of [nth_bad] to include an error value as a possible\n outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption.\n\n(** We can then change the above definition of [nth_bad] to\n return [None] when the list is too short and [Some a] when the\n list has enough members and [a] appears at position [n]. We call\n this new function [nth_error] to indicate that it may result in an\n error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => match beq_nat n O with\n | true => Some a\n | false => nth_error l' (pred n)\n end\n end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n examples are elided. Click on a box if you want to see one.)\n\n This example is also an opportunity to introduce one more small\n feature of Coq's programming language: conditional\n expressions... *)\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => if beq_nat n O then Some a\n else nth_error' l' (pred n)\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_error) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_error (l : natlist) : natoption :=\n match l with \n | [] => None\n | h :: t => Some h\n end.\n\nExample test_hd_error1 : hd_error [] = None.\nProof. \nreflexivity. \nQed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. \nreflexivity. \nQed.\n\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. \nreflexivity. \nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_error l).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n Coq, here is a simple _partial map_ data type, analogous to the\n map or dictionary data structures found in most programming\n languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n | Id : nat -> id.\n\n(** Internally, an [id] is just a number. Introducing a separate type\n by wrapping each nat with the tag [Id] makes definitions more\n readable and gives us the flexibility to change representations\n later if we wish.\n\n We'll also need an equality test for [id]s: *)\n\nDefinition beq_id x1 x2 :=\n match x1, x2 with\n | Id n1, Id n2 => beq_nat n1 n2\n end.\n\n\n(** **** Exercise: 1 star (beq_id_refl) *) \nSearchAbout beq_nat.\n\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n intros x.\n induction x.\n - simpl. rewrite <- beq_nat_refl. reflexivity. \nQed.\n\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nImport NatList.\n \nInductive partial_map : Type :=\n | empty : partial_map\n | record : id -> nat -> partial_map -> partial_map.\n\n(** This declaration can be read: \"There are two ways to construct a\n [partial_map]: either using the constructor [empty] to represent an\n empty partial map, or by applying the constructor [record] to\n a key, a value, and an existing [partial_map] to construct a\n [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n partial map (or adds a new entry if the given key is not already\n present). *)\n\nDefinition update (d : partial_map)\n (key : id) (value : nat)\n : partial_map :=\n record key value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n key. It returns [None] if the key was not found and [Some val] if\n the key was associated with [val]. If the same key is mapped to\n multiple values, [find] will return the first one it\n encounters. *)\n\nFixpoint find (key : id) (d : partial_map) : natoption :=\n match d with\n | empty => None\n | record k v d' => if beq_id key k\n then Some v\n else find key d'\n end.\n\n(** **** Exercise: 1 star (update_eq) *) \n(*SearchAbout beq_id *)\nSearchAbout beq_nat.\n\nTheorem update_eq :\n forall (d : partial_map) (k : id) (v: nat),\n find k (update d k v) = Some v.\nProof.\n intros. \n - simpl. rewrite <- beq_id_refl. reflexivity. \nQed.\n\n(** **** Exercise: 1 star (update_neq) *)\nTheorem update_neq :\n forall (d : partial_map) (m n : id) (o: nat),\n beq_id m n = false -> find m (update d n o) = find m d.\nProof.\n intros. \n - simpl. rewrite -> H. reflexivity.\nQed.\n(** [] *)\n\nEnd PartialMap.\n\n(** **** Exercise: 2 stars (baz_num_elts) *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n | Baz1 : baz -> baz\n | Baz2 : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have? (Answer in English\n or the natural language of your choice.)\n\nAnswer: 0\n*)\n(** [] *)\n\n(** $Date: 2016-06-01 15:34:59 -0400 (Wed, 01 Jun 2016) $ *)\n\n", "meta": {"author": "hpbrown92", "repo": "Coq-Solutions", "sha": "2467e185261bfe2dc043b2a49e353c8a9217b75e", "save_path": "github-repos/coq/hpbrown92-Coq-Solutions", "path": "github-repos/coq/hpbrown92-Coq-Solutions/Coq-Solutions-2467e185261bfe2dc043b2a49e353c8a9217b75e/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.9314625017359052, "lm_q1q2_score": 0.8638041391209706}} {"text": "Require Export Basics.\n\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *) reflexivity.\n - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity. Qed.\n\nTheorem minus_diag : forall n,\n minus n n = 0.\nProof.\n (* WORKED IN CLASS *)\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n simpl. reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n intros n. induction n as [|n' IHn'].\n reflexivity.\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof.\n intros n m. induction n as [| n' IHn'].\n simpl. reflexivity.\n simpl. rewrite <- IHn'. reflexivity. Qed.\n\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros n m. induction n as [| n' IHn'].\n simpl. rewrite <- plus_n_O. reflexivity.\n simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity. \nQed.\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n' IHn'].\n simpl. reflexivity.\n simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n intros n. induction n as [|n' IHn'].\n reflexivity.\n simpl.\n rewrite -> IHn'.\n rewrite <- plus_n_Sm. \n reflexivity.\nQed.\n\n(* Proofs Within Proofs *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n). { reflexivity. }\n rewrite -> H.\n reflexivity. \nQed.\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n assert (H: (n + m) = (m + n)). { rewrite <- plus_comm. reflexivity. }\n rewrite <- H.\n reflexivity.\nQed.\n\nTheorem plus_swap : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n assert (H1: n + (m + p) = (n + m) + p). { rewrite <- plus_assoc. reflexivity. }\n rewrite -> H1.\n assert (H2: m + (n + p) = (m + n) + p). { rewrite <- plus_assoc. reflexivity. }\n rewrite -> H2.\n assert (H3: m + n = n + m). { rewrite <- plus_comm. reflexivity. }\n rewrite <- H3. reflexivity.\nQed.\n\nLemma mult_n_zero : forall n : nat,\n n * 0 = 0 * n.\nProof.\n intros n. induction n as [|n' IHn'].\n reflexivity.\n simpl. rewrite -> IHn'. simpl. reflexivity.\n\nQed.\n\nLemma mult_m_plus_Sn_eq_mn: forall m n : nat,\n m * S n = m + m * n.\nProof.\n intros n m. induction n as [|n' IHn'].\n simpl. reflexivity.\n simpl. rewrite -> IHn'. rewrite <- plus_swap. reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\n intros m n. induction n as [|n' IHn'].\n rewrite -> mult_n_zero. reflexivity.\n simpl. rewrite <- IHn'. rewrite <- mult_m_plus_Sn_eq_mn. reflexivity.\nQed.\n \nFixpoint beq_nat (n m : nat) : bool :=\n match n with\n | O => match m with\n | O => true\n | S m' => false\n end\n | S n' => match m with\n | O => false\n | S m' => beq_nat n' m'\n end\n end.\n \nTheorem beq_nat_refl : forall n : nat,\n true = beq_nat n n.\nProof.\n intros n. induction n as [|n' IHn'].\n reflexivity.\n simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem plus_swap' : forall n m p : nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n assert (H1: n + (m + p) = (n + m) + p). { rewrite <- plus_assoc. reflexivity. }\n rewrite -> H1.\n assert (H2: m + (n + p) = (m + n) + p). { rewrite <- plus_assoc. reflexivity. }\n rewrite -> H2.\n replace (m + n) with (n + m). reflexivity.\n rewrite <- plus_comm. reflexivity.\nQed.\n", "meta": {"author": "avatar29A", "repo": "SoftwareFoundationSolutions", "sha": "c8f6ab5a6a6ead61668ee800e49e578f303bf473", "save_path": "github-repos/coq/avatar29A-SoftwareFoundationSolutions", "path": "github-repos/coq/avatar29A-SoftwareFoundationSolutions/SoftwareFoundationSolutions-c8f6ab5a6a6ead61668ee800e49e578f303bf473/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.9173026516730629, "lm_q1q2_score": 0.863781857365874}} {"text": "Require Import PeanoNat.\n\n(* Algorithm from\n * \n *)\nFixpoint modexp' m b e c :=\n match e with\n | 0 => c mod m\n | S e' => modexp' m b e' ((b * c) mod m)\n end.\nDefinition modexp m b e := modexp' m b e 1.\n\nLemma modexp'_correct : forall m b e c, m <> 0 -> b <> 0 ->\n modexp' m b e c = (b ^ e * c) mod m.\nProof.\n intros m b e.\n induction e; intros.\n - cbn.\n now rewrite Nat.add_0_r.\n - cbn.\n rewrite IHe; auto.\n rewrite Nat.mul_mod_idemp_r; auto.\n now rewrite Nat.mul_assoc, (Nat.mul_comm _ b).\nQed.\n\nLemma modexp_correct : forall m b e, m <> 0 -> b <> 0 ->\n modexp m b e = (b ^ e) mod m.\nProof.\n intros.\n unfold modexp.\n rewrite modexp'_correct; auto.\n now rewrite Nat.mul_1_r.\nQed.\n", "meta": {"author": "mgrabovsky", "repo": "fm-notes", "sha": "6c38cee5a4390c4543d6a404bd88909f3116bafe", "save_path": "github-repos/coq/mgrabovsky-fm-notes", "path": "github-repos/coq/mgrabovsky-fm-notes/fm-notes-6c38cee5a4390c4543d6a404bd88909f3116bafe/sketches/modexp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013548, "lm_q2_score": 0.9059898184796792, "lm_q1q2_score": 0.8636574828982089}} {"text": "Module NatNameSpace.\n\nInductive nat : Type :=\n | O : nat\n | S : nat -> nat.\n\nDefinition pred (n : nat) : nat :=\n match n with\n | O => O\n | S n' => n'\n end.\n\nInductive bin_nat : Type :=\n | b : bin_nat\n | b0 : bin_nat -> bin_nat\n | b1 : bin_nat -> bin_nat.\n\nEnd NatNameSpace.\n\nCheck (S (S (S O))).\n(* ===> 3 : nat *)\n\nDefinition minustwo (n : nat) : nat :=\n match n with\n | O => O\n | S O => O\n | S (S n') => n'\n end.\n\nCompute (minustwo 4).\nCheck S.\nCheck pred.\nCheck minustwo.\n\nInductive bool : Type :=\n| true : bool\n| false : bool.\n\nFixpoint evenb (n : nat) : bool :=\n match n with\n | O => true\n | S O => false\n | S (S n') => evenb n'\n end.\n\nDefinition negb (b : bool) : bool :=\n match b with\n | true => false\n | false => true\n end.\n\nDefinition oddb (n : nat) : bool := negb (evenb n).\n\nExample test_oddb1 : oddb 1 = true.\nProof. simpl. reflexivity. Qed.\nExample test_oddb2 : oddb 4 = false.\nProof. simpl. reflexivity. Qed.\n\nModule NatNameSpace2.\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n match n with\n | O => m\n | S n' => S (plus n' m)\n end.\nCompute (plus 3 2).\n \nFixpoint mult (n m : nat) : nat :=\n match n with\n | O => O\n | S n' => plus m (mult n' m)\n end.\nExample test_mult1 : (mult 3 3) = 9.\nProof. simpl. reflexivity. Qed.\n\nFixpoint minus (n m : nat) : nat :=\n match n, m with\n | O , _ => O\n | S _ , O => n\n | S n' , S m' => minus n' m'\n end.\nExample test_minus1: (minus 2 1) = 1.\nProof. simpl. reflexivity. Qed.\nEnd NatNameSpace2.\n\nFixpoint exp (base power: nat) : nat :=\n match power with\n | O => S O\n | S p => mult base (exp base p)\n end.\nExample test_exp1: (exp 9 0) = 1.\nProof. simpl. reflexivity. Qed.\nExample test_exp2: (exp 9 3) = 729.\nProof. simpl. reflexivity. Qed.\n\nFixpoint fibo (n: nat) : nat :=\n match n with\n | O => 1\n | S O => 1\n | S n' => (fibo (minus n' 1)) + (fibo n')\n end.\nExample test_fibo1: (fibo 0) = 1.\nProof. simpl. reflexivity. Qed.\nExample test_fibo2: (fibo 1) = 1.\nProof. simpl. reflexivity. Qed.\nExample test_fibo3: (fibo 2) = 2.\nProof. simpl. reflexivity. Qed.\n\nFixpoint fact (n: nat) : nat :=\n match n with\n | O => 1\n | S n' => mult (S n') (fact n')\n end.\nExample test_fact1: (fact 0) = 1.\nProof. simpl. reflexivity. Qed.\nExample test_fact2: (fact 1) = 1.\nProof. simpl. reflexivity. Qed.\nExample test_fact3: (fact 5) = 120.\nProof. simpl. reflexivity. Qed.\n\nFixpoint nat_iseq (n m: nat) : bool :=\n match n with\n | O => match m with\n | O => true\n | S m' => false\n end\n | S n' => match m with\n | O => false\n | S m' => nat_iseq n' m'\n end\n end.\nExample test_nat_iseq1: (nat_iseq 1 1) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nat_iseq2: (nat_iseq 4 0) = false.\nProof. simpl. reflexivity. Qed.\nExample test_nat_iseq3: (nat_iseq 4 5) = false.\nProof. simpl. reflexivity. Qed.\n\nFixpoint nat_leq (n m: nat) : bool :=\n match n with\n | O => true\n | S n' => match m with\n | O => false\n | S m' => nat_leq n' m'\n end\n end.\n\nFixpoint nat_lt (n m: nat) : bool :=\n match n with\n | O => match m with\n | O => false\n | S m' => true\n end\n | S n' => match m with\n | O => false\n | S m' => nat_lt n' m'\n end\n end.\nExample test_nat_lt1: (nat_lt 0 1) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nat_lt2: (nat_lt 2 3) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nat_lt3: (nat_lt 1 1) = false.\nProof. simpl. reflexivity. Qed.\nExample test_nat_lt4: (nat_lt 1 0) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition nat_lt2 (n m: nat) : bool := negb (nat_leq m n).\nExample test_nat_lt21: (nat_lt 0 1) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nat_lt22: (nat_lt 2 3) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nat_lt23: (nat_lt 1 1) = false.\nProof. simpl. reflexivity. Qed.\nExample test_nat_lt24: (nat_lt 1 0) = false.\nProof. simpl. reflexivity. Qed.", "meta": {"author": "JacobFeiWang", "repo": "CoqProgram", "sha": "73c300d4483942b508a258eb7c64b7f1f1aa517b", "save_path": "github-repos/coq/JacobFeiWang-CoqProgram", "path": "github-repos/coq/JacobFeiWang-CoqProgram/CoqProgram-73c300d4483942b508a258eb7c64b7f1f1aa517b/CoqEx2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370535, "lm_q2_score": 0.9032941988938414, "lm_q1q2_score": 0.8635324078295027}} {"text": "Require Export BasicsThales.\n\nTheorem plus_n_O_firsttry : forall n:nat,\n n = n + 0.\n\nProof.\n intros n.\n simpl. (* Does nothing! *)\nAbort.\n\nTheorem plus_n_O_secondtry : forall n:nat,\n n = n + 0.\nProof.\n intros n. destruct n as [| n'].\n - (* n = 0 *)\n reflexivity. (* so far so good... *)\n - (* n = S n' *)\n simpl. (* ...but here we are stuck again *)\nAbort.\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *) reflexivity.\n - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity. Qed.\n\nTheorem minus_diag : forall n,\n minus n n = 0.\nProof.\n (* WORKED IN CLASS *)\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n simpl. reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(*Exercise: 2 stars, recommended (basic_induction)\nProve the following using induction. You might need previously proven results.*)\n\n(*\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n intros n.\n destruct n.\n -\n simpl.\n reflexivity.\n -\n simpl.\n induction n as [|n' IHn].\n +\n simpl.\n reflexivity.\n +\n simpl.\n assumption.\nQed.*)\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n intros n.\n induction n as [|n' IHn].\n -\n simpl.\n reflexivity.\n -\n simpl.\n rewrite -> IHn.\n reflexivity. \nQed.\n \nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof.\n intros n m.\n induction n as [|n' Sn].\n - \n simpl.\n reflexivity.\n -\n simpl.\n rewrite -> Sn.\n reflexivity.\nQed.\n\n(*Auxiliar Theorem*)\nTheorem plus_n_0 : forall n: nat, n + 0 = n.\nProof.\n intros n.\n simpl.\n induction n as [|n' IHn].\n -\n simpl.\n reflexivity.\n -\n simpl.\n rewrite -> IHn.\n reflexivity.\n \n Qed.\n\n(*Auxiliar Theorem*)\nTheorem plus_n_m_n_plus_Sn : forall n m: nat, S(n + m) = n + S m.\nProof.\n intros n m.\n induction n as [|n' IHn].\n +\n simpl.\n reflexivity.\n +\n simpl.\n rewrite <- IHn.\n reflexivity.\nQed.\n\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros n m.\n induction n.\n +\n rewrite <- plus_n_O.\n simpl.\n reflexivity.\n +\n simpl. \n rewrite -> IHn. \n rewrite <- plus_n_m_n_plus_Sn.\n reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n\n intros n m p.\n induction n as [|n' IHn].\n -\n simpl.\n reflexivity.\n -\n simpl.\n rewrite <- IHn.\n reflexivity.\nQed.\n\n(*Exercise: 2 stars (double_plus)\nConsider the following function, which doubles its argument:*)\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\n(*Use induction to prove this simple fact about double:*)\nLemma double_plus : forall n, double n = n + n .\nProof.\n intros n.\n induction n as [|n' IHn'].\n -\n simpl.\n reflexivity.\n -\n simpl.\n rewrite -> IHn'.\n rewrite -> plus_n_m_n_plus_Sn.\n reflexivity.\nQed.\n\n(*Auxiliar for exercise below*)\nTheorem negb_negb_b : forall b : bool, negb (negb b) = b.\nProof.\n intro b.\n destruct b.\n -\n simpl.\n reflexivity.\n -\n simpl.\n reflexivity.\nQed.\n\n\n(*Exercise: 2 stars, optional (evenb_S)\nOne inconvenient aspect of our definition of evenb n is the recursive call on n - 2. This makes proofs about evenb n harder when done by induction on n, since we may need an induction hypothesis about n - 2. The following lemma gives an alternative characterization of evenb (S n) that works better with induction:*)\nTheorem evenb_S : forall n : nat, evenb (S n) = negb (evenb n).\nProof.\n intro n.\n simpl.\n induction n.\n -\n simpl.\n reflexivity.\n -\n simpl.\n rewrite -> IHn.\n rewrite -> negb_negb_b.\n reflexivity.\n \nQed.\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n). { simpl. reflexivity. }(*\"Simpl\" added by me*)\n rewrite -> H.\n reflexivity. Qed.\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n (* We just need to swap (n + m) for (m + n)... seems\n like plus_comm should do the trick! *)\n rewrite -> plus_comm.\n (* Doesn't work...Coq rewrote the wrong plus! *)\nAbort.\n\nTheorem plus_rearrange : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n assert (H: n + m = m + n).\n { rewrite -> plus_comm. reflexivity. }\n rewrite -> H. reflexivity. Qed.\n\nTheorem plus_assoc' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n' IHn']. reflexivity.\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_assoc'' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n' IHn'].\n - (* n = 0 *)\n reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(*Exercise: 2 stars, optional (beq_nat_refl_informal)\nWrite an informal proof of the following theorem, using the informal proof of plus_assoc as a model. Don't just paraphrase the Coq tactics into English!*)\nTheorem beq_nat_refl_informal: forall n : nat, beq_nat n n = true.\nProof.\n\n intro n.\n induction n as [|n' IHn].\n -\n simpl.\n reflexivity.\n -\n simpl.\n (*assumption.*)\n (*apply IHn.*)\n rewrite <- IHn.\n reflexivity.\nQed.\n\n(*My simpler beq_nat*)\nFixpoint beq_nat_easy (n m : nat) : bool :=\n match n, m with\n | 0, 0 => true\n | S n, S m => beq_nat_easy n m\n | _, _ => false\n end.\n\n(*My new - and personal - version of the theorem*)\nTheorem beq_nat_refl_informal_easy: forall n : nat, beq_nat_easy n n = true.\nProof.\n\n intro n.\n induction n as [|n' IHn].\n -\n simpl.\n reflexivity.\n -\n simpl.\n (*assumption.*)\n (*apply IHn.*)\n rewrite <- IHn.\n reflexivity.\nQed.", "meta": {"author": "thalesad", "repo": "coqexercises", "sha": "62f09168bf5267196780146ddb6ab53b4bb458d6", "save_path": "github-repos/coq/thalesad-coqexercises", "path": "github-repos/coq/thalesad-coqexercises/coqexercises-62f09168bf5267196780146ddb6ab53b4bb458d6/InductionThales.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.9219218380728936, "lm_q1q2_score": 0.8631815967374308}} {"text": "Add LoadPath \"../Basics\".\nRequire Import EnumTypes.\nRequire Import CaseAnalysis.\nRequire Import NamingCases.\nRequire Import Induction.\nRequire Import ProofsInProofs.\n\n(** EXERCISE [***]: Prove the following theorems. First determine\n whether they can be proven w/ simple rewriting and simplification.\n If not, determine whether it needs case analysis via [destruct], or\n full-on [induction] *)\n\n(** INDUCTION *)\nTheorem ble_nat_refl : forall n : nat,\n true = ble_nat n n.\n\nProof.\n intro n. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** REWRITE ONLY *)\nTheorem zero_nbeq_S : forall n : nat,\n beq_nat 0 (S n) = false.\n\nProof.\n intro n. simpl. reflexivity. Qed.\n\n(** CASE ANALYSIS *)\nTheorem andb_false_r : forall b : bool,\n andb b false = false.\n\nProof.\n intro b. destruct b.\n Case \"b = true\".\n simpl. reflexivity.\n Case \"b = false\".\n simpl. reflexivity. Qed.\n\n(** INDUCTION *)\nTheorem plus_ble_compat_1 : forall n m p : nat,\n ble_nat n m = true ->\n ble_nat (p + n) (p + m) = true.\n\nProof.\n intros n m p. intro H.\n induction p as [| p'].\n Case \"p = 0\".\n simpl. rewrite -> H. reflexivity.\n Case \"p = S p'\".\n simpl. rewrite -> IHp'. reflexivity. Qed.\n\n(** REWRITE ONLY *)\nTheorem S_nbeq_0 : forall n : nat,\n beq_nat (S n) 0 = false.\n\nProof.\n intro n. simpl. reflexivity. Qed.\n\n(** REWRITE ONLY *)\nTheorem mult_1_1 : forall n : nat,\n 1 * n = n.\n\nProof.\n intro n. simpl. rewrite <- plus_n_O. reflexivity. Qed.\n\n(** CASE ANALYSIS *)\nTheorem all3_spec : forall b c : bool,\n orb (andb b c) (orb (negb b) (negb c)) = true.\n\nProof.\n intros b c. destruct b.\n Case \"b = true\".\n destruct c.\n SCase \"c = true\".\n simpl. reflexivity.\n SCase \"c = false\".\n simpl. reflexivity.\n Case \"b = false\".\n destruct c.\n SCase \"c = true\".\n simpl. reflexivity.\n SCase \"c = false\".\n simpl. reflexivity. Qed.\n\n(** TODO *)\nTheorem mult_plus_distr_r : forall n m p : nat,\n (n + m) * p = (n * p) + (m * p).\n\nProof.\n Admitted.\n\n(** INDUCTION *)\nTheorem mult_assoc : forall n m p: nat,\n n * (m * p) = (n * m) * p.\n\nProof.\n intros n m p. induction n as [| n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. rewrite -> mult_plus_distr_r.\n reflexivity. Qed.\n\n(** EXERCISE [**]: Prove the following theorem *)\nTheorem beq_nat_refl : forall n : nat,\n true = beq_nat n n.\n\nProof.\n intro n. induction n as [| n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** EXERCISE [**]: The [replace] tactice lets you specify a particular\n subterm to rewrite and what you want it rewritten to. That is,\n [replace (t) with (u)] replaces all copeis of expression [t] in\n the goal statement by expression [u], and generates [t = u] as an\n additional subgoal. Use this tactic to prove [plus_swap] without\n [assert] *)\nTheorem plus_swap' : forall n m p : nat,\n n + (m + p) = m + (n + p).\n\nProof.\n intros n m p.\n replace (n + (m + p)) with ((m + p) + n).\n replace (n+p) with (p + n).\n rewrite -> plus_assoc.\n reflexivity.\n Case \"Proof of second replacement\".\n rewrite -> plus_comm. reflexivity.\n Case \"Proof of first replacement\".\n rewrite <- plus_comm. reflexivity. Qed.\n\n(** EXERCISE [***]: Prove that [increment] and [binary-to-unary]\n commute. *)\n", "meta": {"author": "madelgi", "repo": "software-foundations", "sha": "7f533d9596c4408eedd02bb7463f4ed532e9541e", "save_path": "github-repos/coq/madelgi-software-foundations", "path": "github-repos/coq/madelgi-software-foundations/software-foundations-7f533d9596c4408eedd02bb7463f4ed532e9541e/Induction/Exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.929440403324091, "lm_q1q2_score": 0.8629006518789617}} {"text": "(*\n# Inductive propositions\n\n```coq\n*)\n\nRequire Bool List.\n\nModule IndProp.\n\n(*\n```\n\nWe will use the following tactics:\n\n - `induction`\n - `apply`\n - `congruence` (subsumes `exact`, `assumption`, `reflexivity`)\n - `simpl`, `simpl `: Unfolding of definitions. Also `unfold`.\n - `trivial`: Like `auto`, but with a very limited search depth.\n - `repeat`: Milk a tactic dry. Good with `try`.\n - `tauto`: Solves propositional logic problems.\n - `replace`: Replaces a term by another, generates subgoal to show that they are equal.\n - `rewrite`: Replaces a term by another using a hypothesis.\n\nWe will introduce\n\n - `unfold` (and `fold`)\n\n - `discriminate`\n - `generalize`\n - `remember`\n - `inversion` (subsumes `destruct` (as) )\n\n\n## Defining inductive properties\n\nHow to define the even natural numbers in Coq?\n\n1. Mathematical characterisation.\n\n `unfold` and `discriminate`.\n\n```coq\n*)\n\nDefinition even_p (n : nat) : Prop := exists k, n = k + k.\n\nExample even_8 : even_p 8.\nunfold even_p.\nexists 4.\nsimpl.\nreflexivity.\nQed.\n\n\nExample not_even_1 : ~(even_p 1).\nunfold even_p.\nintro.\ndestruct H as [ k Pk ].\ndestruct k.\nsimpl in Pk.\ndiscriminate Pk.\nsimpl in Pk.\n(* plus_n_Sm: forall n m : nat, S (n + m) = n + S m *)\nrewrite <- plus_n_Sm in Pk.\ndiscriminate Pk.\nQed.\n\n(*\n```\n\n2. Decision algorithm.\n\n```coq\n*)\n\nFixpoint is_even (n : nat) : bool :=\n match n with\n | 0 => true\n | 1 => false\n | (S (S n)) => is_even n\n end.\n\nExample is_even_5 : is_even 6 = true.\nsimpl. reflexivity.\nQed.\n\nExample not_is_even_1 : is_even 1 = false.\nsimpl. reflexivity.\nQed.\n\n(*\n```\n\nThese are equivalent: proof in the appendix.\n\n- Disadvantages\n\n - Mathematical characterizations are opaque\n (what does a proof of n = k + k look like?)\n They cannot be inspected, one can only gaze at them.\n\n - Decision procedures are only good for decidable properties.\n\nEnter inductive predicates.\n\n## Inductive predicates\n\nLet’s take `even` as an example.\n\n```coq\n*)\nInductive even : nat -> Prop :=\n | even_0 : even 0\n | even_SS : forall n : nat, even n -> even (S (S (n))).\n\nExample even_6 : even 6.\nexact (even_SS 4 (even_SS 2 (even_SS 0 even_0))).\nQed.\n\nExample even_4 : even 4.\napply even_SS.\napply even_SS.\napply even_0.\nQed.\n\nExample even_200 : even 200.\nrepeat constructor.\nQed.\n\nExample not_even_5 : ~(even 5).\nintro H5.\ninversion H5.\ninversion H0.\ninversion H2.\nQed.\n\n(*\n```\n\n### Generalize\n\nThe importance of being general: `generalize`.\n\n```coq\n*)\nProposition even_correct : forall n, even n <-> even_p n.\n split.\n (* -> *)\n unfold even_p.\n intro H.\n induction H.\n (* H = even_0 *)\n exists 0. trivial.\n (* H = even_SS n' Hn' *)\n destruct IHeven as [ k Pk ].\n exists (S k).\n simpl \"+\". rewrite <- plus_n_Sm.\n congruence.\n\n (* <- *)\n unfold even_p.\n intros.\n destruct H as [ k Pk ].\n (* per AndreasLoow, you can do 'generalize dependent n' instead *)\n generalize n Pk.\n clear n Pk.\n induction k.\n intros. rewrite Pk. apply even_0.\n intros.\n rewrite Pk.\n simpl \"+\". rewrite <- plus_n_Sm.\n apply even_SS.\n apply IHk. trivial.\nQed.\n(*\n```\n\nExercises:\n\n```coq\n*)\nFixpoint nat_eq (m n : nat) : bool :=\n match m, n with\n | 0, 0 => true\n | S m, S n => nat_eq m n\n | _, _ => false\n end.\n\nLemma nat_eq_correct : forall m n, nat_eq m n = true <-> m = n.\nAdmitted.\n\n(*\n```\n\n## Inductive relations\n\n```coq\n*)\n\nInductive le : nat -> nat -> Prop :=\n | le_n : forall n, le n n\n | le_S : forall m n, le m n -> le m (S n).\n\nNotation \"m ≤ n\" := (le m n) (at level 30).\n\nExample le_3_5 : 3 ≤ 5.\napply le_S.\napply le_S.\napply le_n.\nQed.\n\nExample le_big : 2 ≤ 20.\napply le_S.\napply le_S.\nrepeat (try (apply le_n); apply le_S).\nQed.\n\nExample not_le_2_1 : ~(2 ≤ 1).\nintro.\ninversion H as [|m n H1].\ninversion H1.\nQed.\n\nExample not_le_100_10 : ~(100 ≤ 10).\nintro.\nrepeat (rename H into H'; inversion H' as [|? ? H]; clear H').\nQed.\n\n(*\n```\n\n### Remember to `remember`\n\nThe `induction` tactic is an amnesiac fellow.\n\n```coq\n*)\nLemma le_Sm_n_bad : forall m n, S m ≤ n -> m ≤ n.\n intros.\n remember (S m) as sm.\n induction H.\n (* H = le_n *)\n rewrite Heqsm.\n apply le_S.\n apply le_n.\n (* H = le_S *)\n apply le_S.\n apply IHle.\n trivial.\nQed.\n\nFixpoint le_Sm_n (m n : nat) ( H : S m ≤ n) : m ≤ n.\n inversion H.\n apply le_S.\n apply le_n.\n (* H = le_S *)\n apply le_S.\n apply le_Sm_n.\n assumption.\nQed.\n\nPrint le_Sm_n.\n\n(*\n```\n\nWhen doing induction on an inductive proposition, we need to\nexplicitly remember the indices.\n\n```coq\n*)\n(*\n```\n\n### Exercises:\n\n(Software Foundations, IndProp).\nR_provability2, R_fact:\n\n```coq\n*)\n\nSection R.\n\nInductive R : nat -> nat -> nat -> Prop :=\n | c1 : R 0 0 0\n | c2 : forall m n o, R m n o -> R (S m) n (S o)\n | c3 : forall m n o, R m n o -> R m (S n) (S o)\n | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n | c5 : forall m n o, R m n o -> R n m o.\n\n(*\n```\n * Which of the following propositions are provable?\n```coq\n*)\nExample exR1 : R 1 1 2. Admitted.\nExample exR2 : R 2 2 6. Admitted.\n(*\n```\n\n * If we dropped constructor c5 from the definition of R, would the set of provable propositions change?\n * If we dropped constructor c4 from the definition of R, would the set of provable propositions change?\n\n```coq\n*)\nDefinition fR : nat -> nat -> nat.\nAdmitted.\n\n\nTheorem R_equiv_fR : forall m n o, R m n o <-> fR m n = o.\nAdmitted.\n\nEnd R.\n(*\n```\n\n## Case study: regular expressions\n\n```coq\n*)\n\nImport Bool List.\nImport ListNotations.\n\nInductive regex (T : Type) : Type :=\n | empty : regex T\n | ε : regex T\n | char : T -> regex T\n | concat : regex T -> regex T -> regex T\n | union : regex T -> regex T -> regex T\n | star : regex T -> regex T.\n\nNotation \"∅\" := (empty _).\nArguments ε {T}.\nNotation \"« x »\" := (char _ x).\nNotation \"x · y\" := (concat _ x y) (at level 35, right associativity).\nNotation \"x ∪ y\" := (union _ x y) (at level 55, right associativity).\nNotation \"x **\" := (star _ x) (at level 10).\n(*\n```\n\nExamples of regular expressions.\n\n```coq\n*)\n\nExample re_all_true : regex bool := (« true » **).\n\nExample re_length_one : regex bool := (« true » ∪ « false »).\n\nExample re_even_length : regex bool :=\n ((« true » ∪ « false ») · (« true » ∪ « false »)) **.\n\nExample re_odd_length : regex bool.\n refine (_ · (_ · _) **); exact re_length_one.\nDefined.\n\nEval compute in re_odd_length.\n(*\n```\n\nWhat does it mean for a regular expression to match a string?\n\n```coq\n*)\nInductive matches {T} : regex T -> list T -> Prop :=\n | m_empty : matches ε []\n | m_char : forall x, matches « x » [x]\n | m_concat : forall xs ys r₁ r₂,\n matches r₁ xs ->\n matches r₂ ys ->\n matches (r₁ · r₂) (xs ++ ys)\n | m_unionL : forall xs r₁ r₂,\n matches r₁ xs ->\n matches (r₁ ∪ r₂) xs\n | m_unionR : forall xs r₁ r₂,\n matches r₂ xs ->\n matches (r₁ ∪ r₂) xs\n (* Alternative:\n | m_union : forall xs r₁ r₂,\n matches r₁ xs \\/ matches r₂ xs ->\n matches (r₁ ∪ r₂) xs\n *)\n | m_star0 : forall r₁, matches (r₁ **) []\n | m_starS : forall xs ys r,\n matches r xs ->\n matches (r **) ys ->\n matches (r **) (xs ++ ys).\n\nNotation \"s ∈ re\" := (matches re s) (at level 80).\n\nExample match_length_one : forall b, [b] ∈ re_length_one.\nintros.\nunfold re_length_one.\ninduction b.\napply m_unionL. apply m_char.\napply m_unionR. apply m_char.\nDefined.\n\n\nEval compute in match_length_one.\n\nExample match_odd_3 : [true;true;false] ∈ re_odd_length.\nunfold re_odd_length.\napply (m_concat [true] [true; false]).\napply match_length_one.\napply (m_starS [true; false] []).\napply (m_concat [true] [false]).\napply match_length_one.\napply match_length_one.\napply m_star0.\nDefined.\n\nEval compute in match_odd_3.\n\n(*\n```\n\nGood!\n\n### Exercises\n\n\n1. Define a decision procedure to check if a regular expression\n accepts the empty string, and show it correct.\n\n```coq\n*)\n\nFixpoint ε_in {T : Type} (re : regex T) : bool.\nAdmitted.\n\nLemma ε_in_good {T} (re : regex T) : ε_in re = true <-> [] ∈ re.\nAdmitted.\n(*\n```\n\n Ultimately, we want to decide if an expression matches a given list.\n We can only do this if we have a way of comparing elements in the alphabet\n for equality.\n\n To simplify, we will work with regular expresions over the boolean alphabet.\n It is easy to generalize this to any type with decidable equality.\n\n There is a polymorphic version of the exercise in the appendix, which you can\n do instead.\n\n```coq\n*)\n\nSection ExerciseMonomorphic.\n\nDefinition bool_eq (x y : bool) : bool :=\n match x, y with\n | true, true => true\n | false, false => true\n | _, _ => false\n end.\nNotation \"x == y\" := (bool_eq x y) (at level 60).\n\nDefinition reflect_bool_eq (x y : bool) : x == y = true -> x = y.\n (intros; induction x, y; trivial; (discriminate H)).\nQed.\n\nDefinition compute_bool_eq (x : bool) : x == x = true.\n induction x; simpl; trivial.\nQed.\n\n(*\n```\n\n2. Given a regular expression X accepting a language L, compute the regular expression\n that accepts the [Brzozowski derivative](https://en.wikipedia.org/wiki/Brzozowski_derivative) of L,\n and prove the definition correct.\n\n```coq\n*)\n\nFixpoint derivative (re : regex bool) (t : bool) : regex bool\n. Admitted.\n\nLemma derivative_good re a x : x ∈ derivative re a <-> a :: x ∈ re.\nAdmitted.\n\n(*\n```\n\n3. Prove that the matching function is correct. You can do this before solving\n part 1. or part 2.\n\n```coq\n*)\nFixpoint matches_b (re : regex bool) (x : list bool) : bool :=\n match x with\n | [] => ε_in re\n | t :: ts => matches_b (derivative re t) ts\n end.\n\nEval compute in matches_b (re_odd_length) [true;true;false;true;false].\nEval compute in matches_b (re_odd_length) [true;false;true;false].\n\nLemma matches_b_good (re : regex bool) (x : list bool) : matches_b re x = true <-> x ∈ re.\nAdmitted.\n\nEnd ExerciseMonomorphic.\n(*\n```\n\n4. (From SF)\n\nGiven:\n\n```coq\n*)\nFixpoint regex_list {T} (l : list T) :=\n match l with\n | [] => ε\n | x :: l' => « x » · (regex_list l')\n end.\n\n(*\n```\n\nShow:\n\n```coq\n*)\n\n\nLemma reg_exp_of_list_spec {T} (x : list T) : x ∈ regex_list x.\nAdmitted.\n(*\n```\n\n\n## Appendix\n\n### Equivalence between `is_even` and `even_p`\n\nFirst, define a new induction principle on the natural numbers,\nand prove it correct.\n\n```coq\n*)\n\nFixpoint is_even_ind (P : nat -> Prop)\n (P0 : P 0)\n (P1 : P 1)\n (PSS : forall n, P n -> P (S (S n)))\n (n : nat) : P n.\n destruct n as [|[|n']]; try assumption.\n apply PSS.\n apply is_even_ind; assumption.\nQed.\n\nLemma is_even_correct : forall n, is_even n = true <-> even_p n.\n split.\n\n (* -> *)\n induction n using is_even_ind.\n\n (* n = 0 *)\n intros.\n unfold even_p.\n exists 0.\n reflexivity.\n\n (* n = 1 *)\n intros.\n simpl in H. discriminate H.\n\n (* n = S (S n') *)\n simpl.\n unfold even_p in *.\n intros.\n specialize (IHn H); clear H.\n destruct IHn as [k Pk].\n exists (S k).\n simpl.\n (* obs: plus_n_Sm: forall n m : nat, S (n + m) = n + S m *)\n rewrite <- plus_n_Sm.\n congruence.\n\n (* <- *)\n unfold even_p.\n intros.\n destruct H as [k Pk].\n generalize n Pk; clear n Pk.\n induction k; intros n Hn; rewrite Hn; trivial.\n (* k = S k' *)\n simpl \"+\".\n rewrite <- plus_n_Sm.\n simpl is_even.\n apply IHk.\n reflexivity.\nQed.\n(*\n```\n\n## Derivative for arbitrary types with decidable equality\n\nDefine a notion of decidable equality.\n\n```coq\n*)\n\nSection RegexDec.\n\nClass eqDec (T : Type) : Type :=\n mkEqDec {\n eqDec_f : T -> T -> bool\n ; eqDec_pf : forall x y, eqDec_f x y = true <-> x = y\n }.\n\nNotation \"x == y\" := (eqDec_f x y) (at level 60).\n\nDefinition reflectEq {T} {eq : eqDec T} {a b : T} : a == b = true -> a = b.\n intros.\n apply eqDec_pf.\n trivial.\nDefined.\n\nDefinition computeEq {T} {eq : eqDec T} (a : T) : a == a = true.\n intros.\n apply eqDec_pf.\n trivial.\nDefined.\n(*\n```\n\nAn instance for `nat`\n\n```coq\n*)\nFixpoint nat_eqDec_f (m n : nat) : bool :=\n match m, n with\n | 0, 0 => true\n | S n, S m => nat_eqDec_f n m\n | _, _ => false\n end.\n\nInstance nat_eqDec : eqDec nat := { eqDec_f := nat_eqDec_f}.\nProof.\n (** x = 0 *)\n (** x = S _ *)\nAdmitted.\n\nFixpoint derivativeD {T} {eq : eqDec T} (re : regex T) (t : T) : regex T\n. Admitted.\n\n\nFixpoint matchesD {T} {eq : eqDec T} (re : regex T) (x : list T) : bool\n. Admitted.\n\nEval compute in matchesD ((«1» · «1» · «1») **) [1;1;1;1;1].\n\nEval compute in matchesD ((«1» · «1» · «1») **) [1;1;1;1;1;1].\n\nEnd RegexDec.\n\nEnd IndProp.\n\n(*\n```\n*)\n", "meta": {"author": "vlopezj", "repo": "coq-course", "sha": "b7f3c44d73859ddad49a6edbfd3430283bcc251f", "save_path": "github-repos/coq/vlopezj-coq-course", "path": "github-repos/coq/vlopezj-coq-course/coq-course-b7f3c44d73859ddad49a6edbfd3430283bcc251f/exercises/2/exindprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.9294404028354749, "lm_q1q2_score": 0.8629006477431842}} {"text": "From mathcomp Require Import all_ssreflect.\n\nImplicit Type p q r : bool.\nImplicit Type m n a b c : nat.\n\n(** *** Exercise 1:\n - look for lemmas supporting contrapositive reasoning\n - use the eqP view to finish the proof.\n*)\nLemma bool_gimmics1 a : a != a.-1 -> a != 0.\n(*D*)Proof. by apply: contra; move => /eqP E; rewrite E. Qed.\n\n(** *** Exercise 2:\n - it helps to find out what is behind [./2] and [.*2] in order to [Search]\n - any proof would do, but there is one not using [implyP]\n*)\nLemma view_gimmics1 p a b : p -> (p ==> (a == b.*2)) -> a./2 = b.\n(*D*)Proof. by move=> -> /eqP->; exact: doubleK. Qed.\n\n(** *** Exercise 3:\n - Prove this view by unfolding maxn and then using [leqP]\n*)\nLemma maxn_idPl m n : reflect (maxn m n = m) (m >= n).\nProof. apply: (iffP idP).\n(*D*)by rewrite /maxn; case: leqP.\n(*D*)by move=> <-; rewrite /maxn; case: leqP.\nQed.\n\n(** *** Exercise 4:\n - there is no need to prove [reflect] with [iffP]: here just use [rewrite] and [apply]\n - check out the definitions and theory of [leq] and [maxn]\n - proof sketch:\n<<\n n <= m = n - m == 0\n = m + n - m == m + 0\n = maxn m n == m\n>> *)\nLemma maxn_idPl_bis m n : reflect (maxn m n = m) (m >= n).\n(*D*)Proof. by rewrite -subn_eq0 -(eqn_add2l m) addn0 -maxnE; apply: eqP. Qed.\n\n", "meta": {"author": "gares", "repo": "typesschool18", "sha": "c27fe831c750c948245593a5fa52f768dd990cb3", "save_path": "github-repos/coq/gares-typesschool18", "path": "github-repos/coq/gares-typesschool18/typesschool18-c27fe831c750c948245593a5fa52f768dd990cb3/exercise3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.9304582497090321, "lm_q1q2_score": 0.8628728233081503}} {"text": "\nRequire Import Arith.\n\nFixpoint nat_fact (n:nat) : nat :=\n match n with\n | O => 1 \n | S p => S p * nat_fact p \n end.\n\n\nFixpoint fib (n:nat) : nat :=\n match n with\n | O => 0\n | S q => \n match q with\n | O => 1\n | S p => fib p + fib q\n end\n end.\n\nRequire Import ZArith.\n\nOpen Scope Z_scope.\n\nDefinition fact_aux (n:Z) :=\nZ.iter n (fun p => (fst p + 1, snd p * (fst p + 1))) (0, 1).\n\nDefinition Z_fact (n:Z) := snd (fact_aux n).\nCompute Z_fact 100.\n\nClose Scope Z_scope.\n\n\n", "meta": {"author": "James-Oswald", "repo": "Coq-In-A-Hurry", "sha": "d9ba73090affe7d7c8a324bf726f709a7b949a15", "save_path": "github-repos/coq/James-Oswald-Coq-In-A-Hurry", "path": "github-repos/coq/James-Oswald-Coq-In-A-Hurry/Coq-In-A-Hurry-d9ba73090affe7d7c8a324bf726f709a7b949a15/Chapter8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.956634196290671, "lm_q2_score": 0.9019206798249231, "lm_q1q2_score": 0.862808164662251}} {"text": "Add LoadPath \"../Basics\".\nAdd LoadPath \"../Induction\".\n\nRequire Import Lists.\nRequire Import EnumTypes.\nRequire Import Induction.\nRequire Import NamingCases.\n\n(** Simplification can sometimes be good enough for\n lists, too *)\nTheorem nil_app : forall l : natlist,\n [] ++ l = l.\n\nProof.\n reflexivity. Qed.\n\n(** Case analysis can also be good *)\nTheorem tl_length_pred : forall l : natlist,\n pred (length l) = length (tl l).\n\nProof.\n intros l. destruct l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = cons n l'\".\n reflexivity. Qed.\n\n\n(**********************)\n(* INDUCTION ON LISTS *)\n(**********************)\n\n(** Induction can be performed on lists in a pretty straightforward\n manner. For some proposition [P] and a list [l],\n\n 1. Prove that [P] is true when [l = nil] (base case)\n 2. Assuming [P(l')] is true, show that [P] is true for [l] when\n [l = n :: l'], where [n] is some number and [l'] is a smaller list.\n\n*)\n\n(** Example of induction on lists. this proves that [++] is associative *)\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\n\nProof.\n intros l1 l2 l3. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons n l1'\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Another example of list induction. *)\nTheorem app_length : forall l1 l2 : natlist,\n length (l1 ++ l2) = (length l1) + (length l2).\n\nProof.\n intros l1 l2. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"cons n l1'\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Let's create a cons function that attaches an element on the right *)\nFixpoint snoc (l : natlist) (v : nat) : natlist :=\n match l with\n | nil => [v]\n | h :: t => h :: (snoc t v)\n end.\n\n(** Now we can use [snoc] to create a list reversing funciton *)\nFixpoint rev (l : natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => snoc (rev t) h\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** Now we can prove some facts about reverse. First, we try to prove that\n reversing a list does not change its length *)\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\n\nProof.\n intros l. induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n :: l'\".\n simpl. rewrite <- IHl'.\nAbort.\n\n(** Above, we became stuck. Let's isolate the part we get stuck on, and\n prove that. *)\nTheorem length_snoc : forall n : nat, forall l : natlist,\n length (snoc l n) = S (length l).\n\nProof.\n intros n l. induction l as [| x l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = x :: l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed.\n\n(** with [length_snoc], we can return to the original proof. *)\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\n\nProof.\n intros l. induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n :: l'\".\n simpl. rewrite -> length_snoc. rewrite -> IHl'. reflexivity. Qed.\n\n(************************)\n(* LIST EXERCISES PT. 1 *)\n(************************)\n\n(** EXERCISE [***]: Prove the following theorems. *)\n\n(* appending a nil list does nothing *)\nTheorem app_nil_end : forall l : natlist,\n l ++ [] = l.\n\nProof.\n intro l. induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n :: l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed.\n\n(** Lemma for the upcoming theorem *)\nLemma rev_snoc: forall (l : natlist) (n : nat),\n rev (snoc l n) = n :: (rev l).\n\nProof.\n intros l n. induction l as [| x l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = x :: l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed.\n\n(** rev is its own inverse *)\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\n\nProof.\n intro l. induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n :: l'\".\n simpl. rewrite -> rev_snoc.\n rewrite -> IHl'. reflexivity. Qed.\n\n(** extend associativity *)\nTheorem app_assoc4: forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\n\nProof.\n intros l1 l2 l3 l4. rewrite -> app_assoc.\n rewrite -> app_assoc. reflexivity. Qed.\n\n(** an alternate definition of [snoc], in some sense *)\nTheorem snoc_append : forall (l : natlist) (n : nat),\n snoc l n = l ++ [n].\n\nProof.\n intros l n. induction l as [| x l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = x :: l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed.\n\n(** TODO: this is a pretty bad proof. Can it be made better? *)\nTheorem distr_rev : forall l1 l2 : natlist,\n rev (l1 ++ l2) = (rev l2) ++ (rev l1).\n\nProof.\n intros l1 l2. induction l1 as [| x l1'].\n Case \"l1 = []\".\n assert (H: rev [] = []).\n SCase \"Assertion H\".\n simpl. reflexivity.\n rewrite -> nil_app. rewrite -> H.\n rewrite -> app_nil_end. reflexivity.\n Case \"l1 = x :: l1'\".\n simpl. rewrite -> IHl1'. rewrite -> snoc_append.\n assert (H': snoc (rev l1') x = (rev l1') ++ [x]).\n SCase \"Assertion H'\".\n rewrite -> snoc_append. reflexivity.\n rewrite -> H'. rewrite -> app_assoc. reflexivity. Qed.\n\n(* asserts that we can distribute [nonzeros] across [++] *)\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\n\nProof.\n intros l1 l2. induction l1 as [| x l1'].\n Case \"l1 = []\".\n reflexivity.\n Case \"l1 = x :: l1'\".\n simpl. destruct x as [| x'].\n SCase \"x = 0\".\n rewrite IHl1'. reflexivity.\n SCase \"x = S x'\".\n rewrite IHl1'. reflexivity. Qed.\n\n(** EXERCISE [**]: fill in the definition of [beq_natlist], which\n compares lists of numbers for equality. Next, prove that\n [beq_natlist l l = true] for all [l : natlist]. *)\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n match l1, l2 with\n | [], [] => true\n | [], _ => false\n | _, [] => false\n | (x :: xs), (y :: ys) => if beq_nat x y\n then beq_natlist xs ys\n else false\n end.\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\nExample test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\nExample test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l : natlist,\n true = beq_natlist l l.\n\nProof.\n intro l. induction l as [| x l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = x :: l'\".\n simpl. rewrite -> beq_nat_refl. rewrite -> IHl'.\n reflexivity. Qed.\n\n\n(************************)\n(* LIST EXERCISES PT. 2 *)\n(************************)\n\n(** EXERCISE [**]: Write down a non-trivial theorem [cons_snoc_app]\n involving [cons], [snoc], and [app], and then prove it TODO *)\nTheorem cons_snoc_app: forall (n:nat) (l1 l2 : natlist),\n true = true.\n\nProof. Admitted.\n\n\n\n(** EXERCISE [***, advanced]: Several theorems about the definition of\n [bag], from earlier in the section *)\nTheorem count_member_nonzero : forall (s : bag),\n ble_nat 1 (count 1 (1 :: s)) = true.\n\nProof.\n intro s. reflexivity. Qed.\n\n(* A lemma to help us with the following proof *)\n(* Note to self: Coq is smart enough to infer the type of [n], here *)\nLemma ble_n_Sn : forall n,\n ble_nat n (S n) = true.\n\nProof.\n intros n. induction n as [| n'].\n Case \"0\".\n reflexivity.\n Case \"S n'\".\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\n\nProof.\n intros s. induction s as [| x s'].\n Case \"s = []\".\n reflexivity.\n Case \"s = x :: s'\".\n destruct x as [| x'].\n SCase \"x = 0\".\n simpl. rewrite ble_n_Sn. reflexivity.\n SCase \"x = S x'\".\n simpl. rewrite IHs'. reflexivity. Qed.\n\n(** EXERCISE [***]: Write down an interessting theorem [bag_count_sum]\n about bags involving the functions [count] and [sum], and prove it\n TODO *)\nTheorem bag_count_sum : forall (s1 s2 : bag) (n : nat),\n count n (sum s1 s2) = (count n s1) + (count n s2).\n\nProof.\n intros s1 s2 n. induction s1 as [| x s1'].\n Case \"s1 = []\".\n reflexivity.\n Case \"s1 = x :: s1'\".\n simpl. rewrite IHs1'. destruct x as [| x']. destruct n as [| n'].\n SCase \"x = n = 0\".\n reflexivity.\n SCase \"x = 0, n = S n'\".\n reflexivity.\n SCase \"x = S x', n = 0\".\nAbort.\n\n(** EXERCISE [****, advanced]: Prove that the rev function is injective,\n that is: *)\nTheorem rev_inj: forall (l1 l2 : natlist),\n rev l1 = rev l2 -> l1 = l2.\n\nProof.\n intros l1 l2. intro H.\n rewrite <- rev_involutive. rewrite <- H.\n rewrite -> rev_involutive. reflexivity. Qed.\n", "meta": {"author": "madelgi", "repo": "software-foundations", "sha": "7f533d9596c4408eedd02bb7463f4ed532e9541e", "save_path": "github-repos/coq/madelgi-software-foundations", "path": "github-repos/coq/madelgi-software-foundations/software-foundations-7f533d9596c4408eedd02bb7463f4ed532e9541e/Lists/Reasoning.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.9390248225478307, "lm_q1q2_score": 0.8624757460641619}} {"text": "Theorem plus_n_0 : forall n:nat,\n n = n + 0.\nProof.\n intros n.\n induction n as [|n' IHn'].\n - reflexivity.\n - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\n\nTheorem mult_0_r: forall n: nat,\n n * 0 = 0.\nProof.\n intros n.\n induction n as [| n' iH].\n - reflexivity.\n - simpl. rewrite -> iH. reflexivity.\nQed.\n\nTheorem plus_n_Sm: forall n m: nat,\n S (n + m) = n + S m.\nProof.\n intros n m.\n induction n as [|n' iHn].\n - reflexivity.\n - simpl. rewrite -> iHn. reflexivity.\nQed.\n\n\n\nTheorem plus_comm: forall a b: nat,\n a + b = b + a.\nProof.\n intros a b.\n induction a as [|a' iha'].\n - simpl.\n induction b as [| b' ihb'].\n * reflexivity.\n * simpl. rewrite <- ihb'. reflexivity.\n - simpl. rewrite -> iha'. rewrite <- plus_n_Sm. reflexivity.\nQed.\n\n\nTheorem plus_assoc: forall a b c: nat,\n a + (b + c) = (a + b) + c.\nProof.\n intros a b c.\n induction a as [| a' iha'].\n - reflexivity.\n - simpl. rewrite <- iha'. reflexivity.\nQed.\n\n\nFixpoint double (n:nat) :=\n match n with\n | 0 => 0\n | S n' => S (S (double n'))\n end.\n\nLemma double_plus: forall (n:nat), double n = n + n.\nProof.\n intros n.\n induction n as [|n' ihn'].\n - reflexivity.\n - rewrite <- plus_n_Sm. simpl. rewrite -> ihn'. reflexivity.\nQed.\n\n\nFixpoint evenb (n:nat) : bool :=\n match n with\n | O => true\n | S O => false\n | S (S n') => evenb n'\n end.\n\n\nTheorem negb2: forall b: bool,\n negb (negb b) = b.\nProof.\n intros [].\n reflexivity.\n reflexivity.\nQed.\n\nTheorem evenb_S : forall n : nat,\n evenb (S n) = negb (evenb n).\nProof.\nProof.\n intros n.\n induction n as [|n' ihn'].\n - reflexivity.\n - rewrite -> ihn'. simpl. rewrite -> negb2. reflexivity.\nQed.\n\nTheorem plus_swap: forall n m p: nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n rewrite -> plus_assoc.\n rewrite -> plus_assoc.\n assert (H: n + m = m + n). rewrite <- plus_comm. reflexivity.\n rewrite -> H.\n reflexivity.\nQed.\n\n\nLemma mult_n_0: forall a, a * 0 = 0.\nProof.\n intros a.\n induction a as [|a' iHa'].\n - reflexivity.\n - simpl. rewrite -> iHa'. reflexivity.\nQed.\n\nLemma mult_n_1: forall a, a * 1 = a.\nProof.\n intros a.\n induction a as [|a' iHa'].\n - reflexivity.\n - simpl. rewrite -> iHa'. reflexivity.\nQed.\n\n(*\nFixpoint mul n m :=\n match n with\n | 0 => 0\n | S p => m + p * m\n end\n*)\n\nLemma mult_n_Sm: forall n m, n * S m = n + n * m.\nProof.\n intros m n.\n induction m as [| m' iHm'].\n - reflexivity.\n - simpl. rewrite -> iHm'. \n rewrite -> plus_assoc.\n rewrite -> plus_assoc.\n assert (H: n + m' = m' + n). rewrite -> plus_comm. reflexivity.\n rewrite -> H.\n reflexivity.\nQed.\n\nTheorem mult_comm: forall m n, m * n = n * m.\nProof.\n intros m n.\n induction m as [| m' iHm'].\n - rewrite -> mult_n_0. reflexivity.\n - simpl.\n rewrite -> iHm'.\n rewrite <- mult_n_Sm.\n reflexivity.\nQed.\n\nRequire Import Arith.\nCheck leb.\n\nTheorem leb_refl: forall n:nat,\n true = (n <=? n).\nProof.\n intros n.\n induction n as [| n' iHn'].\n - reflexivity.\n - simpl. rewrite <- iHn'. reflexivity.\nQed.\n\n\nTheorem zero_nbeq_S: forall n: nat,\n 0 =? S n = false.\nProof.\n intros n.\n induction n as [| n' iHn'].\n - reflexivity.\n - reflexivity.\nQed.\n\n\nTheorem and_false_r: forall b: bool,\n andb b false = false.\nProof.\n intros [].\n - reflexivity.\n - reflexivity.\nQed.\n\nTheorem plus_ble_compat_1: forall n m p: nat,\n n <=? m = true -> (p + n) <=? (p + m) = true.\nProof.\n intros n m p H.\n induction p as [|p iHp'].\n - rewrite -> plus_comm. \n rewrite <- plus_n_0.\n rewrite -> plus_comm.\n rewrite <- plus_n_0.\n rewrite -> H.\n reflexivity.\n - simpl.\n rewrite -> iHp'.\n reflexivity.\nQed.\n\nTheorem S_nbeq_0: forall n,\n S n =? 0 = false.\nProof.\n intros n. reflexivity.\nQed.\n\nTheorem mult_1_1: forall n,\n 1 * n = n.\nProof.\n simpl. \n intros n.\n rewrite <- plus_n_0.\n reflexivity.\nQed.\n\n\n\nTheorem all3_spec: forall b c: bool,\n orb\n (andb b c)\n (orb (negb b) (negb c))\n = true.\n\nProof.\n intros [] [].\n - reflexivity.\n - reflexivity.\n - reflexivity.\n - reflexivity.\nQed.\n\n\nTheorem plus_eq_del: forall a b c:nat,\n b = c -> a + b = a + c.\nProof.\n intros a b c H.\n induction a as [|a' iHa'].\n - simpl. rewrite -> H. reflexivity.\n - simpl. rewrite -> iHa'. reflexivity.\nQed.\n\n\nTheorem mult_plus__distr_r: forall a b c,\n (a + b) * c = (a * c) + (b * c).\nProof.\n intros a b c.\n induction c as [| c' iHc'].\n - simpl.\n rewrite -> mult_n_0.\n rewrite -> mult_n_0.\n rewrite -> mult_n_0.\n reflexivity.\n - assert (H: forall x y, x * S y = S y * x). \n intros x y. \n rewrite -> mult_comm.\n reflexivity.\n rewrite -> H. rewrite -> H. rewrite -> H.\n simpl. rewrite <- plus_assoc. rewrite <- plus_assoc.\n assert (H1: b + c' * (a + b) = c' * a + (b + c' * b)).\n rewrite -> plus_swap.\n rewrite -> mult_comm.\n rewrite -> iHc'.\n rewrite -> mult_comm.\n assert (H2: b * c' = c' * b). rewrite -> mult_comm. reflexivity.\n rewrite -> H2.\n reflexivity.\n rewrite -> H1.\n reflexivity.\nQed.\n\n\nTheorem mult_assoc: forall a b c,\n a * (b * c) = (a * b) * c.\nProof.\n intros a b c.\n induction a as [| a' iHa'].\n - reflexivity.\n - simpl.\n rewrite -> iHa'.\n rewrite -> mult_plus__distr_r.\n reflexivity.\nQed.\n\nTheorem eqb_refl: forall n: nat,\n true = (n =? n).\nProof.\n intros n.\n induction n as [|n' IHn'].\n - reflexivity.\n - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\n\nTheorem plus_swap' : forall n m p: nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n rewrite -> plus_assoc.\n rewrite -> plus_assoc.\n replace (n + m) with (m + n). reflexivity.\n rewrite -> plus_comm.\n reflexivity.\nQed.\n \n\nInductive bin: Type :=\n | Z\n | A (n: bin)\n | B (n: bin).\n\nFixpoint incr (m:bin):bin :=\n match m with\n | Z => B Z\n | A n => B n\n | B n => A (incr n)\n end.\n\nFixpoint bin_to_nat (m: bin): nat :=\n match m with\n | Z => 0\n | A n => 2 * bin_to_nat n\n | B n => 1 + 2 * bin_to_nat n\n end.\n\n\nTheorem bin_to_nat_pres_incr: forall x: bin,\n bin_to_nat (incr x) = S (bin_to_nat x).\nProof.\n intros x.\n induction x as [|xa iHxa|xb iHxb].\n - reflexivity.\n - simpl. replace (bin_to_nat xa + 0) with (bin_to_nat xa). reflexivity.\n rewrite <- plus_n_0.\n reflexivity.\n - simpl.\n replace (bin_to_nat xb + 0) with (bin_to_nat xb).\n replace ((bin_to_nat (incr xb)) + 0) with (bin_to_nat (incr xb)).\n rewrite -> iHxb.\n simpl.\n assert (H: forall a b, a + S b = S (a + b)).\n intros a b.\n induction a as [| a' iHa'].\n reflexivity.\n simpl. rewrite -> iHa'. reflexivity.\n rewrite -> H. reflexivity.\n rewrite <- plus_n_0. reflexivity.\n rewrite <- plus_n_0. reflexivity.\nQed.\n\nCheck true.\n\nCompute (S 1) / 2.\n\n\n\n \n\n", "meta": {"author": "pzzp", "repo": "sf", "sha": "d60708e408a4f9342142cb8de51d0d4d75f144f9", "save_path": "github-repos/coq/pzzp-sf", "path": "github-repos/coq/pzzp-sf/sf-d60708e408a4f9342142cb8de51d0d4d75f144f9/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.9073122150949273, "lm_q1q2_score": 0.8623194888068921}} {"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export logic.\nRequire Coq.omega.Omega.\n\n\nInductive ev : nat -> Prop :=\n| ev_0 : ev 0\n| ev_SS (n : nat) (H : ev n) : ev (S (S n)).\n\n\n(** **** Exercise: 1 star, standard (ev_double) *)\nTheorem ev_double : forall n,\n ev (double n).\nProof.\n intros.\n induction n as [|n'].\n - (* n = 0 *) apply ev_0.\n - (* n = S n' *) simpl. apply ev_SS. apply IHn'.\nQed.\n\n\nTheorem ev_inversion :\n forall (n : nat), ev n ->\n (n = 0) \\/ (exists n', n = S (S n') /\\ ev n').\nProof.\n intros n E.\n destruct E as [ | n' E'].\n - (* E = ev_0 : ev 0 *)\n left. reflexivity.\n - (* E = ev_SS n' E' : ev (S (S n')) *)\n right. exists n'. split. reflexivity. apply E'.\nQed.\n\n\nTheorem evSS_ev : forall n, ev (S (S n)) -> ev n.\nProof.\n intros n H. apply ev_inversion in H. destruct H.\n - discriminate H.\n - destruct H as [n' [Hnm Hev]]. injection Hnm as Heq.\n rewrite Heq. apply Hev.\nQed.\n\n\n(** **** Exercise: 1 star, standard (inversion_practice) \n\n Prove the following result using [inversion]. (For extra practice,\n you can also prove it using the inversion lemma.) *)\n\nTheorem SSSSev__even : forall n,\n ev (S (S (S (S n)))) -> ev n.\nProof.\n intros.\n inversion H.\n inversion H1.\n apply H3.\nQed.\n\nTheorem SSSSev__even___inversion_lemma : forall n,\n ev (S (S (S (S n)))) -> ev n.\nProof.\n intros.\n apply ev_inversion in H.\n destruct H as [H1 | H2].\n - discriminate H1.\n - destruct H2. destruct H.\n apply ev_inversion in H0.\n destruct H0 as [F | G].\n + rewrite F in H. discriminate H.\n + destruct G. destruct H0.\n rewrite H0 in H.\n injection H as E.\n rewrite <- E in H1.\n apply H1.\nQed.\n\n(** **** Exercise: 1 star, standard (ev5_nonsense) \n\n Prove the following result using [inversion]. *)\n\nTheorem ev5_nonsense :\n ev 5 -> 2 + 2 = 9.\nProof.\n intros.\n inversion H.\n inversion H1.\n inversion H3.\nQed.\n\n(** **** Exercise: 2 stars, standard (ev_sum) *)\nTheorem ev_sum : forall n m, ev n -> ev m -> ev (n + m).\nProof.\n intros n m H H1.\n induction H as [| n'].\n - simpl. apply H1.\n - simpl. apply ev_SS. apply IHev.\nQed.\n\n(** **** Exercise: 4 stars, advanced, optional (ev'_ev) \n\n In general, there may be multiple ways of defining a\n property inductively. For example, here's a (slightly contrived)\n alternative definition for [ev]: *)\n\nInductive ev' : nat -> Prop :=\n| ev'_0 : ev' 0\n| ev'_2 : ev' 2\n| ev'_sum n m (Hn : ev' n) (Hm : ev' m) : ev' (n + m).\n\n(** Prove that this definition is logically equivalent to the old one.\n To streamline the proof, use the technique (from [Logic]) of\n applying theorems to arguments, and note that the same technique\n works with constructors of inductively defined propositions. *)\n\nLemma SS_eq_plus_2: forall n, S (S n) = n + 2.\nProof.\n intros.\n induction n.\n - reflexivity.\n - rewrite IHn. reflexivity.\nQed.\n\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\n intros n.\n split.\n - intro.\n induction H.\n + apply ev_0.\n + apply ev_SS. apply ev_0.\n + apply ev_sum.\n * apply IHev'1.\n * apply IHev'2.\n - intro.\n induction H.\n + apply ev'_0.\n + simpl. rewrite SS_eq_plus_2. apply ev'_sum.\n * apply IHev.\n * apply ev'_2.\nQed.\n\n(** **** Exercise: 3 stars, advanced, recommended (ev_ev__ev) \n\n There are two pieces of evidence you could attempt to induct upon\n here. If one doesn't work, try the other. *)\n\nTheorem ev_ev__ev : forall n m,\n ev (n+m) -> ev n -> ev m.\nProof.\n intros n m H H1.\n induction H1.\n - simpl in H. apply H.\n - simpl in H. apply evSS_ev in H. apply IHev in H. apply H.\nQed.\n\n(** **** Exercise: 3 stars, standard, optional (ev_plus_plus) \n\n This exercise just requires applying existing lemmas. No\n induction or even case analysis is needed, though some of the\n rewriting may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n intros n m p H.\n apply ev_ev__ev. rewrite plus_comm. rewrite plus_swap.\n rewrite <- plus_assoc. rewrite plus_assoc. apply ev_sum. \n - apply H. \n - rewrite <- double_plus. apply ev_double.\nQed.\n\n\nInductive le : nat -> nat -> Prop :=\n | le_n (n : nat) : le n n\n | le_S (n m : nat) (H : le n m) : le n (S m).\n\nNotation \"m <= n\" := (le m n).\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n | sq n : square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n | nn n : next_nat n (S n).\n\nInductive next_ev : nat -> nat -> Prop :=\n | ne_1 n (H: ev (S n)) : next_ev n (S n)\n | ne_2 n (H: ev (S (S n))) : next_ev n (S (S n)).\n\n(** **** Exercise: 2 stars, standard, optional (total_relation) \n\n Define an inductive binary relation [total_relation] that holds\n between every pair of natural numbers. *)\nInductive universal_relation : nat -> nat -> Prop :=\n | uni : forall (n m :nat), universal_relation n m.\n\n\n(** **** Exercise: 2 stars, standard, optional (empty_relation) \n\n Define an inductive binary relation [empty_relation] (on numbers)\n that never holds. *)\n\nInductive null_relation : nat -> nat -> Prop :=.\n\n(** **** Exercise: 3 stars, standard, optional (le_exercises) \n\n Here are a number of facts about the [<=] and [<] relations that\n we are going to need later in the course. The proofs make good\n practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n intros m n o H H1.\n induction H1.\n - apply H.\n - apply le_S. apply IHle. apply H.\nQed. \n\nTheorem O_le_n : forall n,\n 0 <= n.\nProof.\n intro n.\n induction n.\n - apply le_n.\n - apply le_S. apply IHn.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n n <= m -> S n <= S m.\nProof.\n intros n m H.\n induction H.\n - apply le_n.\n - apply le_S. apply IHle.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n S n <= S m -> n <= m.\nProof.\n intros n m H.\n inversion H.\n - apply le_n.\n - apply le_trans with (n:=S n).\n + apply le_S. apply le_n.\n + apply H2.\nQed.\n\nTheorem le_plus_l : forall a b,\n a <= a + b.\nProof.\n intros a b.\n induction a.\n - apply O_le_n.\n - simpl. apply n_le_m__Sn_le_Sm. apply IHa.\nQed.\n \nTheorem plus_le : forall n1 n2 m,\n n1 + n2 <= m ->\n n1 <= m /\\ n2 <= m.\nProof.\n intros n1 n2 m H.\n split.\n - (* n1 <= m *)\n induction n2.\n + rewrite <- plus_n_O in H. apply H.\n + apply IHn2. rewrite plus_comm in H. simpl in H. apply le_S in H.\n apply Sn_le_Sm__n_le_m in H. rewrite plus_comm in H. apply H.\n - (* n2 <= m *)\n induction n1.\n + rewrite plus_comm in H. rewrite <- plus_n_O in H. apply H.\n + apply IHn1. simpl in H. apply le_S in H.\n apply Sn_le_Sm__n_le_m in H. apply H.\nQed.\n\n(** Hint: the next one may be easiest to prove by induction on [n]. *)\nLemma Sn_le_O: forall n,\n S n <= 0 <-> False.\nProof.\n intros.\n split.\n - intros. induction n.\n + inversion H.\n + inversion H.\n - intros. apply ex_falso_quodlibet. apply H.\nQed.\n\nTheorem add_le_cases : forall n m p q,\n n + m <= p + q -> n <= p \\/ m <= q.\nProof.\n intros n m p q H.\n induction n as [|n'].\n - left. apply O_le_n.\n - simpl in H. apply le_S in H. apply Sn_le_Sm__n_le_m in H. apply IHn' in H as [H1 | H2].\n + left. Admitted.\n\nTheorem lt_S : forall n m,\n n < m ->\n n < S m.\nProof.\n unfold lt.\n intros.\n apply le_S.\n apply H.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n n1 + n2 < m ->\n n1 < m /\\ n2 < m.\nProof.\n unfold lt.\n intros.\n split.\n - (* S n1 <= m *)\n apply plus_le with (n1:=S(n1)) in H as [H1 H2]. apply H1.\n - (* S n2 <= m *)\n rewrite plus_n_Sm in H. apply plus_le with (n2:=S(n2)) in H as [H1 H2]. apply H2.\nQed.\n\nTheorem leb_complete : forall n m,\n n <=? m = true -> n <= m.\nProof.\n induction n.\n - intros. apply O_le_n.\n - intros. destruct m.\n + inversion H.\n + apply n_le_m__Sn_le_Sm. simpl in H. apply IHn. apply H.\nQed. \n\n(** Hint: The next one may be easiest to prove by induction on [m]. *)\n\nTheorem leb_correct : forall n m,\n n <= m ->\n n <=? m = true.\nProof.\n intros. generalize dependent n. induction m. \n - intros. destruct n. \n + reflexivity.\n + inversion H.\n - intros. destruct n. \n + reflexivity.\n + apply IHm. apply Sn_le_Sm__n_le_m. apply H.\nQed. \n\n\n(** Hint: The next one can easily be proved without using [induction]. *)\n\nTheorem leb_true_trans : forall n m o,\n n <=? m = true -> m <=? o = true -> n <=? o = true.\nProof.\n intros.\n apply leb_correct.\n apply leb_complete in H.\n apply leb_complete in H0.\n apply le_trans with (n:= m).\n - apply H.\n - apply H0.\nQed.\n\n(** **** Exercise: 2 stars, standard, optional (leb_iff) *)\nTheorem leb_iff : forall n m,\n n <=? m = true <-> n <= m.\nProof.\n intros. split.\n - intro. apply leb_complete in H. apply H.\n - intro. apply leb_correct in H. apply H.\nQed.\n\nModule R.\n\n(** **** Exercise: 3 stars, standard, recommended (R_provability) \n\n We can define three-place relations, four-place relations,\n etc., in just the same way as binary relations. For example,\n consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n | c1 : R 0 0 0\n | c2 m n o (H : R m n o) : R (S m) n (S o)\n | c3 m n o (H : R m n o) : R m (S n) (S o)\n | c4 m n o (H : R (S m) (S n) (S (S o))) : R m n o\n | c5 m n o (H : R m n o) : R n m o.\n\n(** - Which of the following propositions are provable?\n - [R 1 1 2]\n - [R 2 2 6]\n\n - If we dropped constructor [c5] from the definition of [R],\n would the set of provable propositions change? Briefly (1\n sentence) explain your answer.\n\n - If we dropped constructor [c4] from the definition of [R],\n would the set of provable propositions change? Briefly (1\n sentence) explain your answer. *)\n\n\n(** **** Exercise: 3 stars, standard, optional (R_fact) \n\n The relation [R] above actually encodes a familiar function.\n Figure out which function; then state and prove this equivalence\n in Coq? *)\n\nDefinition fR : nat -> nat -> nat:=\n (fun (x y : nat) => (x + y)).\n\nTheorem R_equiv_fR : forall m n o, R m n o <-> fR m n = o.\nProof.\n intros.\n split.\n - (* -> *)\n intro.\n induction H; unfold fR.\n + reflexivity.\n + simpl. f_equal. apply IHR.\n + rewrite plus_comm. simpl. f_equal. rewrite plus_comm. apply IHR.\n + unfold fR in IHR. simpl in IHR. inversion IHR.\n rewrite <- plus_n_Sm in H1. inversion H1. reflexivity.\n + unfold fR in IHR. rewrite plus_comm in IHR. assumption.\n - (* <- *)\n intro.\n induction H. induction n.\n + induction m.\n * simpl. apply c1.\n * simpl. apply c2. apply IHm.\n + induction m.\n * simpl. apply c3. apply IHn.\n * simpl. apply c2. apply IHm. apply c3 in IHn. apply c4. apply IHn.\nQed.\n\n(** **** Exercise: 2 stars, advanced (subsequence) \n\n A list is a _subsequence_ of another list if all of the elements\n in the first list occur in the same order in the second list,\n possibly with some extra elements in between. For example,\n\n [1;2;3]\n\n is a subsequence of each of the lists\n\n [1;2;3]\n [1;1;1;2;2;3]\n [1;2;7;3]\n [5;6;1;9;9;2;7;3;8]\n\n but it is _not_ a subsequence of any of the lists\n\n [1;2]\n [1;3]\n [5;6;2;1;7;3;8].\n\n - Define an inductive proposition [subseq] on [list nat] that\n captures what it means to be a subsequence. (Hint: You'll need\n three cases.)\n\n - Prove [subseq_refl] that subsequence is reflexive, that is,\n any list is a subsequence of itself.\n\n - Prove [subseq_app] that for any lists [l1], [l2], and [l3],\n if [l1] is a subsequence of [l2], then [l1] is also a subsequence\n of [l2 ++ l3].\n\n - (Optional, harder) Prove [subseq_trans] that subsequence is\n transitive -- that is, if [l1] is a subsequence of [l2] and [l2]\n is a subsequence of [l3], then [l1] is a subsequence of [l3].\n Hint: choose your induction carefully! *)\n\nInductive subseq : list nat -> list nat -> Prop :=\n | sub_nil : forall l, subseq [] l\n | sub_cons1 : forall k l n, (subseq k l) -> (subseq k (n :: l))\n | sub_cons2 : forall k l n, (subseq k l) -> (subseq (n::k) (n::l))\n.\n\nTheorem subseq_refl : forall (l : list nat), subseq l l.\nProof.\n intros.\n induction l.\n - apply sub_nil.\n - apply sub_cons2. apply IHl.\nQed.\n\nTheorem subseq_app : forall (l1 l2 l3 : list nat),\n subseq l1 l2 ->\n subseq l1 (l2 ++ l3).\nProof.\n intros.\n induction H.\n - apply sub_nil.\n - simpl. apply sub_cons1. apply IHsubseq.\n - simpl. apply sub_cons2. apply IHsubseq.\nQed.\n\nTheorem subseq_trans : forall (l1 l2 l3 : list nat),\n subseq l1 l2 ->\n subseq l2 l3 ->\n subseq l1 l3.\nProof.\n intros l1 l2 l3 H1 H2. generalize dependent H1. generalize dependent l1.\n induction H2; intros.\n - inversion H1. apply sub_nil.\n - apply sub_cons1. apply IHsubseq. apply H1.\n - inversion H1.\n + apply sub_nil.\n + apply sub_cons1. apply IHsubseq. apply H3.\n + apply sub_cons2. apply IHsubseq. apply H3.\nQed.\n\n(** **** Exercise: 2 stars, standard, optional (R_provability2) \n\n Suppose we give Coq the following definition:\n\n Inductive R : nat -> list nat -> Prop :=\n | c1 : R 0 []\n | c2 n l (H: R n l) : R (S n) (n :: l)\n | c3 n l (H: R (S n) l) : R n l.\n\n Which of the following propositions are provable?\n\n - [R 2 [1;0]]\n - [R 1 [1;2;1;0]]\n - [R 6 [3;2;1;0]] *)\n\n(* FILL IN HERE\n\n [] *)\n\n\n\nInductive reg_exp (T : Type) : Type :=\n | EmptySet\n | EmptyStr\n | Char (t : T)\n | App (r1 r2 : reg_exp T)\n | Union (r1 r2 : reg_exp T)\n | Star (r : reg_exp T).\n\nArguments EmptySet {T}.\nArguments EmptyStr {T}.\nArguments Char {T} _.\nArguments App {T} _ _.\nArguments Union {T} _ _.\nArguments Star {T} _.\n\nReserved Notation \"s =~ re\" (at level 80).\n\nInductive exp_match {T} : list T -> reg_exp T -> Prop :=\n | MEmpty : [] =~ EmptyStr\n | MChar x : [x] =~ (Char x)\n | MApp s1 re1 s2 re2\n (H1 : s1 =~ re1)\n (H2 : s2 =~ re2)\n : (s1 ++ s2) =~ (App re1 re2)\n | MUnionL s1 re1 re2\n (H1 : s1 =~ re1)\n : s1 =~ (Union re1 re2)\n | MUnionR re1 s2 re2\n (H2 : s2 =~ re2)\n : s2 =~ (Union re1 re2)\n | MStar0 re : [] =~ (Star re)\n | MStarApp s1 s2 re\n (H1 : s1 =~ re)\n (H2 : s2 =~ (Star re))\n : (s1 ++ s2) =~ (Star re)\n where \"s =~ re\" := (exp_match s re).\n\nFixpoint reg_exp_of_list {T} (l : list T) :=\n match l with\n | [] => EmptyStr\n | x :: l' => App (Char x) (reg_exp_of_list l')\n end.\n\nLemma MStar1 :\n forall T s (re : reg_exp T) ,\n s =~ re ->\n s =~ Star re.\nProof.\n intros T s re H.\n rewrite <- (app_nil_r _ s).\n apply (MStarApp s [] re).\n - apply H.\n - apply MStar0.\nQed.\n\n\n(** **** Exercise: 3 stars, standard (exp_match_ex1) \n\n The following lemmas show that the informal matching rules given\n at the beginning of the chapter can be obtained from the formal\n inductive definition. *)\n\nLemma empty_is_empty : forall T (s : list T),\n ~ (s =~ EmptySet).\nProof.\n intros T s H.\n inversion H.\nQed.\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : reg_exp T),\n s =~ re1 \\/ s =~ re2 ->\n s =~ Union re1 re2.\nProof.\n intros T s re1 re2 H.\n destruct H.\n - apply MUnionL. apply H.\n - apply MUnionR. apply H.\nQed.\n\n(** The next lemma is stated in terms of the [fold] function from the\n [Poly] chapter: If [ss : list (list T)] represents a sequence of\n strings [s1, ..., sn], then [fold app ss []] is the result of\n concatenating them all together. *)\n\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp T),\n (forall s, In s ss -> s =~ re) ->\n fold app ss [] =~ Star re.\nProof.\n intros T ss re H.\n induction ss as [|ss'].\n - simpl. apply MStar0.\n - simpl. apply MStarApp.\n + apply H. simpl. left. reflexivity.\n + apply IHss. intros. apply H. simpl. right. apply H0.\nQed.\n\n(** **** Exercise: 4 stars, standard, optional (reg_exp_of_list_spec) \n\n Prove that [reg_exp_of_list] satisfies the following\n specification: *)\nLemma add_to_app: forall S (x:S) y, [x]++y = x::y.\nProof.\n intros S x y. simpl. reflexivity.\nQed.\n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof.\n intros T s1 s2. \n generalize dependent s1.\n induction s2 as [|h t].\n - (* s2 = [] *)\n split. \n + intros H. simpl in H. inversion H. reflexivity.\n + intros H. simpl. rewrite H. apply MEmpty.\n - (* s2 = h::t *)\n intros s1. split. \n + intros H. simpl in H. inversion H. \n inversion H3. simpl. \n rewrite (IHt s2) in H4. rewrite H4. reflexivity.\n + intros H. simpl. rewrite H.\n rewrite <- add_to_app. apply MApp.\n * apply MChar.\n * apply IHt. reflexivity.\nQed.\n\n\nFixpoint re_chars {T} (re : reg_exp T) : list T :=\n match re with\n | EmptySet => []\n | EmptyStr => []\n | Char x => [x]\n | App re1 re2 => re_chars re1 ++ re_chars re2\n | Union re1 re2 => re_chars re1 ++ re_chars re2\n | Star re => re_chars re\n end.\n\nTheorem in_re_match : forall T (s : list T) (re : reg_exp T) (x : T),\n s =~ re ->\n In x s ->\n In x (re_chars re).\nProof.\n intros T s re x Hmatch Hin.\n induction Hmatch\n as [| x'\n | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2].\n - (* MEmpty *)\n simpl in Hin. destruct Hin.\n - (* MChar *)\n simpl. simpl in Hin.\n apply Hin.\n - (* MApp *)\n simpl.\n\n(** Something interesting happens in the [MApp] case. We obtain\n _two_ induction hypotheses: One that applies when [x] occurs in\n [s1] (which matches [re1]), and a second one that applies when [x]\n occurs in [s2] (which matches [re2]). *)\n\n rewrite In_app_iff in *.\n destruct Hin as [Hin | Hin].\n + (* In x s1 *)\n left. apply (IH1 Hin).\n + (* In x s2 *)\n right. apply (IH2 Hin).\n - (* MUnionL *)\n simpl. rewrite In_app_iff.\n left. apply (IH Hin).\n - (* MUnionR *)\n simpl. rewrite In_app_iff.\n right. apply (IH Hin).\n - (* MStar0 *)\n destruct Hin.\n - (* MStarApp *)\n simpl.\n\n(** Here again we get two induction hypotheses, and they illustrate\n why we need induction on evidence for [exp_match], rather than\n induction on the regular expression [re]: The latter would only\n provide an induction hypothesis for strings that match [re], which\n would not allow us to reason about the case [In x s2]. *)\n\n rewrite In_app_iff in Hin.\n destruct Hin as [Hin | Hin].\n + (* In x s1 *)\n apply (IH1 Hin).\n + (* In x s2 *)\n apply (IH2 Hin).\nQed.\n\n\n\n\n(** **** Exercise: 4 stars, standard (re_not_empty) \n\n Write a recursive function [re_not_empty] that tests whether a\n regular expression matches some string. Prove that your function\n is correct. *)\n\nFixpoint re_not_empty {T : Type} (re : reg_exp T) : bool :=\n match re with\n | EmptySet => false\n | EmptyStr => true\n | Char _ => true\n | App re1 re2 => andb (re_not_empty re1) (re_not_empty re2)\n | Union re1 re2 => orb (re_not_empty re1) (re_not_empty re2)\n | Star re1 => true\n end.\n\nLemma re_not_empty_correct : forall T (re : reg_exp T),\n (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n intros T re.\n split.\n - intros [s H].\n induction H.\n + (* EmptyStr *) reflexivity.\n + (* Char *) reflexivity.\n + (* App *) simpl. rewrite IHexp_match1. rewrite IHexp_match2. reflexivity.\n + (* UnionL *) simpl. rewrite IHexp_match. reflexivity.\n + (* UnionR *) simpl. rewrite IHexp_match. destruct (re_not_empty re1); reflexivity.\n + (* Star0 *) reflexivity.\n + (* StarApp *) reflexivity.\n - intros H.\n induction re.\n + (* EmptySet *) discriminate H.\n + (* EmptyStr *) exists []. apply MEmpty.\n + (* Char *) exists [t]. apply MChar.\n + (* App *) simpl in H. rewrite andb_true_iff in H. destruct H as [H1 H2].\n apply IHre1 in H1. destruct H1 as [s1 H1].\n apply IHre2 in H2. destruct H2 as [s2 H2].\n exists (s1++s2). apply MApp; assumption.\n + (* Union *) simpl in H. rewrite orb_true_iff in H.\n destruct H as [H1 | H2].\n * apply IHre1 in H1. destruct H1. exists x. apply MUnionL. apply H.\n * apply IHre2 in H2. destruct H2. exists x. apply MUnionR. apply H.\n + (* Start *) exists []. apply MStar0.\nQed.\n\n\n(** **** Exercise: 4 stars, standard, optional (exp_match_ex2) *)\n\n(** The [MStar''] lemma below (combined with its converse, the\n [MStar'] exercise above), shows that our definition of [exp_match]\n for [Star] is equivalent to the informal one given previously. *)\n\nLemma MStar'' : forall T (s : list T) (re : reg_exp T),\n s =~ Star re ->\n exists ss : list (list T),\n s = fold app ss []\n /\\ forall s', In s' ss -> s' =~ re.\nProof.\n intros T s re H.\n remember (Star re) as re'.\n induction H\n as [|x'|s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n |s1 re1 re2 Hmatch IH|re1 s2 re2 Hmatch IH\n |re''|s1 s2 re'' Hmatch1 IH1 Hmatch2 IH2].\n - inversion Heqre'.\n - inversion Heqre'.\n - inversion Heqre'.\n - inversion Heqre'.\n - inversion Heqre'.\n - (* Star 0 *)\n exists []. split.\n + reflexivity. \n + intros s' H. inversion H.\n - (* Star *)\n destruct (IH2 Heqre') as [ss' [L R]].\n exists (s1::ss'). split.\n + simpl. rewrite <- L. reflexivity.\n + intros s' H. destruct H.\n * rewrite <- H. inversion Heqre'. rewrite H1 in Hmatch1. apply Hmatch1.\n * apply R. apply H.\nQed.\n\n\n\n\n(** **** Exercise: 5 stars, advanced (weak_pumping) \n\n One of the first really interesting theorems in the theory of\n regular expressions is the so-called _pumping lemma_, which\n states, informally, that any sufficiently long string [s] matching\n a regular expression [re] can be \"pumped\" by repeating some middle\n section of [s] an arbitrary number of times to produce a new\n string also matching [re]. (For the sake of simplicity in this\n exercise, we consider a slightly weaker theorem than is usually\n stated in courses on automata theory.)\n\n To get started, we need to define \"sufficiently long.\" Since we\n are working in a constructive logic, we actually need to be able\n to calculate, for each regular expression [re], the minimum length\n for strings [s] to guarantee \"pumpability.\" *)\n\nModule Pumping.\n\nFixpoint pumping_constant {T} (re : reg_exp T) : nat :=\n match re with\n | EmptySet => 1\n | EmptyStr => 1\n | Char _ => 2\n | App re1 re2 =>\n pumping_constant re1 + pumping_constant re2\n | Union re1 re2 =>\n pumping_constant re1 + pumping_constant re2\n | Star r => pumping_constant r\n end.\n\n(** You may find these lemmas about the pumping constant useful when\n proving the pumping lemma below. *)\n\nLemma pumping_constant_ge_1 :\n forall T (re : reg_exp T),\n 1 <= pumping_constant re.\nProof.\n intros T re. induction re.\n - (* Emptyset *)\n apply le_n.\n - (* EmptyStr *)\n apply le_n.\n - (* Char *)\n apply le_S. apply le_n.\n - (* App *)\n simpl.\n apply le_trans with (n:=pumping_constant re1).\n apply IHre1. apply le_plus_l.\n - (* Union *)\n simpl.\n apply le_trans with (n:=pumping_constant re1).\n apply IHre1. apply le_plus_l.\n - (* Star *)\n simpl. apply IHre.\nQed.\n\nLemma pumping_constant_0_false :\n forall T (re : reg_exp T),\n pumping_constant re = 0 -> False.\nProof.\n intros T re H.\n assert (Hp1 : 1 <= pumping_constant re).\n { apply pumping_constant_ge_1. }\n inversion Hp1.\n - rewrite H in H2. discriminate H2.\n - rewrite H in H0. discriminate H0.\nQed.\n\n(** Next, it is useful to define an auxiliary function that repeats a\n string (appends it to itself) some number of times. *)\n\nFixpoint napp {T} (n : nat) (l : list T) : list T :=\n match n with\n | 0 => []\n | S n' => l ++ napp n' l\n end.\n\n(** This auxiliary lemma might also be useful in your proof of the\n pumping lemma. *)\n\nLemma napp_plus: forall T (n m : nat) (l : list T),\n napp (n + m) l = napp n l ++ napp m l.\nProof.\n intros T n m l.\n induction n as [|n IHn].\n - reflexivity.\n - simpl. rewrite IHn, app_assoc. reflexivity.\nQed.\n\nLemma napp_star :\n forall T m s1 s2 (re : reg_exp T),\n s1 =~ re -> s2 =~ Star re ->\n napp m s1 ++ s2 =~ Star re.\nProof.\n intros T m s1 s2 re Hs1 Hs2.\n induction m.\n - simpl. apply Hs2.\n - simpl. rewrite <- app_assoc.\n apply MStarApp.\n + apply Hs1.\n + apply IHm.\nQed.\n\n\n(** The (weak) pumping lemma itself says that, if [s =~ re] and if the\n length of [s] is at least the pumping constant of [re], then [s]\n can be split into three substrings [s1 ++ s2 ++ s3] in such a way\n that [s2] can be repeated any number of times and the result, when\n combined with [s1] and [s3] will still match [re]. Since [s2] is\n also guaranteed not to be the empty string, this gives us\n a (constructive!) way to generate strings matching [re] that are\n as long as we like. *)\n\nLemma plus_le_one: forall n m,\n 1 <= n + m -> 1 <= n \\/ 1 <= m.\nProof.\n intros.\n generalize dependent n.\n induction m.\n - intros n H. left. replace n with (n + 0).\n + assumption.\n + rewrite plus_n_O. reflexivity.\n - intros n H.\n right.\n apply n_le_m__Sn_le_Sm.\n apply O_le_n.\nQed.\n\nLemma length_le_one__neq_empty: forall (X:Type) (s:list X),\n 1 <= length s -> s <> [].\nProof.\n intros.\n induction s.\n + simpl in H. apply Sn_le_O in H. apply ex_falso_quodlibet. assumption.\n + unfold not. intros. rewrite H0 in H. simpl in H. apply Sn_le_O in H.\n assumption.\nQed.\n\nLemma app_star: forall T (s1 s2 : list T) (re : reg_exp T),\n s1 =~ Star re ->\n s2 =~ Star re ->\n s1 ++ s2 =~ Star re.\nProof.\n intros T s1 s2 re H1.\n remember (Star re) as re'.\n generalize dependent s2.\n induction H1\n as [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n |s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH\n |re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n - (* MEmpty *) inversion Heqre'.\n - (* MChar *) inversion Heqre'.\n - (* MApp *) inversion Heqre'.\n - (* MUnionL *) inversion Heqre'.\n - (* MUnionR *) inversion Heqre'.\n - (* MStar0 *)\n inversion Heqre'. intros s H. apply H.\n - (* MStarApp *)\n inversion Heqre'. rewrite H0 in IH2, Hmatch1.\n intros s2 H1. rewrite <- app_assoc.\n apply MStarApp.\n + apply Hmatch1.\n + apply IH2.\n * reflexivity.\n * apply H1.\nQed.\n\nLemma weak_pumping : forall T (re : reg_exp T) s,\n s =~ re ->\n pumping_constant re <= length s ->\n exists s1 s2 s3,\n s = s1 ++ s2 ++ s3 /\\\n s2 <> [] /\\\n forall m, s1 ++ napp m s2 ++ s3 =~ re.\n\n(** You are to fill in the proof. Several of the lemmas about\n [le] that were in an optional exercise earlier in this chapter\n may be useful. *)\nProof.\n intros T re s Hmatch.\n induction Hmatch\n as [ | x | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2 ].\n - (* MEmpty *)\n simpl. intros contra. inversion contra.\n - (* Char *)\n simpl. intros contra. inversion contra. inversion H1.\n - (* App *)\n simpl. rewrite app_length. intros H. apply add_le_cases in H. destruct H as [H1 | H2].\n + apply IH1 in H1. destruct H1 as [s2' [s3' [s4' [H0 [H1 H2]]]]].\n exists s2'. exists s3'. exists (s4'++s2). split.\n * rewrite H0. rewrite <- app_assoc. rewrite <- app_assoc. reflexivity.\n * split. apply H1.\n intros.\n replace (s2' ++ napp m s3' ++ s4' ++ s2) with ((s2' ++ napp m s3' ++ s4') ++ s2).\n apply (MApp (s2' ++ napp m s3' ++ s4')).\n apply H2.\n apply Hmatch2.\n rewrite <- app_assoc. rewrite <- app_assoc. reflexivity.\n + apply IH2 in H2. inversion H2 as [s2' [s3' [s4' [H0' [H1' H2']]]]].\n exists (s1++s2'). exists s3'. exists s4'.\n split.\n * rewrite H0'. rewrite <- app_assoc. reflexivity.\n * split. apply H1'.\n intros.\n rewrite <- app_assoc.\n apply MApp.\n apply Hmatch1.\n apply H2'.\n - (* Union L*)\n simpl. intros. apply plus_le in H as [H1 H2].\n apply IH in H1. inversion H1 as [s2' [s3' [s4' [H3 [H4 H5]]]]].\n exists s2'. exists s3'. exists s4'. split.\n + rewrite H3. reflexivity.\n + split.\n * apply H4.\n * intros. apply MUnionL. apply H5.\n - (* Union R*)\n simpl. intros. apply plus_le in H as [H1 H2].\n apply IH in H2. inversion H2 as [s2' [s3' [s4' [H3 [H4 H5]]]]].\n exists s2'. exists s3'. exists s4'. split.\n + rewrite H3. reflexivity.\n + split.\n * apply H4.\n * intros. apply MUnionR. apply H5.\n - (* Star *)\n simpl. intros. inversion H. apply pumping_constant_0_false in H2.\n apply ex_falso_quodlibet. apply H2.\n - (* Star *)\n simpl. simpl in IH2. intros. rewrite app_length in H.\n assert (Ht: 1 <= pumping_constant re).\n { apply pumping_constant_ge_1. }\n assert (H1: 1 <= length s1 + length s2).\n { apply le_trans with (n:= pumping_constant re). apply Ht. apply H. }\n assert (H2: 1 <= length s1 \\/ 1 <= length s2).\n { apply plus_le_one in H1. apply H1. }\n destruct H2.\n + exists []. exists s1. exists s2.\n split.\n * reflexivity.\n * split.\n (* s1 <> [ ] *)\n unfold not. intro.\n assert (H2': length s1 = 0).\n { rewrite H2. reflexivity. }\n rewrite H2' in H0. apply Sn_le_O in H0. assumption.\n (* forall m : nat, [ ] ++ napp m s1 ++ s2 =~ Star re *)\n intros m. simpl. apply napp_star; assumption.\n + exists s1. exists s2. exists [].\n split.\n * rewrite app_nil_r. reflexivity.\n * split.\n (* s2 <> [ ] *)\n unfold not. intro.\n assert (H2': length s2 = 0).\n { rewrite H2. reflexivity. }\n rewrite H2' in H0. apply Sn_le_O in H0. assumption.\n (* forall m : nat, s1 ++ napp m s2 ++ [ ] =~ Star re *)\n intros m. rewrite app_nil_r. \n apply app_star. replace s1 with (s1 ++ []). apply MStarApp. apply Hmatch1. \n apply MStar0. rewrite app_nil_r. reflexivity.\n induction m.\n { simpl. apply MStar0. }\n { simpl. apply app_star. apply Hmatch2. apply IHm. }\nQed.\n\n(** **** Exercise: 5 stars, advanced, optional (pumping) \n\n Now here is the usual version of the pumping lemma. In addition to\n requiring that [s2 <> []], it also requires that [length s1 +\n length s2 <= pumping_constant re]. *)\n\nLemma app_length_le: forall (X:Type) (s1 s2:list X),\n length s2 <= length (s1 ++ s2).\nProof.\n intros.\n induction s1.\n - simpl. apply le_n.\n - simpl. apply le_S. apply IHs1.\nQed.\n\nLemma pumping : forall T (re : reg_exp T) s,\n s =~ re ->\n pumping_constant re <= length s ->\n exists s1 s2 s3,\n s = s1 ++ s2 ++ s3 /\\\n s2 <> [] /\\\n length s1 + length s2 <= pumping_constant re /\\\n forall m, s1 ++ napp m s2 ++ s3 =~ re.\n\n(** You may want to copy your proof of weak_pumping below. *)\nProof.\n intros T re s Hmatch.\n induction Hmatch\n as [ | x | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2 ].\n - simpl. intros contra. inversion contra.\n - simpl. intros contra. inversion contra. inversion H1.\n - simpl. intros. rewrite app_length in H. apply add_le_cases in H. destruct H as [H1|H2].\n + apply IH1 in H1. destruct H1 as [s2' [s3' [s4' [H1 [H2 H3]]]]].\n exists s2'. exists s3'. exists (s4' ++ s2). split.\n * rewrite H1. rewrite <- app_assoc. rewrite <- app_assoc. reflexivity.\n * split. apply H2.\n destruct H3.\n split.\n { apply le_trans with (n:= pumping_constant re1). apply H. apply le_plus_l. }\n { intros.\n replace (s2' ++ napp m s3' ++ s4' ++ s2) with ((s2' ++ napp m s3' ++ s4') ++ s2).\n apply (MApp (s2' ++ napp m s3' ++ s4')). apply H0. apply Hmatch2.\n rewrite <- app_assoc. rewrite <- app_assoc. reflexivity. }\n + apply IH2 in H2. inversion H2 as [s2' [s3' [s4' [H1' [H2' H3']]]]].\n exists (s1++s2'). exists (s3'). exists s4'.\n split.\n * rewrite H1'. rewrite <- app_assoc. reflexivity.\n * split. apply H2'.\n split.\n { destruct H3' as [H3' H4']. rewrite app_length.\n apply le_trans with (n:=pumping_constant re2).\n Admitted. }\n\nEnd Pumping.\n\n\nInductive reflect (P : Prop) : bool -> Prop :=\n| ReflectT (H : P) : reflect P true\n| ReflectF (H : ~ P) : reflect P false.\n\nTheorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.\nProof.\n intros P b H. destruct b.\n - apply ReflectT. rewrite H. reflexivity.\n - apply ReflectF. rewrite H. intros H'. discriminate.\nQed.\n\n(** **** Exercise: 2 stars, standard, recommended (reflect_iff) *)\nTheorem reflect_iff : forall P b, reflect P b -> (P <-> b = true).\nProof.\n intros P b H. destruct H.\n - split.\n + (* -> *) reflexivity.\n + intros. assumption.\n - split.\n + intros. apply ex_falso_quodlibet. apply H. apply H0.\n + intros. discriminate.\nQed.\n\nTheorem eqb_refl : forall n : nat,\n true = (n =? n).\nProof.\n intros.\n induction n.\n - reflexivity.\n - simpl. assumption.\nQed.\n\nTheorem eqb_eq : forall n1 n2 : nat,\n n1 =? n2 = true <-> n1 = n2.\nProof.\n intros n1 n2. split.\n - apply eqb_true.\n - intros H. rewrite H. rewrite <- eqb_refl. reflexivity.\nQed.\n\nLemma eqbP : forall n m, reflect (n = m) (n =? m).\nProof.\n intros n m. apply iff_reflect. rewrite eqb_eq. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, standard, recommended (eqbP_practice) \n\n Use [eqbP] as above to prove the following: *)\n\nFixpoint count n l :=\n match l with\n | [] => 0\n | m :: l' => (if n =? m then 1 else 0) + count n l'\n end.\n\nTheorem eqbP_practice : forall n l,\n count n l = 0 -> ~(In n l).\nProof.\n intros n.\n induction l.\n - unfold not. intros. simpl in H0. assumption.\n - simpl. destruct (eqbP n x) as [H1|H1].\n + intros. unfold not. intros. inversion H.\n + intros. unfold not. intros. apply IHl in H. destruct H0.\n * unfold not in H1. symmetry in H0. apply H1 in H0. assumption.\n * apply H. apply H0.\nQed.\n\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars, standard, recommended (nostutter_defn) \n\n Formulating inductive definitions of properties is an important\n skill you'll need in this course. Try to solve this exercise\n without any help at all.\n\n We say that a list \"stutters\" if it repeats the same element\n consecutively. (This is different from not containing duplicates:\n the sequence [[1;4;1]] repeats the element [1] but does not\n stutter.) The property \"[nostutter mylist]\" means that [mylist]\n does not stutter. Formulate an inductive definition for\n [nostutter]. *)\n\nInductive nostutter {X:Type} : list X -> Prop :=\n | ns_nil : nostutter []\n | ns_one : forall x, nostutter [x]\n | ns_con : forall x h t, nostutter (h :: t) -> ~ (x = h) -> nostutter (x :: h :: t)\n.\n\n(** Make sure each of these tests succeeds, but feel free to change\n the suggested proof (in comments) if the given one doesn't work\n for you. Your definition might be different from ours and still\n be correct, in which case the examples might need a different\n proof. (You'll notice that the suggested proofs use a number of\n tactics we haven't talked about, to make them more robust to\n different possible ways of defining [nostutter]. You can probably\n just uncomment and use them as-is, but you can also prove each\n example with more basic tactics.) *)\n\nExample test_nostutter_1: nostutter [3;1;4;1;5;6].\n Proof. repeat constructor; apply eqb_neq; auto.\n Qed.\n\nExample test_nostutter_2: nostutter (@nil nat).\n Proof. repeat constructor; apply eqb_neq; auto.\n Qed.\n\nExample test_nostutter_3: nostutter [5].\n Proof. repeat constructor; apply eqb_false; auto. Qed.\n\nExample test_nostutter_4: not (nostutter [3;1;1;4]).\n Proof. intro.\n repeat match goal with\n h: nostutter _ |- _ => inversion h; clear h; subst\n end.\n contradiction; auto.\nQed.\n\n(** **** Exercise: 4 stars, advanced (filter_challenge) \n\n Let's prove that our definition of [filter] from the [Poly]\n chapter matches an abstract specification. Here is the\n specification, written out informally in English:\n\n A list [l] is an \"in-order merge\" of [l1] and [l2] if it contains\n all the same elements as [l1] and [l2], in the same order as [l1]\n and [l2], but possibly interleaved. For example,\n\n [1;4;6;2;3]\n\n is an in-order merge of\n\n [1;6;2]\n\n and\n\n [4;3].\n\n Now, suppose we have a set [X], a function [test: X->bool], and a\n list [l] of type [list X]. Suppose further that [l] is an\n in-order merge of two lists, [l1] and [l2], such that every item\n in [l1] satisfies [test] and no item in [l2] satisfies test. Then\n [filter test l = l1].\n\n Translate this specification into a Coq theorem and prove\n it. (You'll need to begin by defining what it means for one list\n to be a merge of two others. Do this with an inductive relation,\n not a [Fixpoint].) *)\n\n(* FILL IN HERE *)\n\n\n(** **** Exercise: 5 stars, advanced, optional (filter_challenge_2) \n\n A different way to characterize the behavior of [filter] goes like\n this: Among all subsequences of [l] with the property that [test]\n evaluates to [true] on all their members, [filter test l] is the\n longest. Formalize this claim and prove it. *)\n\n(* FILL IN HERE *)\n\n(** **** Exercise: 4 stars, standard, optional (palindromes) \n\n A palindrome is a sequence that reads the same backwards as\n forwards.\n\n - Define an inductive proposition [pal] on [list X] that\n captures what it means to be a palindrome. (Hint: You'll need\n three cases. Your definition should be based on the structure\n of the list; just having a single constructor like\n\n c : forall l, l = rev l -> pal l\n\n may seem obvious, but will not work very well.)\n\n - Prove ([pal_app_rev]) that\n\n forall l, pal (l ++ rev l).\n\n - Prove ([pal_rev] that)\n\n forall l, pal l -> l = rev l.\n*)\n\n(* FILL IN HERE *)\n\n\n(** **** Exercise: 5 stars, standard, optional (palindrome_converse) \n\n Again, the converse direction is significantly more difficult, due\n to the lack of evidence. Using your definition of [pal] from the\n previous exercise, prove that\n\n forall l, l = rev l -> pal l.\n*)\n\n(* FILL IN HERE\n\n [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (NoDup) \n\n Recall the definition of the [In] property from the [Logic]\n chapter, which asserts that a value [x] appears at least once in a\n list [l]: *)\n\n(* Fixpoint In (A : Type) (x : A) (l : list A) : Prop :=\n match l with\n | [] => False\n | x' :: l' => x' = x \\/ In A x l'\n end *)\n\n(** Your first task is to use [In] to define a proposition [disjoint X\n l1 l2], which should be provable exactly when [l1] and [l2] are\n lists (with elements of type X) that have no elements in\n common. *)\n\n(* FILL IN HERE *)\n\n(** Next, use [In] to define an inductive proposition [NoDup X\n l], which should be provable exactly when [l] is a list (with\n elements of type [X]) where every member is different from every\n other. For example, [NoDup nat [1;2;3;4]] and [NoDup\n bool []] should be provable, while [NoDup nat [1;2;1]] and\n [NoDup bool [true;true]] should not be. *)\n\n(* FILL IN HERE *)\n\n(** Finally, state and prove one or more interesting theorems relating\n [disjoint], [NoDup] and [++] (list append). *)\n\n(* FILL IN HERE *)\n\n(** **** Exercise: 4 stars, advanced, optional (pigeonhole_principle) \n\n The _pigeonhole principle_ states a basic fact about counting: if\n we distribute more than [n] items into [n] pigeonholes, some\n pigeonhole must contain at least two items. As often happens, this\n apparently trivial fact about numbers requires non-trivial\n machinery to prove, but we now have enough... *)\n\n(** First prove an easy useful lemma. *)\n\nLemma in_split : forall (X:Type) (x:X) (l:list X),\n In x l ->\n exists l1 l2, l = l1 ++ x :: l2.\nProof.\n intros.\n induction l as [| h t].\n - apply ex_falso_quodlibet. simpl in H. assumption.\n - inversion H.\n + exists []. exists t. rewrite H0. reflexivity. \n + apply IHt in H0. inversion H0 as [l1 [l2]].\n exists (h :: l1). exists l2. simpl. rewrite H1. reflexivity.\nQed.\n\n(** Now define a property [repeats] such that [repeats X l] asserts\n that [l] contains at least one repeated element (of type [X]). *)\n\nInductive repeats {X:Type} : list X -> Prop :=\n | repeats_in : forall (x:X) (l : list X), In x l -> repeats (x :: l)\n | repeats_nin : forall (x:X) (l : list X), repeats l -> repeats (x :: l)\n.\n\n(** Now, here's a way to formalize the pigeonhole principle. Suppose\n list [l2] represents a list of pigeonhole labels, and list [l1]\n represents the labels assigned to a list of items. If there are\n more items than labels, at least two items must have the same\n label -- i.e., list [l1] must contain repeats.\n\n This proof is much easier if you use the [excluded_middle]\n hypothesis to show that [In] is decidable, i.e., [forall x l, (In x\n l) \\/ ~ (In x l)]. However, it is also possible to make the proof\n go through _without_ assuming that [In] is decidable; if you\n manage to do this, you will not need the [excluded_middle]\n hypothesis. *)\n\nTheorem pigeonhole_principle: forall (X:Type) (l1 l2:list X),\n excluded_middle ->\n (forall x, In x l1 -> In x l2) ->\n length l2 < length l1 ->\n repeats l1.\nProof.\n intros X l1. induction l1 as [|x l1' IHl1'].\n - intros. destruct l2.\n + inversion H1.\n + inversion H1.\n - intros. apply repeats_in. inversion H1.\n + Admitted.\n\n\nRequire Import Coq.Strings.Ascii.\n(** ** Extended Exercise: A Verified Regular-Expression Matcher *)\n\n(** We have now defined a match relation over regular expressions and\n polymorphic lists. We can use such a definition to manually prove that\n a given regex matches a given string, but it does not give us a\n program that we can run to determine a match autmatically.\n\n It would be reasonable to hope that we can translate the definitions\n of the inductive rules for constructing evidence of the match relation\n into cases of a recursive function that reflects the relation by recursing\n on a given regex. However, it does not seem straightforward to define\n such a function in which the given regex is a recursion variable\n recognized by Coq. As a result, Coq will not accept that the function\n always terminates.\n\n Heavily-optimized regex matchers match a regex by translating a given\n regex into a state machine and determining if the state machine\n accepts a given string. However, regex matching can also be\n implemented using an algorithm that operates purely on strings and\n regexes without defining and maintaining additional datatypes, such as\n state machines. We'll implemement such an algorithm, and verify that\n its value reflects the match relation. *)\n\n(** We will implement a regex matcher that matches strings represented\n as lists of ASCII characters: *)\n\n\nDefinition string := list ascii.\n\n(** The Coq standard library contains a distinct inductive definition\n of strings of ASCII characters. However, we will use the above\n definition of strings as lists as ASCII characters in order to apply\n the existing definition of the match relation.\n\n We could also define a regex matcher over polymorphic lists, not lists\n of ASCII characters specifically. The matching algorithm that we will\n implement needs to be able to test equality of elements in a given\n list, and thus needs to be given an equality-testing\n function. Generalizing the definitions, theorems, and proofs that we\n define for such a setting is a bit tedious, but workable. *)\n\n(** The proof of correctness of the regex matcher will combine\n properties of the regex-matching function with properties of the\n [match] relation that do not depend on the matching function. We'll go\n ahead and prove the latter class of properties now. Most of them have\n straightforward proofs, which have been given to you, although there\n are a few key lemmas that are left for you to prove. *)\n\n(** Each provable [Prop] is equivalent to [True]. *)\nLemma provable_equiv_true : forall (P : Prop), P -> (P <-> True).\nProof.\n intros.\n split.\n - intros. constructor.\n - intros _. apply H.\nQed.\n\n(** Each [Prop] whose negation is provable is equivalent to [False]. *)\nLemma not_equiv_false : forall (P : Prop), ~P -> (P <-> False).\nProof.\n intros.\n split.\n - apply H.\n - intros. destruct H0.\nQed.\n\n(** [EmptySet] matches no string. *)\nLemma null_matches_none : forall (s : string), (s =~ EmptySet) <-> False.\nProof.\n intros.\n apply not_equiv_false.\n unfold not. intros. inversion H.\nQed.\n\n(** [EmptyStr] only matches the empty string. *)\nLemma empty_matches_eps : forall (s : string), s =~ EmptyStr <-> s = [ ].\nProof.\n split.\n - intros. inversion H. reflexivity.\n - intros. rewrite H. apply MEmpty.\nQed.\n\n(** [EmptyStr] matches no non-empty string. *)\nLemma empty_nomatch_ne : forall (a : ascii) s, (a :: s =~ EmptyStr) <-> False.\nProof.\n intros.\n apply not_equiv_false.\n unfold not. intros. inversion H.\nQed.\n\n(** [Char a] matches no string that starts with a non-[a] character. *)\nLemma char_nomatch_char :\n forall (a b : ascii) s, b <> a -> (b :: s =~ Char a <-> False).\nProof.\n intros.\n apply not_equiv_false.\n unfold not.\n intros.\n apply H.\n inversion H0.\n reflexivity.\nQed.\n\n(** If [Char a] matches a non-empty string, then the string's tail is empty. *)\nLemma char_eps_suffix : forall (a : ascii) s, a :: s =~ Char a <-> s = [ ].\nProof.\n split.\n - intros. inversion H. reflexivity.\n - intros. rewrite H. apply MChar.\nQed.\n\n(** [App re0 re1] matches string [s] iff [s = s0 ++ s1], where [s0]\n matches [re0] and [s1] matches [re1]. *)\nLemma app_exists : forall (s : string) re0 re1,\n s =~ App re0 re1 <->\n exists s0 s1, s = s0 ++ s1 /\\ s0 =~ re0 /\\ s1 =~ re1.\nProof.\n intros.\n split.\n - intros. inversion H. exists s1, s2. split.\n * reflexivity.\n * split. apply H3. apply H4.\n - intros [ s0 [ s1 [ Happ [ Hmat0 Hmat1 ] ] ] ].\n rewrite Happ. apply (MApp s0 _ s1 _ Hmat0 Hmat1).\nQed.\n\n(** **** Exercise: 3 stars, standard, optional (app_ne) \n\n [App re0 re1] matches [a::s] iff [re0] matches the empty string\n and [a::s] matches [re1] or [s=s0++s1], where [a::s0] matches [re0]\n and [s1] matches [re1].\n\n Even though this is a property of purely the match relation, it is a\n critical observation behind the design of our regex matcher. So (1)\n take time to understand it, (2) prove it, and (3) look for how you'll\n use it later. *)\nLemma app_ne : forall (a : ascii) s re0 re1,\n a :: s =~ (App re0 re1) <->\n ([ ] =~ re0 /\\ a :: s =~ re1) \\/\n exists s0 s1, s = s0 ++ s1 /\\ a :: s0 =~ re0 /\\ s1 =~ re1.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** [s] matches [Union re0 re1] iff [s] matches [re0] or [s] matches [re1]. *)\nLemma union_disj : forall (s : string) re0 re1,\n s =~ Union re0 re1 <-> s =~ re0 \\/ s =~ re1.\nProof.\n intros. split.\n - intros. inversion H.\n + left. apply H2.\n + right. apply H1.\n - intros [ H | H ].\n + apply MUnionL. apply H.\n + apply MUnionR. apply H.\nQed.\n\n(** **** Exercise: 3 stars, standard, optional (star_ne) \n\n [a::s] matches [Star re] iff [s = s0 ++ s1], where [a::s0] matches\n [re] and [s1] matches [Star re]. Like [app_ne], this observation is\n critical, so understand it, prove it, and keep it in mind.\n\n Hint: you'll need to perform induction. There are quite a few\n reasonable candidates for [Prop]'s to prove by induction. The only one\n that will work is splitting the [iff] into two implications and\n proving one by induction on the evidence for [a :: s =~ Star re]. The\n other implication can be proved without induction.\n\n In order to prove the right property by induction, you'll need to\n rephrase [a :: s =~ Star re] to be a [Prop] over general variables,\n using the [remember] tactic. *)\n\nLemma star_ne : forall (a : ascii) s re,\n a :: s =~ Star re <->\n exists s0 s1, s = s0 ++ s1 /\\ a :: s0 =~ re /\\ s1 =~ Star re.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The definition of our regex matcher will include two fixpoint\n functions. The first function, given regex [re], will evaluate to a\n value that reflects whether [re] matches the empty string. The\n function will satisfy the following property: *)\nDefinition refl_matches_eps m :=\n forall re : reg_exp ascii, reflect ([ ] =~ re) (m re).\n\n(** **** Exercise: 2 stars, standard, optional (match_eps) \n\n Complete the definition of [match_eps] so that it tests if a given\n regex matches the empty string: *)\nFixpoint match_eps (re: reg_exp ascii) : bool\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (match_eps_refl) \n\n Now, prove that [match_eps] indeed tests if a given regex matches\n the empty string. (Hint: You'll want to use the reflection lemmas\n [ReflectT] and [ReflectF].) *)\nLemma match_eps_refl : refl_matches_eps match_eps.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** We'll define other functions that use [match_eps]. However, the\n only property of [match_eps] that you'll need to use in all proofs\n over these functions is [match_eps_refl]. *)\n\n(** The key operation that will be performed by our regex matcher will\n be to iteratively construct a sequence of regex derivatives. For each\n character [a] and regex [re], the derivative of [re] on [a] is a regex\n that matches all suffixes of strings matched by [re] that start with\n [a]. I.e., [re'] is a derivative of [re] on [a] if they satisfy the\n following relation: *)\n\nDefinition is_der re (a : ascii) re' :=\n forall s, a :: s =~ re <-> s =~ re'.\n\n(** A function [d] derives strings if, given character [a] and regex\n [re], it evaluates to the derivative of [re] on [a]. I.e., [d]\n satisfies the following property: *)\nDefinition derives d := forall a re, is_der re a (d a re).\n\n(** **** Exercise: 3 stars, standard, optional (derive) \n\n Define [derive] so that it derives strings. One natural\n implementation uses [match_eps] in some cases to determine if key\n regex's match the empty string. *)\nFixpoint derive (a : ascii) (re : reg_exp ascii) : reg_exp ascii\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(** The [derive] function should pass the following tests. Each test\n establishes an equality between an expression that will be\n evaluated by our regex matcher and the final value that must be\n returned by the regex matcher. Each test is annotated with the\n match fact that it reflects. *)\nExample c := ascii_of_nat 99.\nExample d := ascii_of_nat 100.\n\n(** \"c\" =~ EmptySet: *)\nExample test_der0 : match_eps (derive c (EmptySet)) = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** \"c\" =~ Char c: *)\nExample test_der1 : match_eps (derive c (Char c)) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** \"c\" =~ Char d: *)\nExample test_der2 : match_eps (derive c (Char d)) = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** \"c\" =~ App (Char c) EmptyStr: *)\nExample test_der3 : match_eps (derive c (App (Char c) EmptyStr)) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** \"c\" =~ App EmptyStr (Char c): *)\nExample test_der4 : match_eps (derive c (App EmptyStr (Char c))) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** \"c\" =~ Star c: *)\nExample test_der5 : match_eps (derive c (Star (Char c))) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** \"cd\" =~ App (Char c) (Char d): *)\nExample test_der6 :\n match_eps (derive d (derive c (App (Char c) (Char d)))) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** \"cd\" =~ App (Char d) (Char c): *)\nExample test_der7 :\n match_eps (derive d (derive c (App (Char d) (Char c)))) = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 4 stars, standard, optional (derive_corr) \n\n Prove that [derive] in fact always derives strings.\n\n Hint: one proof performs induction on [re], although you'll need\n to carefully choose the property that you prove by induction by\n generalizing the appropriate terms.\n\n Hint: if your definition of [derive] applies [match_eps] to a\n particular regex [re], then a natural proof will apply\n [match_eps_refl] to [re] and destruct the result to generate cases\n with assumptions that the [re] does or does not match the empty\n string.\n\n Hint: You can save quite a bit of work by using lemmas proved\n above. In particular, to prove many cases of the induction, you\n can rewrite a [Prop] over a complicated regex (e.g., [s =~ Union\n re0 re1]) to a Boolean combination of [Prop]'s over simple\n regex's (e.g., [s =~ re0 \\/ s =~ re1]) using lemmas given above\n that are logical equivalences. You can then reason about these\n [Prop]'s naturally using [intro] and [destruct]. *)\nLemma derive_corr : derives derive.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** We'll define the regex matcher using [derive]. However, the only\n property of [derive] that you'll need to use in all proofs of\n properties of the matcher is [derive_corr]. *)\n\n(** A function [m] matches regexes if, given string [s] and regex [re],\n it evaluates to a value that reflects whether [s] is matched by\n [re]. I.e., [m] holds the following property: *)\nDefinition matches_regex m : Prop :=\n forall (s : string) re, reflect (s =~ re) (m s re).\n\n(** **** Exercise: 2 stars, standard, optional (regex_match) \n\n Complete the definition of [regex_match] so that it matches\n regexes. *)\nFixpoint regex_match (s : string) (re : reg_exp ascii) : bool\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (regex_refl) \n\n Finally, prove that [regex_match] in fact matches regexes.\n\n Hint: if your definition of [regex_match] applies [match_eps] to\n regex [re], then a natural proof applies [match_eps_refl] to [re]\n and destructs the result to generate cases in which you may assume\n that [re] does or does not match the empty string.\n\n Hint: if your definition of [regex_match] applies [derive] to\n character [x] and regex [re], then a natural proof applies\n [derive_corr] to [x] and [re] to prove that [x :: s =~ re] given\n [s =~ derive x re], and vice versa. *)\nTheorem regex_refl : matches_regex regex_match.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Sajadrahimi", "repo": "Software-Foundations-Coq", "sha": "507f417aae16898b7f6de68823bec13a96ab65e0", "save_path": "github-repos/coq/Sajadrahimi-Software-Foundations-Coq", "path": "github-repos/coq/Sajadrahimi-Software-Foundations-Coq/Software-Foundations-Coq-507f417aae16898b7f6de68823bec13a96ab65e0/ch1/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.9207896748041439, "lm_q1q2_score": 0.8621215659667287}} {"text": "\nRequire Import Coq.Arith.Plus.\n\n(* The Monoid spec, with a theorem *)\nModule Monoid.\n\nClass Monoid :=\n {\n T : Type;\n zero : T;\n add : T -> T -> T;\n add_assoc : forall t1 t2 t3, add t1 (add t2 t3) = add (add t1 t2) t3;\n add_zero_left : forall t, add zero t = t;\n add_zero_right : forall t, add t zero = t\n }.\n\nLemma add_add_zero `{Monoid} :\n forall t, add t (add t zero) = add t t.\n intro t; rewrite add_zero_right; reflexivity.\nQed.\n\nEnd Monoid.\n\n(* The name of the spec is exported without the period *)\nNotation Monoid := Monoid.Monoid.\n\n\n(*\nCheck Monoid.T.\nPrint Monoid.T.\n*)\n\n(* The Group spec *)\nModule Group.\n\nClass Group :=\n {\n T : Type;\n zero : T;\n add : T -> T -> T;\n inv : T -> T;\n add_assoc : forall t1 t2 t3, add t1 (add t2 t3) = add (add t1 t2) t3;\n add_zero_left : forall t, add zero t = t;\n add_zero_right : forall t, add t zero = t;\n add_inv_left : forall t, add (inv t) t = zero;\n add_inv_right : forall t, add t (inv t) = zero\n }.\n\nEnd Group.\n\nNotation Group := Group.Group.\n\n\n(*\nModule Monoid_Group_morph.\nImport Monoid.\n*)\n\n(* The morphism from Monoid ==> Group *)\n\n(*\nInstance Monoid_Group_morph (G: Group) : Monoid :=\n {|\n T := Group.T;\n zero := Group.zero;\n add := Group.add;\n add_assoc := Group.add_assoc;\n add_zero_left := Group.add_zero_left;\n add_zero_right := Group.add_zero_right\n |}.\n*)\nInstance Monoid_Group_morph (G: Group) : Monoid :=\n {|\n T := Group.T;\n zero := Group.zero;\n add := Group.add\n |}.\napply Group.add_assoc.\napply Group.add_zero_left.\napply Group.add_zero_right.\nDefined.\n(* README: This needs to be \"Defined\" not \"Qed\" so Monoid_Group_morph\n is transparent when we try to use Monoid theorems below *)\n\nPrint Monoid_Group_morph.\n(* Coercion Monoid_Group_morph : Group >-> Monoid. *)\n\n(*\nEnd Monoid_Group_morph.\n*)\n\n\n(* Moving the add_add_zero theorem along a morphism *)\nDefinition add_add_zero_group `{Group} :\n forall t, Group.add t (Group.add t Group.zero) = Group.add t t :=\n Monoid.add_add_zero.\n\n(* Another test to move add_add_zero theorem along a morphism *)\n(* README: need to apply add_add_zero to an argument when it is used\n in a tactic script, since otherwise the instance resolution does\n not happen *)\nLemma add_add_zero_zero `{Group} :\n forall t, Group.add t (Group.add t (Group.add Group.zero Group.zero)) = Group.add t t.\n intro t. rewrite Group.add_zero_left.\n apply (Monoid.add_add_zero t).\nQed.\n\n\n(* README: this is an example of building an instance *)\nDefinition nat_Monoid : Monoid :=\n {| T := nat; zero := 0; add := plus;\n add_assoc := plus_assoc; add_zero_left := plus_0_l;\n add_zero_right := plus_0_r |}.\n\n\n", "meta": {"author": "KestrelInstitute", "repo": "SpecwareC", "sha": "b1234db75aeaaa91e66b15dae79b3ec195e12e41", "save_path": "github-repos/coq/KestrelInstitute-SpecwareC", "path": "github-repos/coq/KestrelInstitute-SpecwareC/SpecwareC-b1234db75aeaaa91e66b15dae79b3ec195e12e41/theories/archival/Test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810444238087, "lm_q2_score": 0.9099070017626536, "lm_q1q2_score": 0.8620286456584391}} {"text": "Require Import Arith.\nImplicit Type m n : nat.\n\nInductive even : nat -> Prop :=\n| ev_0 : even 0\n| ev_SS : forall n, even n -> even (S (S n)).\n\nInductive odd : nat -> Prop :=\n| odd_1 : odd 1\n| odd_SS : forall n, odd n -> odd (S (S n)).\n\nHint Constructors odd even.\n\nLemma even_add_one : forall n, even n -> odd (S n).\nProof.\n intros.\n induction H.\n - auto.\n - simpl. auto.\nQed.\n\nHint Resolve even_add_one.\n\nLemma odd_add_one : forall n, odd n -> even (S n).\nProof. intros; induction H; auto. Qed.\n\nHint Resolve odd_add_one.\n\nLemma parity_dec : forall n, {even n} + {odd n}.\nProof.\n induction n.\n - auto.\n - destruct IHn.\n + auto.\n + simpl. auto.\nQed.\n\nHint Resolve parity_dec.\n(* Addition *)\n\nTheorem odd_add_odd : forall n m, odd n -> odd m -> even (n + m).\nProof. intros; induction H; simpl; auto. Qed.\n\nHint Resolve odd_add_odd.\n\nTheorem odd_add_even : forall n m, odd n -> even m -> odd (n + m).\nProof. intros; induction H; simpl; auto. Qed.\n\nHint Resolve odd_add_even.\n\nTheorem even_add_odd : forall n m, even n -> odd m -> odd (n + m).\nProof. intros; induction H; simpl; auto. Qed.\n\nHint Resolve even_add_odd.\n\nTheorem even_add_even : forall n m, even n -> even m -> even (n + m).\nProof. intros; induction H; simpl; auto. Qed.\n\nHint Resolve even_add_even.\n\n(* Multiplication *)\n\nTheorem even_mul_even : forall n m, even n -> even m -> even (n * m).\nProof. intros; induction H; simpl; auto. Qed.\n\nHint Resolve even_mul_even.\n\nTheorem even_mul_odd : forall n m, even n -> odd m -> even (n * m).\nProof. intros; induction H; simpl; auto. Qed.\n\nHint Resolve even_mul_odd.\n\nTheorem odd_mul_even : forall n m, odd n -> even m -> even (n * m).\nProof. intros; induction H; simpl; auto. Qed.\n\nHint Resolve odd_mul_even.\n\nTheorem odd_mul_odd : forall n m, odd n -> odd m -> odd (n * m).\nProof. intros; induction H; simpl; auto. Qed.\n\nHint Resolve odd_mul_odd.\n\nTheorem even_mul : forall n m, even n -> even (n * m).\nProof.\n intros.\n destruct (parity_dec m).\n -(*m = even*) auto.\n -(*m=odd*) auto.\nQed.\n", "meta": {"author": "Whu-Lambda", "repo": "Lambda-Cube", "sha": "6845929d9f816a350e65b33078657b14ae940693", "save_path": "github-repos/coq/Whu-Lambda-Lambda-Cube", "path": "github-repos/coq/Whu-Lambda-Lambda-Cube/Lambda-Cube-6845929d9f816a350e65b33078657b14ae940693/第一次分享会/Coq 小课堂/Odd_and_Even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377237352756, "lm_q2_score": 0.899121373891026, "lm_q1q2_score": 0.8618417550912377}} {"text": "(** * Lists: Working with Structured Data *)\n\nRequire Import Le Lt Gt Decidable PeanoNat.\nFrom LF Require Export Induction.\nModule NatList.\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one (as with [nybble], and here): *)\n\nInductive natprod : Type :=\n| pair (n1 n2 : nat).\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n(** Here are simple functions for extracting the first and\n second components of a pair. *)\n\nDefinition fst (p : natprod) : nat :=\n match p with\n | pair x y => x\n end.\n\nDefinition snd (p : natprod) : nat :=\n match p with\n | pair x y => y\n end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs will be used heavily, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new pair notation can be used both in expressions and in\n pattern matches. *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n match p with\n | (x,y) => x\n end.\n\nDefinition snd' (p : natprod) : nat :=\n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n match p with\n | (x,y) => (y,x)\n end.\n\n(** Note that pattern-matching on a pair (with parentheses: [(x, y)])\n is not to be confused with the \"multiple pattern\" syntax\n (with no parentheses: [x, y]) that we have seen previously.\n\n The above examples illustrate pattern matching on a pair with\n elements [x] and [y], whereas [minus] below (taken from\n [Basics]) performs pattern matching on the values [n]\n and [m].\n\n Fixpoint minus (n m : nat) : nat :=\n match n, m with\n | O , _ => O\n | S _ , O => n\n | S n', S m' => minus n' m'\n end.\n\n The distinction is minor, but it is worth knowing that they\n are not the same. For instance, the following definitions are\n ill-formed:\n\n (* Can't match on a pair with multiple patterns: *)\n Definition bad_fst (p : natprod) : nat :=\n match p with\n | x, y => x\n end.\n\n (* Can't match on multiple values with pair patterns: *)\n Definition bad_minus (n m : nat) : nat :=\n match n, m with\n | (O , _ ) => O\n | (S _ , O ) => n\n | (S n', S m') => bad_minus n' m'\n end.\n*)\n\n(** Let's try to prove a few simple facts about pairs.\n\n If we state things in a slightly peculiar way, we can complete\n proofs with just reflexivity (and its built-in simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** Notice that, unlike its behavior with [nat]s, where it\n generates two subgoals, [destruct] generates just one subgoal\n here. That's because [natprod]s can only be constructed in one\n way. *)\n\n(** **** Exercise: 1 star, standard (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n destruct p as [x y].\n reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n destruct p as [x y].\n reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n type of _lists_ of numbers like this: \"A list is either the empty\n list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n | nil\n | cons (n : nat) (l : natlist).\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n declarations, but here is roughly what's going on in case you are\n interested. The [right associativity] annotation tells Coq how to\n parenthesize expressions involving multiple uses of [::] so that,\n for example, the next three declarations mean exactly the same\n thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\n\n Notation \"x + y\" := (plus x y)\n (at level 50, left associativity).\n\n the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than\n [1 + (2 :: [3])].\n\n (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n you read them in a [.v] file. The inner brackets, around 3, indicate\n a list, but the outer brackets, which are invisible in the HTML\n rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n part should be displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Since [app] will be used extensively in what follows, it is\n again convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head (With Default) and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first element (the\n \"tail\"). Since the empty list has no first element, we must pass\n a default value to be returned in that case. *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, standard, recommended (list_funs) \n\n Complete the definitions of [nonzeros], [oddmembers], and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | nil => nil\n | cons 0 l => (nonzeros l)\n | cons e l => cons e (nonzeros l)\n end.\n\nExample test_nonzeros:\n nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. simpl. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | nil => nil\n | cons e l =>\n match (evenb e) with\n | true => oddmembers l\n | false => cons e (oddmembers l)\n end\n end.\n\nExample test_oddmembers:\n oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. simpl. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n match l with\n | nil => O\n | cons e l =>\n match (evenb e) with\n | true => countoddmembers l\n | false => plus 1 (countoddmembers l)\n end\n end.\n\nExample test_countoddmembers1:\n countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers2:\n countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers3:\n countoddmembers nil = 0.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) \n\n Complete the definition of [alternate], which interleaves two\n lists into one, alternating between elements taken from the first\n list and elements from the second. See the tests below for more\n specific examples.\n\n (Note: one natural and elegant way of writing [alternate] will\n fail to satisfy Coq's requirement that all [Fixpoint] definitions\n be \"obviously terminating.\" If you find yourself in this rut,\n look for a slightly more verbose solution that considers elements\n of both lists at the same time. One possible solution involves\n defining a new kind of pairs, but this is not the only way.) *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | cons e1 l1' =>\n match l2 with\n | nil => cons e1 l1'\n | cons e2 l2' => e1 :: e2 :: alternate l1' l2'\n end\n end.\n\nExample test_alternate1:\n alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. reflexivity. Qed.\n\nExample test_alternate2:\n alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\n\nExample test_alternate3:\n alternate [1;2;3] [4] = [1;4;2;3].\nProof. reflexivity. Qed.\n\nExample test_alternate4:\n alternate [] [20;30] = [20;30].\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n can appear multiple times rather than just once. One possible\n representation for a bag of numbers is as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, standard, recommended (bag_functions) \n\n Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat :=\n match s with\n | nil => O\n | cons e l =>\n match (v =? e) with\n | true => 1 + count v l\n | false => count v l\n end\n end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n the elements of [a] and of [b]. (Mathematicians usually define\n [union] on multisets a little bit differently -- using max instead\n of sum -- which is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := cons v s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool := (notb ((count v s) =? 0)).\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (bag_more_functions) \n\n Here are some more [bag] functions for you to practice with. *)\n\n(** When [remove_one] is applied to a bag without the number to\n remove, it should return the same bag unchanged. (This exercise\n is optional, but students following the advanced track will need\n to fill in the definition of [remove_one] for a later\n exercise.) *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | cons e l =>\n match (v =? e) with\n | false => cons e (remove_one v l)\n | true => l\n end\n end.\n\nExample test_remove_one1:\n count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one2:\n count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one3:\n count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\nExample test_remove_one4:\n count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | cons e l =>\n match (v =? e) with\n | false => cons e (remove_all v l)\n | true => remove_all v l\n end\n end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. simpl. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n match s1 with\n | nil => true\n | cons e l =>\n match (member e s2) with\n | true => subset l (remove_one e s2)\n | false => false\n end\n end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, recommended (bag_theorem) \n\n Write down an interesting theorem [bag_theorem] about bags\n involving the functions [count] and [add], and prove it. Note\n that, since this problem is somewhat open-ended, it's possible\n that you may come up with a theorem which is true, but whose proof\n requires techniques you haven't learned yet. Feel free to ask for\n help if you get stuck! *)\n\n(*\nTheorem bag_theorem : ...\nProof.\n ...\nQed.\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_bag_theorem : option (nat*string) := None.\n(* Note to instructors: For silly technical reasons, in this\n file (only) you will need to write [Some (Datatypes.pair 3 \"\"%string)]\n rather than [Some (3,\"\"%string)] to enter your grade and comments. \n\n [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As for numbers, simple facts about list-processing functions\n can sometimes be proved entirely by simplification. For example,\n the simplification performed by [reflexivity] is enough for this\n theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ...because the [[]] is substituted into the\n \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n the match) in the definition of [app], allowing the match itself\n to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons n l' *)\n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Micro-Sermon *)\n\n(** Simply _reading_ proof scripts will not get you very far! It is\n important to step through the details of each one using Coq and\n think about what each step achieves. Otherwise it is more or less\n guaranteed that the exercises will make no sense when you get to\n them. 'Nuff said. *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n little less familiar than standard natural number induction, but\n the idea is equally simple. Each [Inductive] declaration defines\n a set of data values that can be built up using the declared\n constructors: a boolean can be either [true] or [false]; a number\n can be either [O] or [S] applied to another number; a list can be\n either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two arguments together establish\n the truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons n l1' *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n [as...] clause provided to the [induction] tactic gives a name to\n the induction hypothesis corresponding to the smaller list [l1']\n in the [cons] case. Once again, this Coq proof is not especially\n illuminating as a static document -- it is easy to see what's\n going on if you are reading the proof in an interactive Coq\n session and you can see the current goal and context at each\n point, but this state is not visible in the written-down parts of\n the Coq proof. So a natural-language proof -- one written for\n human readers -- will need to include more explicit signposts; in\n particular, it will help the reader stay oriented if we remind\n them exactly what the induction hypothesis is in the second\n case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n (the induction hypothesis). We must show\n\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n By the definition of [++], this follows from\n\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n which is immediate from the induction hypothesis. [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n lists, suppose we use [app] to define a list-reversing function\n [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => rev t ++ [h]\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Properties of [rev] *)\n\n(** Now, for something a bit more challenging than the proofs\n we've seen so far, let's prove that reversing a list does not\n change its length. Our first attempt gets stuck in the successor\n case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = [] *)\n reflexivity.\n - (* l = n :: l' *)\n (* This is the tricky case. Let's begin as usual\n by simplifying. *)\n simpl.\n (* Now we seem to be stuck: the goal is an equality\n involving [++], but we don't have any useful equations\n in either the immediate context or in the global\n environment! We can make a little progress by using\n the IH to rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n would have enabled us to make progress and state it as a separate\n lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Note that, to make the lemma as general as possible, we\n quantify over _all_ [natlist]s, not just those that result from an\n application of [rev]. This should seem natural, because the truth\n of the goal clearly doesn't depend on the list having been\n reversed. Moreover, it is easier to prove the more general\n property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons *)\n simpl. rewrite -> app_length, plus_comm.\n simpl. rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n _Theorem_: For all lists [l1] and [l2],\n [length (l1 ++ l2) = length l1 + length l2].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n length ([] ++ l2) = length [] + length l2,\n\n which follows directly from the definitions of\n [length] and [++].\n\n - Next, suppose [l1 = n::l1'], with\n\n length (l1' ++ l2) = length l1' + length l2.\n\n We must show\n\n length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n This follows directly from the definitions of [length] and [++]\n together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n\n length (rev []) = length [],\n\n which follows directly from the definitions of [length]\n and [rev].\n\n - Next, suppose [l = n::l'], with\n\n length (rev l') = length l'.\n\n We must show\n\n length (rev (n :: l')) = length (n :: l').\n\n By the definition of [rev], this follows from\n\n length ((rev l') ++ [n]) = S (length l')\n\n which, by the previous lemma, is the same as\n\n length (rev l') + length [n] = S (length l').\n\n This follows directly from the induction hypothesis and the\n definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n After the first few, we might find it easier to follow proofs that\n give fewer details (which we can easily work out in our own minds or\n on scratch paper if necessary) and just highlight the non-obvious\n steps. In this more compressed style, the above proof might look\n like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n for any [l] (this follows by a straightforward induction on [l]).\n The main property again follows by induction on [l], using the\n observation together with the induction hypothesis in the case\n where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for our\n present purposes. *)\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, e.g., using [rewrite]. But in order to refer to a\n theorem, we need to know its name! Indeed, it is often hard even\n to remember what theorems have been proven, much less what they\n are called.\n\n Coq's [Search] command is quite helpful with this. Typing [Search\n foo] into your .v file and evaluating this line will cause Coq to\n display a list of all theorems involving [foo]. For example, try\n uncommenting the following line to see a list of theorems that we\n have proved about [rev]: *)\n\n(* Search rev. *)\n\n(** Keep [Search] in mind as you do the following exercises and\n throughout the rest of the book; it can save you a lot of time!\n\n If you are using ProofGeneral, you can run [Search] with\n [C-c C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars, standard (list_exercises) \n\n More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n l ++ [] = l.\nProof.\n induction l as [|e l' IHl'].\n - reflexivity.\n - simpl.\n rewrite -> IHl'.\n reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n induction l1 as [|e1 l1' IHl1'].\n - simpl.\n intros l2.\n rewrite -> app_nil_r.\n reflexivity.\n - simpl.\n intros l2.\n rewrite -> IHl1', app_assoc.\n reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n induction l as [|e l' IHl'].\n - reflexivity.\n - simpl.\n rewrite -> rev_app_distr, IHl'.\n reflexivity.\nQed.\n\n(** There is a short solution to the next one. If you find yourself\n getting tangled up, step back and try to look for a simpler\n way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros l1 l2 l3 l4.\n rewrite -> app_assoc, app_assoc.\n reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nCheck nonzeros.\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n induction l1 as [|e1 l1' IHl1'].\n - reflexivity.\n - simpl.\n intros l2.\n destruct e1.\n + rewrite -> IHl1'.\n reflexivity.\n + rewrite -> IHl1'.\n reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (eqblist) \n\n Fill in the definition of [eqblist], which compares\n lists of numbers for equality. Prove that [eqblist l l]\n yields [true] for every list [l]. *)\n\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n match l1 with\n | nil =>\n match l2 with\n | nil => true\n | cons e l => false\n end\n | cons e l =>\n match l2 with\n | nil => false\n | cons e' l' =>\n match (e =? e') with\n | true => eqblist l l'\n | false => false\n end\n end\n end.\n\n\nExample test_eqblist1 :\n (eqblist nil nil = true).\nProof. reflexivity. Qed.\n\nExample test_eqblist2 :\n eqblist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\nExample test_eqblist3 :\n eqblist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem nat_eq_self:\n forall n:nat, (n =? n) = true.\nProof.\n induction n as [|n' IHn'].\n - reflexivity.\n - simpl.\n rewrite -> IHn'.\n reflexivity.\nQed.\n\nTheorem eqblist_refl : forall l:natlist,\n true = eqblist l l.\nProof.\n induction l as [|e l' IHl'].\n - reflexivity.\n - simpl.\n rewrite <- IHl'.\n assert (H: forall n:nat, (n =? n) = true).\n { induction n as [|n' IHn'].\n - reflexivity.\n - simpl. rewrite -> IHn'. reflexivity. }\n rewrite -> H.\n reflexivity.\nQed.\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** Here are a couple of little theorems to prove about your\n definitions about bags above. *)\n\n(** **** Exercise: 1 star, standard (count_member_nonzero) *)\nTheorem count_member_nonzero : forall (s : bag),\n 1 <=? (count 1 (1 :: s)) = true.\nProof.\n simpl.\n reflexivity.\nQed.\n(** [] *)\n\n(** The following lemma about [leb] might help you in the next exercise. *)\n\nTheorem leb_n_Sn : forall n,\n n <=? (S n) = true.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* 0 *)\n simpl. reflexivity.\n - (* S n' *)\n simpl. rewrite IHn'. reflexivity. Qed.\n\n(** Before doing the next exercise, make sure you've filled in the\n definition of [remove_one] above. *)\n(** **** Exercise: 3 stars, advanced (remove_does_not_increase_count) *)\nTheorem remove_does_not_increase_count: forall (s : bag),\n (count 0 (remove_one 0 s)) <=? (count 0 s) = true.\nProof.\n induction s as [|e l' IHl'].\n - reflexivity.\n - simpl.\n destruct e.\n + simpl.\n rewrite -> leb_n_Sn.\n reflexivity.\n + simpl.\n rewrite -> IHl'.\n reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (bag_count_sum) \n\n Write down an interesting theorem [bag_count_sum] about bags\n involving the functions [count] and [sum], and prove it using\n Coq. (You may find that the difficulty of the proof depends on\n how you defined [count]!) *)\nTheorem count_and_sum:\n forall (n:nat) (l1 l2:bag),\n count n (sum l1 l2) = (count n l1) + (count n l2).\nProof.\n induction l1 as [|e1 l1' IHl1'].\n - simpl.\n reflexivity.\n - simpl.\n intros l2.\n rewrite -> IHl1'.\n destruct (n =? e1).\n + reflexivity.\n + reflexivity.\nQed.\n\n(** **** Exercise: 4 stars, advanced (rev_injective) \n\n Prove that the [rev] function is injective -- that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\n (There is a hard way and an easy way to do this.) *)\n\nTheorem rev_injective':\n forall l1 l2:natlist, (rev l1 = rev l2) -> l1 = l2.\nProof.\n assert (H1: forall l1 l2:natlist, l1 = l2 -> (rev l1 = rev l2)).\n { intros l1 l2 H1'. rewrite -> H1'. reflexivity. }\n assert (H2: forall l1 l2:natlist, rev (rev l1) = rev (rev l2) -> l1 = l2).\n { intros l1 l2 H2'.\n rewrite -> rev_involutive in H2'.\n rewrite -> rev_involutive in H2'.\n rewrite -> H2'.\n reflexivity. }\n intros l1 l2 rev_eq_H.\n apply H1 in rev_eq_H as rev_rev_eq_H.\n apply H2 in rev_rev_eq_H as eq_H.\n apply eq_H.\nQed.\n\nTheorem rev_injective:\n forall l1 l2:natlist, (rev l1 = rev l2) -> l1 = l2.\nProof.\n intros l1 l2 H.\n replace l1 with (rev (rev l1)).\n replace l2 with (rev (rev l2)).\n rewrite H.\n reflexivity.\n - rewrite -> rev_involutive.\n reflexivity.\n - rewrite -> rev_involutive.\n reflexivity.\nQed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_rev_injective : option (nat*string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n element of some list. If we give it type [nat -> natlist -> nat],\n then we'll have to choose some number to return when the list is\n too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match n =? O with\n | true => a\n | false => nth_bad l' (pred n)\n end\n end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n can't tell whether that value actually appears on the input\n without further processing. A better alternative is to change the\n return type of [nth_bad] to include an error value as a possible\n outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n | Some (n : nat)\n | None.\n\n(** We can then change the above definition of [nth_bad] to\n return [None] when the list is too short and [Some a] when the\n list has enough members and [a] appears at position [n]. We call\n this new function [nth_error] to indicate that it may result in an\n error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => match n =? O with\n | true => Some a\n | false => nth_error l' (pred n)\n end\n end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n examples are elided. Click on a box if you want to see one.)\n\n This example is also an opportunity to introduce one more small\n feature of Coq's programming language: conditional\n expressions... *)\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => if n =? O then Some a\n else nth_error' l' (pred n)\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually supports conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars, standard (hd_error) \n\n Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_error (l : natlist) : natoption :=\n match l with\n | nil => None\n | cons e l' => Some e\n end.\n\nExample test_hd_error1 : hd_error [] = None.\nProof. trivial. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. trivial. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. trivial. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (option_elim_hd) \n\n This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_error l).\nProof.\n induction l as [|e l' IHl'].\n - trivial.\n - trivial.\nQed.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n Coq, here is a simple _partial map_ data type, analogous to the\n map or dictionary data structures found in most programming\n languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n | Id (n : nat).\n\n(** Internally, an [id] is just a number. Introducing a separate type\n by wrapping each nat with the tag [Id] makes definitions more\n readable and gives us the flexibility to change representations\n later if we wish. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition eqb_id (x1 x2 : id) :=\n match x1, x2 with\n | Id n1, Id n2 => n1 =? n2\n end.\n\n(** **** Exercise: 1 star, standard (eqb_id_refl) *)\nTheorem eqb_id_refl : forall x, true = eqb_id x x.\nProof.\n intros x.\n destruct x as [n].\n - simpl.\n rewrite -> (eqb_refl n).\n reflexivity.\nQed.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n \nInductive partial_map : Type :=\n | empty\n | record (i : id) (v : nat) (m : partial_map).\n\n(** This declaration can be read: \"There are two ways to construct a\n [partial_map]: either using the constructor [empty] to represent an\n empty partial map, or by applying the constructor [record] to\n a key, a value, and an existing [partial_map] to construct a\n [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n partial map by shadowing it with a new one (or simply adds a new\n entry if the given key is not already present). *)\n\nDefinition update (d : partial_map)\n (x : id) (value : nat)\n : partial_map :=\n record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n key. It returns [None] if the key was not found and [Some val] if\n the key was associated with [val]. If the same key is mapped to\n multiple values, [find] will return the first one it\n encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n match d with\n | empty => None\n | record y v d' => if eqb_id x y\n then Some v\n else find x d'\n end.\n\n(** **** Exercise: 1 star, standard (update_eq) *)\nTheorem update_eq :\n forall (d : partial_map) (x : id) (v: nat),\n find x (update d x v) = Some v.\nProof.\n intros d x v.\n simpl.\n rewrite <- (eqb_id_refl x).\n reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (update_neq) *)\nTheorem update_neq :\n forall (d : partial_map) (x y : id) (o: nat),\n eqb_id x y = false -> find x (update d y o) = find x d.\nProof.\n intros.\n simpl.\n rewrite -> H.\n reflexivity.\nQed.\n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 stars, standard (baz_num_elts) \n\n Consider the following inductive definition: *)\n\nInductive baz : Type :=\n | Baz1 (x : baz)\n | Baz2 (y : baz) (b : bool).\n\n(** How _many_ elements does the type [baz] have? (Explain in words,\n in a comment.) *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_baz_num_elts : option (nat*string) := None.\n(** [] *)\n\n(* Wed Jan 9 12:02:44 EST 2019 *)\n\n", "meta": {"author": "wierton", "repo": "SoftwareFoundationSolutions", "sha": "e8d2c92ff78997af2cb67c5d06cd13ed6afd9e37", "save_path": "github-repos/coq/wierton-SoftwareFoundationSolutions", "path": "github-repos/coq/wierton-SoftwareFoundationSolutions/SoftwareFoundationSolutions-e8d2c92ff78997af2cb67c5d06cd13ed6afd9e37/LF/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.9314625003089676, "lm_q1q2_score": 0.8618170130345187}} {"text": "(* ========================================================================== *]\n PROVING THINGS WE KNOW\n[* ========================================================================== *)\nRequire Import Nat List Lia. \n\n(* -------------------------------------------------------------------------- *]\n Let's prove things we consider true in our everyday programming life.\n\n We start by defining some common functions for lists.\n[* -------------------------------------------------------------------------- *)\n\n(* Calculate length of list. *)\nFixpoint length {A} (lst : list A) :=\n match lst with\n | nil => 0\n | x :: xs => 1 + length xs\n end.\n\n(* Concatenate two lists. *)\nFixpoint concat {A} (lst1 lst2 : list A) :=\n match lst1 with\n | nil => lst2\n | x :: xs => x :: (concat xs lst2)\n end.\n\n(* Reverse a list. *)\nFixpoint reverse {A} (lst : list A) :=\n match lst with\n | nil => nil\n | x :: xs => concat (reverse xs) (x :: nil)\n end.\n\n(* Apply function on all elements of list. *)\nFixpoint map {A B} (f : A -> B) (lst : list A) :=\n match lst with\n | nil => nil\n | x :: xs => f x :: map f xs\n end.\n\n(* Compose two functions into a single one. *)\nDefinition compose {A B C} (f : B -> C) (g : A -> B) := \n fun x => f (g x).\n\n\n(* -------------------------------------------------------------------------- *]\n Most often we need properties that describe how different functions interact.\n[* -------------------------------------------------------------------------- *)\n\nLemma length_concat {A} (lst1 lst2 : list A):\n length (concat lst1 lst2) = length lst1 + length lst2.\nProof.\n induction lst1.\n - simpl. auto.\n - simpl. rewrite IHlst1. auto.\nQed.\n\n\nLemma length_map {A B} (lst : list A) (f : A -> B):\n length (map f lst) = length lst.\nProof.\n induction lst.\n - simpl. auto.\n - simpl. rewrite IHlst. auto.\nQed.\n\n\nLemma map_compose {A B C} (lst : list A) (f : B -> C) (g : A -> B):\n map f (map g lst) = map (compose f g) lst.\nProof.\n induction lst.\n - simpl. auto.\n - simpl. rewrite IHlst. unfold compose. auto.\nQed.\n\n\n(* -------------------------------------------------------------------------- *]\n Sometimes we need to prove some auxiliary lemmas.\n[* -------------------------------------------------------------------------- *)\n\n(* These two seem obvious but must be shown. *)\nLemma concat_nil {A} (lst1 : list A):\n concat lst1 nil = lst1.\nProof.\n induction lst1.\n - simpl. auto.\n - simpl. rewrite IHlst1. auto.\nQed.\n\nLemma concat_assoc {A} (lst1 lst2 lst3 : list A):\n concat (concat lst1 lst2) lst3 = concat lst1 (concat lst2 lst3).\nProof.\n induction lst1.\n - simpl. auto.\n - simpl. rewrite IHlst1. auto.\nQed.\n\n(* This is what we actually want. *)\nLemma reverse_concat {A} (lst1 lst2 : list A):\n reverse (concat lst1 lst2) = concat (reverse lst2) (reverse lst1).\nProof.\n induction lst1. simpl.\n - rewrite concat_nil. auto.\n - simpl. rewrite IHlst1. rewrite concat_assoc. auto.\nQed.\n\n\n(* -------------------------------------------------------------------------- *]\n Induction needs to be performed at a general enough level in order to complete the following proof. If we try to first introduce all hypotheses, we get\n an induction hypothesis that is too weak.\n[* -------------------------------------------------------------------------- *)\n\nFixpoint get_el {A} n (lst : list A) :=\n match lst, n with\n | nil, _ => None\n | x :: xs, 0 => Some x\n | x :: xs, S m => get_el m xs\n end.\n\nLemma get_fails {A} n (lst : list A) :\n length lst < n -> get_el n lst = None.\nProof.\n revert n.\n induction lst.\n - intros.\n destruct n.\n + simpl. auto.\n + simpl. auto.\n - intros.\n destruct n.\n + simpl. simpl in H. lia.\n + simpl. apply IHlst. simpl in H. lia.\nQed.\n\n(* -------------------------------------------------------------------------- *]\n By defining an inductive data type, Coq already know precisely what the\n appropriate induction principle is.\n[* -------------------------------------------------------------------------- *)\n\nInductive tree {A} :=\n| Empty : tree\n| Node : tree -> A -> tree -> tree\n.\n\nFixpoint mirror {A} (t : @tree A) :=\n match t with\n | Empty => Empty\n | Node l_t x r_t => Node (mirror r_t) x (mirror l_t)\n end.\n\nFixpoint height {A} (t : @tree A) :=\n match t with\n | Empty => 0\n | Node l_t x r_t => 1 + max (height l_t) (height r_t)\n end.\n\n\nLemma height_mirror {A} (t : @tree A) :\n height (mirror t) = height t.\nProof.\n induction t.\n - simpl. auto.\n - simpl. rewrite IHt1, IHt2. lia.\nQed.\n\n\nLemma mirror_mirror {A} (t : @tree A) :\n mirror (mirror t) = t.\nProof.\n induction t.\n - simpl. auto.\n - simpl. rewrite IHt1, IHt2. auto.\nQed.\n", "meta": {"author": "zigaLuksic", "repo": "coq-workshop", "sha": "55252d12fb7391dcf8cd6654c8f34e27017a353c", "save_path": "github-repos/coq/zigaLuksic-coq-workshop", "path": "github-repos/coq/zigaLuksic-coq-workshop/coq-workshop-55252d12fb7391dcf8cd6654c8f34e27017a353c/solutions/proving_things_we_know.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.920789684042214, "lm_q1q2_score": 0.8612574205859511}} {"text": "(* Chap 7 IndProp *)\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Logic.\nRequire Coq.omega.Omega.\n\n(* Chap 7.1 Inductively Defined Propositions *)\nInductive even: nat -> Prop :=\n | ev_0: even 0\n | ev_SS (n: nat) (H: even n) : even (S (S n)).\n\nInductive myeven: nat -> Prop :=\n | myev_0: myeven 0\n | myev_SS: forall n, myeven n -> myeven (S (S n)).\n\nTheorem ev_4: even 4.\nProof.\n apply ev_SS.\n apply ev_SS.\n apply ev_0.\nQed.\n\nTheorem ev_4': even 4.\nProof.\n apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\n\nTheorem ev_plus4: forall n, even n -> even (4 + n).\nProof.\n intros n.\n simpl. intros H.\n apply ev_SS, ev_SS, H.\nQed.\n\n(* Exercise ev_double *)\nTheorem ev_double: forall n,\n even (double n).\nProof.\n intros.\n induction n.\n - simpl. apply ev_0.\n - simpl. apply ev_SS, IHn.\nQed.\n\n(* Chap 7.2 Using Evidence in Proofs *)\n(* Chap 7.2.1 Inversion on Evidence *)\nTheorem ev_inversion:\n forall n: nat, even n -> (n = 0) \\/ (exists n', n = S (S n') /\\ even n').\nProof.\n intros.\n destruct H.\n - left. reflexivity.\n - right. exists n.\n split.\n + reflexivity.\n + apply H.\nQed.\n\nTheorem ev_minus2: forall n,\n even n -> even (pred (pred n)).\nProof.\n intros.\n destruct H.\n - simpl. apply ev_0.\n - simpl. apply H.\nQed.\n\nTheorem evSS_ev: forall n,\n even (S (S n)) -> even n.\nProof.\n intros.\n apply ev_inversion in H.\n destruct H.\n - discriminate H.\n - destruct H as [n' [H1 H2]].\n injection H1 as H1.\n rewrite H1. apply H2.\nQed.\n\nTheorem evSS_ev': forall n,\n even (S (S n)) -> even n.\nProof.\n intros.\n inversion H.\n apply H1.\nQed.\n\nTheorem one_not_even: ~ even 1.\nProof.\n unfold not.\n intros.\n apply ev_inversion in H.\n destruct H.\n - discriminate H.\n - destruct H as [n' [H1 H2]].\n discriminate H1.\nQed.\n\n(* Exercise inversion_practice *)\nTheorem SSSSev__even: forall n,\n even (S (S (S (S n)))) -> even n.\nProof.\n intros.\n inversion H.\n inversion H1.\n apply H3.\nQed.\n\nTheorem SSSSev__even': forall n,\n even (S (S (S (S n)))) -> even n.\nProof.\n intros.\n apply evSS_ev, evSS_ev, H.\nQed.\n\n(* Theorem even5_nonsense *)\nTheorem even5_nonsense:\n even 5 -> 2 + 2 = 9.\nProof.\n intros H.\n exfalso.\n inversion H.\n inversion H1.\n inversion H3.\nQed.\n\nTheorem inversion_ex1: forall n m o: nat,\n [n; m] = [o; o] -> [n] = [m].\nProof.\n intros. inversion H. reflexivity.\nQed.\n\nTheorem inversion_ex2: forall n: nat, \n S n = O -> 2 + 2 = 5.\nProof.\n intros. inversion H.\nQed.\n\n(* Chap 7.2.2 Induction on Evidence *)\nLemma ev_even: forall n,\n even n -> exists k, n = double k.\nProof.\n intros. \n induction H.\n - exists 0. reflexivity.\n - destruct IHeven.\n rewrite H0.\n exists (S x).\n simpl. reflexivity.\nQed.\n\nTheorem ev_sum: forall n m, even n -> even m -> even (n + m).\nProof.\n intros.\n induction H.\n - simpl. apply H0.\n - simpl. apply ev_SS, IHeven.\nQed.\n\nInductive even': nat -> Prop :=\n | even'_0: even' 0\n | even'_2: even' 2\n | even'_sum n m (Hn: even' n) (Hm: even' m): even' (n + m).\n\nTheorem even'_ev: forall n, even' n <-> even n.\nProof.\n intros. split.\n - intros. induction H.\n + apply ev_0.\n + apply ev_SS, ev_0.\n + apply ev_sum. apply IHeven'1. apply IHeven'2.\n - intros. induction H.\n + apply even'_0.\n + assert (I: S (S n) = 2 + n).\n { simpl. reflexivity. }\n rewrite I. apply even'_sum.\n apply even'_2. apply IHeven.\nQed.\n\nTheorem ev_ev__ev: forall n m,\n even (n+m) -> even n -> even m.\nProof.\n intros.\n induction H0.\n simpl in H.\n - apply H.\n - apply IHeven.\n simpl in H.\n apply evSS_ev in H.\n apply H.\nQed.\n\nLemma plus_twice_eq_double:\n forall n, n + n = double n.\nProof.\n intros.\n induction n.\n - reflexivity.\n - simpl. rewrite <- IHn.\n rewrite <- plus_n_Sm.\n reflexivity.\nQed.\n\nTheorem ev_plus_plus: forall n m p,\n even (n+m) -> even (n+p) -> even (m+p).\nProof. \n intros.\n apply ev_ev__ev with (n := n + n).\n rewrite plus_assoc.\n assert(I: n + n + m = n + m + n).\n { rewrite <- plus_assoc. rewrite plus_comm. reflexivity. }\n rewrite I. rewrite <- plus_assoc.\n apply ev_sum.\n apply H.\n apply H0.\n rewrite plus_twice_eq_double.\n apply ev_double.\nQed.\n\n(* Chap 7.3 Inductive Relations *)\nModule Playground.\n\nInductive le: nat -> nat -> Prop :=\n | le_n n: le n n\n | le_S n m (H: le n m): le n (S m).\n\nNotation \"m <= n\" := (le m n).\n\nTheorem test_le1: 3 <= 3.\nProof. apply le_n. Qed.\n\nTheorem test_le2: 3 <= 6.\nProof. apply le_S, le_S, le_S, le_n. Qed.\n\nTheorem test_le3: (2 <= 1) -> 2 + 2 = 5.\nProof. intros. inversion H. inversion H2. Qed.\n\nEnd Playground.\n\nDefinition lt (n m: nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\nInductive square_of: nat -> nat -> Prop :=\n | sq n: square_of n (n * n).\n\nInductive next_nat: nat -> nat -> Prop :=\n | nn n: next_nat n (S n).\n\nInductive next_even: nat -> nat -> Prop :=\n | ne_1 n: even (S n) -> next_even n (S n)\n | ne_2 n (H: even (S (S n))): next_even n (S (S n)).\n\n(* Exercise total_relation *)\nInductive total_relation: nat -> nat -> Prop :=\n | re_0_0: total_relation 0 0\n | re_S_0 n (H: total_relation n 0): total_relation (S n) 0\n | re_n_S n m (H: total_relation n m): total_relation n (S m).\n\n(* Exercise empty_relation *)\nInductive empty_relation: nat -> nat -> Prop := .\n\n(* Exercise le_exercises *)\nLemma le_trans: forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n intros.\n induction H0.\n - apply H.\n - simpl. apply le_S, IHle.\nQed.\n\nTheorem O_le_n: forall n, 0 <= n.\nProof.\n intros.\n induction n.\n - reflexivity.\n - apply le_S, IHn.\nQed.\n\nTheorem n_le_m__Sn_le_Sm: forall n m, n <= m -> S n <= S m.\nProof.\n intros.\n induction H.\n - reflexivity.\n - apply le_S, IHle.\nQed.\n\nTheorem Sn_le_Sm__n_le_m: forall n m, S n <= S m -> n <= m.\nProof.\n intros.\n inversion H.\n - apply le_n.\n - apply (le_trans n (S n)).\n + apply le_S, le_n.\n + apply H1.\nQed.\n\nTheorem le_plus_l: forall a b, a <= a + b.\nProof.\n intros.\n induction b.\n - rewrite <- plus_n_O. apply le_n.\n - rewrite <- plus_n_Sm. apply le_S, IHb.\nQed.\n\nTheorem plus_lt: forall n1 n2 m, n1 + n2 < m -> n1 < m /\\ n2 < m.\nProof.\n unfold lt.\n intros.\n induction H.\n - split.\n + apply n_le_m__Sn_le_Sm, le_plus_l.\n + apply n_le_m__Sn_le_Sm.\n rewrite <- plus_comm.\n apply le_plus_l.\n - destruct IHle as [H1 H2].\n split.\n + apply le_S, H1.\n + apply le_S, H2.\nQed.\n\nTheorem lt_S: forall n m, n < m -> n < S m.\nProof.\n unfold lt.\n intros.\n apply le_S, H.\nQed.\n\nTheorem leb_complete: forall n m, n <=? m = true -> n <= m.\nProof.\n intros.\n generalize dependent n.\n induction m.\n - intros. induction n.\n + apply le_n.\n + inversion H.\n - intros. induction n.\n + apply O_le_n.\n + apply n_le_m__Sn_le_Sm, IHm, H.\nQed.\n\n(* This is the version of induction n. *)\nTheorem leb_correct: forall n m, n <= m -> n <=? m = true.\nProof.\n intros n.\n induction n.\n - intros. inversion H.\n + reflexivity.\n + reflexivity.\n - intros. inversion H.\n + simpl. rewrite <- leb_refl. reflexivity.\n + simpl. apply IHn. apply le_trans with (n := S n).\n apply le_S, le_n. apply H0.\nQed.\n\nTheorem leb_true_trans: forall n m o,\n n <=? m = true -> m <=? o = true -> n <=? o = true.\nProof.\n intros.\n apply leb_correct.\n apply leb_complete in H.\n apply leb_complete in H0.\n apply le_trans with (n := m).\n apply H.\n apply H0.\nQed.\n(* Ques: how to use \"induction\" to proof this? *)\n\n(* Exercise leb_iff *)\nTheorem leb_iff: forall n m, n <=? m = true <-> n <= m.\nProof.\n split.\n - apply leb_complete.\n - apply leb_correct.\nQed.\n\nModule R.\n(* Exercise R_provability, R_fact *)\nInductive R: nat -> nat -> nat -> Prop :=\n | c1: R 0 0 0\n | c2 m n o (H: R m n o): R (S m) n (S o)\n | c3 m n o (H: R m n o): R m (S n) (S o)\n | c4 m n o (H: R (S m) (S n) (S (S o))): R m n o\n | c5 m n o (H: R m n o): R n m o.\n\nDefinition fR: nat -> nat -> nat := plus.\n\nTheorem R_equiv_fR: forall m n o, R m n o <-> fR m n = o.\nProof.\n intros. split.\n - intros. induction H.\n + reflexivity.\n + unfold fR. simpl.\n unfold fR in IHR.\n apply f_equal, IHR.\n + unfold fR. rewrite <- plus_n_Sm.\n unfold fR in IHR.\n apply f_equal, IHR.\n + unfold fR. unfold fR in IHR. simpl in IHR.\n injection IHR. intros.\n rewrite <- plus_n_Sm in H0. \n injection H0 as H0. apply H0.\n + unfold fR. unfold fR in IHR.\n rewrite plus_comm. apply IHR.\n - generalize dependent n. \n generalize dependent o.\n induction m.\n + intros n. induction n.\n * intros. simpl in H. rewrite H. apply c1.\n * intros. simpl in H. simpl in IHn. rewrite H. apply c3, IHn. reflexivity.\n + intros n. induction n.\n * intros. discriminate H.\n * intros. simpl in H. injection H as H. apply c2. apply IHm, H.\nQed.\n\nEnd R.\n\n(* Exercise subsequence *)\nInductive subseq {X: Type}: list X -> list X -> Prop :=\n | empty l: subseq [] l\n | remove_one x l1 l2 (H: subseq l1 l2): subseq l1 (x :: l2)\n | remove_both x l1 l2 (H: subseq l1 l2): subseq (x :: l1) (x :: l2).\n\nTheorem subseq_refl: forall X (l: list X), subseq l l.\nProof.\n intros.\n induction l.\n - apply empty.\n - apply remove_both, IHl.\nQed.\n\nTheorem subseq_app: forall X (l1 l2 l3: list X), subseq l1 l2 -> subseq l1 (l2 ++ l3).\nProof.\n intros.\n induction H. \n - apply empty.\n - simpl. apply remove_one, IHsubseq.\n - simpl. apply remove_both, IHsubseq.\nQed.\n\nLemma subset_empty_is_empty: forall X (l: list X), subseq l [] -> l = [].\nProof.\n intros.\n inversion H.\n reflexivity.\nQed.\n\nTheorem subseq_trans: forall X (l1 l2 l3: list X), subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof.\n intros.\n generalize dependent l1. \n induction H0.\n - intros. apply subset_empty_is_empty in H.\n rewrite H. apply empty.\n - intros. apply remove_one, IHsubseq, H.\n - intros. inversion H.\n + apply empty.\n + apply remove_one, IHsubseq, H3.\n + apply remove_both, IHsubseq, H3.\nQed.\n\n(* Exercise R_provability2 *)\nModule Ex_R.\n\nInductive R: nat -> list nat -> Prop :=\n | c1: R 0 []\n | c2: forall n l, R n l -> R (S n) (n :: l)\n | c3: forall n l, R (S n) l -> R n l.\n\nExample R_ex1: R 2 [1; 0].\nProof. apply c2, c2, c1. Qed.\n\nExample R_ex2: R 1 [1; 2; 1; 0].\nProof. apply c3, c2, c3, c3, c2, c2, c2, c1. Qed.\n\n(* Example R_ex3: R 6 [3; 2; 1; 0]. This cannot be proved. *)\n\nEnd Ex_R.\n\n(* Chap 7.4 Case Study: Regular Expressions *) \nInductive reg_exp {T: Type} : Type :=\n | EmptySet\n | EmptyStr\n | Char (t: T)\n | App (r1 r2: reg_exp)\n | Union (r1 r2: reg_exp)\n | Star (r: reg_exp).\n\nInductive exp_match {T}: list T -> reg_exp -> Prop :=\n | MEmpty: exp_match [] EmptyStr\n | MChar x: exp_match [x] (Char x)\n | MApp s1 re1 s2 re2 (H1: exp_match s1 re1) (H2: exp_match s2 re2): exp_match (s1 ++ s2) (App re1 re2)\n | MUnionL s1 re1 re2 (H1: exp_match s1 re1): exp_match s1 (Union re1 re2)\n | MUnionR s2 re1 re2 (H2: exp_match s2 re2): exp_match s2 (Union re1 re2)\n | MStar0 re: exp_match [] (Star re)\n | MStarApp s1 s2 re (H1: exp_match s1 re) (H2: exp_match s2 (Star re)): exp_match (s1 ++ s2) (Star re).\n\nNotation \"s =~ re\" := (exp_match s re) (at level 80).\n\nExample reg_exp_ex1: [1] =~ Char 1.\nProof. apply MChar. Qed.\n\nExample reg_exp_ex2: [1; 2] =~ App (Char 1) (Char 2).\nProof. \n apply (MApp [1] (Char 1) [2] (Char 2)).\n - apply MChar.\n - apply MChar.\nQed.\n\nExample reg_exp_ex3: ~([1; 2] =~ Char 1).\nProof.\n intros H. inversion H.\nQed.\n\nFixpoint reg_exp_of_list {T} (l: list T) :=\n match l with\n | [] => EmptyStr\n | x :: l' => App (Char x) (reg_exp_of_list l')\n end.\n\nExample reg_exp_ex4: [1; 2; 3] =~ reg_exp_of_list [1; 2; 3].\nProof.\n apply (MApp [1] _ [2; 3]).\n - apply MChar.\n - apply (MApp [2] _ [3]).\n + apply MChar.\n + apply (MApp [3] _ []).\n * apply MChar.\n * apply MEmpty.\nQed.\n\nLemma MStar1:\n forall T s (re: @reg_exp T), s =~ re -> s =~ Star re.\nProof.\n intros.\n rewrite <- (app_nil_r _ s).\n apply (MStarApp s [] re).\n - apply H.\n - apply MStar0.\nQed.\n\n(* Example exp_match_ex1 *)\nLemma empty_is_empty: forall T (s: list T), ~(s =~ EmptySet).\nProof.\n unfold not. intros. inversion H.\nQed.\n\nLemma MUnion': forall T (s: list T) (re1 re2: @reg_exp T),\n s =~ re1 \\/ s =~ re2 -> s =~ (Union re1 re2).\nProof.\n intros. destruct H as [H1 | H2].\n - apply (MUnionL s re1 re2), H1.\n - apply (MUnionR s re1 re2), H2.\nQed.\n\nLemma MStar': forall T (ss: list (list T)) (re: reg_exp),\n (forall s, In s ss -> s =~ re) -> fold app ss [] =~ Star re.\nProof.\n intros. induction ss.\n - simpl. apply MStar0.\n - simpl. apply MStarApp.\n + apply H. simpl. left. reflexivity.\n + apply IHss. intros. apply H. simpl. right. apply H0.\nQed.\n\n(* Exercise reg_exp_of_list_spec *)\nLemma reg_exp_of_list_spec: forall T (s1 s2: list T),\n s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof. \n split.\n - generalize dependent s1.\n induction s2.\n + intros. simpl in H. inversion H. reflexivity.\n + intros. simpl in H. inversion H. apply IHs2 in H4. \n inversion H3. rewrite H4. simpl. reflexivity.\n - generalize dependent s2.\n induction s1.\n + intros. rewrite <- H. simpl. apply MEmpty.\n + intros. rewrite <- H. simpl.\n replace (x :: s1) with ([x] ++ s1).\n apply MApp.\n * apply MChar. \n * apply IHs1. reflexivity.\n * simpl. reflexivity.\nQed.\n\nFixpoint re_chars {T} (re: reg_exp): list T :=\n match re with\n | EmptySet => []\n | EmptyStr => []\n | Char x => [x]\n | App re1 re2 => re_chars re1 ++ re_chars re2\n | Union re1 re2 => re_chars re1 ++ re_chars re2\n | Star re => re_chars re\n end.\n\nTheorem in_re_match: forall T (s: list T) (re: reg_exp) (x: T),\n s =~ re -> In x s -> In x (re_chars re).\nProof.\n intros.\n induction H.\n - simpl in H0. simpl. apply H0.\n - simpl in H0. simpl. apply H0.\n - simpl. rewrite In_app_iff in *.\n destruct H0 as [H2 | H3].\n + left. apply IHexp_match1, H2.\n + right. apply IHexp_match2, H3.\n - simpl. rewrite In_app_iff.\n left. apply IHexp_match, H0.\n - simpl. rewrite In_app_iff.\n right. apply IHexp_match, H0.\n - destruct H0.\n - simpl in *. rewrite In_app_iff in *.\n destruct H0 as [H2 | H3].\n + apply IHexp_match1, H2.\n + apply IHexp_match2, H3.\nQed.\n\n(* Exercise re_not_empty *)\nFixpoint re_not_empty {T: Type} (re: @reg_exp T) : bool :=\n match re with\n | EmptySet => false\n | EmptyStr => true\n | Char t => true\n | App r1 r2 => (re_not_empty r1) && (re_not_empty r2)\n | Union r1 r2 => (re_not_empty r1) || (re_not_empty r2)\n | Star r => true\n end.\n\nLemma re_not_empty_correct: forall T (re: @reg_exp T),\n (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n intros.\n split.\n - induction re.\n + intros [s H]. inversion H.\n + reflexivity.\n + reflexivity.\n + intros [s H]. inversion H. simpl.\n apply andb_true_iff. split.\n * apply IHre1. exists s1. apply H3.\n * apply IHre2. exists s2. apply H4.\n + intros [s H]. inversion H.\n * simpl. \n apply orb_true_iff. left.\n apply IHre1. exists s. apply H2. \n * simpl.\n apply orb_true_iff. right.\n apply IHre2. exists s. apply H1.\n + reflexivity.\n - induction re.\n + intros. discriminate H.\n + intros. exists []. apply MEmpty.\n + intros. exists [t]. apply MChar.\n + intros. inversion H.\n apply andb_true_iff in H1.\n destruct H1 as [H1 H2].\n induction IHre1. induction IHre2.\n exists (x ++ x0). apply MApp. apply H0. apply H3. apply H2. apply H1.\n + intros. inversion H.\n apply orb_true_iff in H1.\n destruct H1 as [H1 | H2].\n * induction IHre1. exists x. apply MUnionL. apply H0. apply H1.\n * induction IHre2. exists x. apply MUnionR. apply H0. apply H2.\n + intros. exists []. apply MStar0.\nQed.\n\n(* The remember Tactic *)\nLemma star_app: forall T (s1 s2: list T) (re: reg_exp),\n s1 =~ Star re -> s2 =~ Star re -> s1 ++ s2 =~ Star re.\nProof.\n intros T s1 s2 re H1.\n remember (Star re) as re'.\n generalize dependent s2.\n induction H1. \n - discriminate.\n - discriminate.\n - discriminate.\n - discriminate.\n - discriminate.\n - injection Heqre'. \n intros. simpl. apply H0.\n - injection Heqre'. \n intros. rewrite <- app_assoc.\n apply MStarApp.\n + apply H1_.\n + apply IHexp_match2.\n * rewrite H. reflexivity.\n * apply H0.\nQed.\n\n(* Exercise exp_match_ex2 *)\nLemma MStar'': forall T (s: list T) (re: reg_exp),\n s =~ Star re ->\n exists ss: list (list T), s = fold app ss [] /\\ \n exists s', In s' ss -> s' =~ re.\nProof.\n intros.\n remember (Star re) as re'.\n induction H.\n - discriminate.\n - discriminate.\n - discriminate.\n - discriminate.\n - discriminate.\n - exists []. simpl. split.\n + reflexivity.\n + exists []. intros. exfalso. apply H.\n - inversion Heqre'. \n apply IHexp_match2 in Heqre'.\n destruct Heqre' as [ss [H3 H4]].\n exists ([s1] ++ ss).\n split.\n + simpl. rewrite <- H3. reflexivity.\n + simpl. exists s1.\n intros. rewrite H2 in H. apply H.\nQed.\n\n(* Exercise pumping *)\nModule Pumping.\n\nFixpoint pumping_constant {T} (re: @reg_exp T) : nat :=\n match re with\n | EmptySet => 0\n | EmptyStr => 1\n | Char _ => 2\n | App re1 re2 => pumping_constant re1 + pumping_constant re2\n | Union re1 re2 => pumping_constant re1 + pumping_constant re2\n | Star _ => 1\n end.\n\nFixpoint napp {T} (n: nat) (l: list T) : list T :=\n match n with\n | 0 => []\n | S n' => l ++ napp n' l\n end.\n\nLemma napp_plus: forall T (n m: nat) (l: list T),\n napp (n + m) l = napp n l ++ napp m l.\nProof.\n intros.\n induction n.\n - reflexivity.\n - simpl. rewrite IHn, app_assoc. reflexivity.\nQed.\n\nImport Coq.omega.Omega.\nLemma pumping: forall T (re: @reg_exp T) s,\n s =~ re -> pumping_constant re <= length s ->\n exists s1 s2 s3, s = s1 ++ s2 ++ s3 /\\ s2 <> [] /\\\n forall m, s1 ++ napp m s2 ++ s3 =~ re.\nProof.\n intros T re s Hmatch.\n induction Hmatch\n as [ | x | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n | s1 re1 re2 Hmatch IH | s2 re1 re2 Hmatch IH\n | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2 ].\n - (* MEmpty *)\n simpl. omega.\n - (* MChar *)\n simpl. omega.\n - (* MApp *)\n simpl. intros. \n rewrite app_length in H.\n apply Nat.add_le_cases in H.\n destruct H as [H | H].\n + apply IH1 in H. destruct H as [s3 [s4 [s5 [H1 [H2 H3]]]]].\n exists s3, s4, (s5 ++ s2). rewrite H1. \n rewrite <- app_assoc. rewrite <- app_assoc. split.\n * reflexivity.\n * split.\n { apply H2. }\n { intros. rewrite -> app_assoc. rewrite -> app_assoc. \n rewrite <- app_assoc with (m := (napp m s4)).\n apply MApp. apply H3. apply Hmatch2. }\n + apply IH2 in H. destruct H as [s3 [s4 [s5 [H1 [H2 H3]]]]].\n exists (s1 ++ s3), s4, s5. rewrite H1.\n rewrite <- app_assoc. split.\n * reflexivity.\n * split.\n { apply H2. }\n { intros. rewrite <- app_assoc.\n apply MApp. apply Hmatch1.\n apply H3. }\n - (* MUnionL *)\n simpl. intros.\n apply le_trans with (n := pumping_constant re1) in H.\n + apply IH in H. destruct H as [s2 [s3 [s4 [H1 [H2 H3]]]]].\n exists s2, s3, s4. rewrite H1. split.\n * reflexivity.\n * split.\n { apply H2. }\n { intros. apply MUnionL. apply H3. }\n + apply le_plus_l.\n - (* MUnionR *)\n simpl. intros. \n rewrite plus_comm in H.\n apply le_trans with (n := pumping_constant re2) in H.\n apply IH in H. destruct H as [s1 [s3 [s4 [H1 [H2 H3]]]]].\n + exists s1, s3, s4. rewrite H1. split.\n * reflexivity.\n * split.\n { apply H2. }\n { intros. apply MUnionR. apply H3. }\n + apply le_plus_l.\n - (* MStar0 *)\n simpl. intros. inversion H.\n - (* MStarApp *)\n simpl. intros. rewrite app_length in H.\n destruct s1.\n + destruct s2.\n * inversion H.\n * simpl in H. simpl in IH2. apply IH2 in H.\n destruct H as [s1 [s3 [s4 [H1 [H2 H3]]]]].\n rewrite H1. simpl. exists s1, s3, s4. split.\n { reflexivity. }\n { split.\n - apply H2.\n - apply H3. }\n + exists [], (x :: s1), s2. split.\n * reflexivity. \n * split.\n { intro. discriminate. }\n { intro. simpl. apply star_app.\n - induction m.\n + simpl. apply MStar0.\n + remember (x :: s1) as s1'.\n simpl. apply star_app.\n rewrite <- app_nil_r with (l := s1').\n apply MStarApp.\n apply Hmatch1.\n apply MStar0.\n apply IHm.\n - apply Hmatch2. }\nQed.\n\nEnd Pumping.\n\n(* Chap 7.5 Case Study: Improving Reflection *)\nTheorem filter_not_empty_In: forall n l,\n filter (fun x => n =? x) l <> [] -> In n l.\nProof.\n intros n l.\n induction l.\n - simpl. intros. apply H. reflexivity.\n - simpl. destruct (n =? x) eqn: H.\n + intros. rewrite eqb_eq in H.\n left. rewrite H. reflexivity.\n + intros. right. apply IHl. apply H0.\nQed.\n\nInductive reflect (P: Prop) : bool -> Prop :=\n | ReflectT (H: P): reflect P true\n | ReflectF (H: ~P): reflect P false.\n\nTheorem iff_reflect: forall P b, (P <-> b = true) -> reflect P b.\nProof.\n intros. destruct b.\n - apply ReflectT. apply H. reflexivity.\n - apply ReflectF. rewrite H. discriminate.\nQed.\n\n(* Exercise reflect_iff *)\nTheorem reflect_iff: forall P b, reflect P b -> (P <-> b = true).\nProof.\n intros P b H.\n induction H.\n - split.\n + reflexivity.\n + intros. apply H.\n - split.\n + intros. apply H in H0. exfalso. apply H0.\n + intros. discriminate H0.\nQed.\n\nLemma eqbP: forall n m, reflect (n = m) (n =? m).\nProof.\n intros. apply iff_reflect. rewrite eqb_eq. reflexivity.\nQed.\n\nTheorem filter_not_empty_In': forall n l,\n filter (fun x => n =? x) l <> [] -> In n l.\nProof.\n intros n l.\n induction l.\n - simpl. intros. apply H. reflexivity.\n - simpl. destruct (eqbP n x) as [H | H]. \n + intros. rewrite H. left. reflexivity.\n + intros. right. apply IHl. apply H0.\nQed.\n\nFixpoint count n l :=\n match l with\n | [] => 0\n | m :: l' => (if n =? m then 1 else 0) + count n l'\n end.\n\n(* Exercise eqbP_practice *)\nTheorem eqbP_practice: forall n l,\n count n l = 0 -> ~ (In n l).\nProof.\n intros n l.\n induction l.\n - intros. simpl. \n unfold not. intros H'. apply H'.\n - intros. simpl.\n destruct (eqbP n x) as [H' | H'].\n + rewrite H' in H.\n simpl in H. rewrite <- eqb_refl in H.\n discriminate H.\n + unfold not. intros.\n destruct H0 as [H1 | H2].\n * unfold not in H'. symmetry in H1. \n apply H' in H1. apply H1.\n * simpl in H. unfold not in IHl. \n apply IHl in H2.\n apply H2.\n replace (n =? x) with false in H.\n simpl in H. apply H.\n destruct (n =? x).\n { discriminate. } { reflexivity. }\nQed.\n(* Ques: too long? *)\n\n(* Chap 7.6 Additional Exercises *)\n(* Exercise nostutter_defn *)\nDefinition check_is_not_head {X: Type} (l: list X) (x: X) : Prop :=\n match l with\n | [] => True\n | h :: t => x <> h\n end.\n\nInductive nostutter {X: Type} : list X -> Prop :=\n | nostutter_nil: nostutter []\n | nostutter_add x l (H: check_is_not_head l x) (I: nostutter l): nostutter (x :: l).\n\nExample test_nostutter_1: nostutter [3;1;4;1;5;6].\nProof.\n repeat constructor; apply eqb_neq; auto.\nQed.\n\nExample test_nostutter_2: nostutter (@nil nat).\nProof.\n repeat constructor; apply eqb_neq; auto.\nQed.\n\nExample test_nostutter_3: nostutter [5].\nProof.\n repeat constructor; apply eqb_false; auto. \nQed.\n\nExample test_nostutter_4: not (nostutter [3;1;1;4]).\nProof.\n intro.\n repeat match goal with\n h: nostutter _ |- _ => inversion h; clear h; subst\n end.\n contradiction H0; auto. \nQed.\n\n\n(* Exercise filter_challenge *)\nInductive merge_in_order {X: Type}: list X -> list X -> list X -> Prop :=\n | Empty_MIO: merge_in_order [] [] []\n | MergeLeft: forall l1 l2 l x, merge_in_order l1 l2 l -> merge_in_order (x :: l1) l2 (x :: l)\n | MergeRight: forall l1 l2 l x, merge_in_order l1 l2 l -> merge_in_order l1 (x :: l2) (x :: l).\n\nTheorem merge_filter_only: forall X (l1 l2 l: list X) (test: X -> bool),\n merge_in_order l1 l2 l -> \n (forall x, In x l1 -> test x = true) ->\n (forall x, In x l2 -> test x = false) ->\n filter test l = l1.\nProof.\n intros.\n induction H.\n - reflexivity.\n - simpl. rewrite -> H0.\n + apply IHmerge_in_order in H1.\n rewrite H1. reflexivity.\n intros. apply H0. simpl. right. apply H2.\n + simpl. left. reflexivity.\n - simpl.\n destruct (test x) eqn: Htest.\n + assert (Hcontra: test x = false).\n { apply H1. simpl. left. reflexivity. }\n rewrite Hcontra in Htest.\n discriminate Htest.\n + apply IHmerge_in_order in H0.\n apply H0.\n intros. apply H1. simpl. right. apply H2.\nQed.\n\n(* Exercise filter_challenge_2 *)\nPrint subseq.\nTheorem filter_behavior: forall X (l sl: list X) (test: X -> bool),\n subseq sl l ->\n forallb test sl = true ->\n length sl <= length (filter test l).\nProof.\n intros X l sl test H1.\n induction H1.\n - intros H2. simpl. apply O_le_n.\n - intros H2. simpl.\n destruct (test x) eqn: Htest.\n + simpl. apply le_S. apply IHsubseq. apply H2.\n + simpl. apply IHsubseq. apply H2.\n - intros H2. simpl.\n destruct (test x) eqn: Htest.\n + simpl. apply n_le_m__Sn_le_Sm. apply IHsubseq.\n simpl in H2. rewrite Htest in H2. apply H2.\n + simpl in H2. rewrite Htest in H2. discriminate H2.\nQed.\n\n(* Exercise palindromes *) \nInductive pal {X: Type}: list X -> Prop :=\n | Empty_P: pal []\n | One_P: forall c, pal [c]\n | Add_P: forall c l, pal l -> pal (c :: l ++ [c]).\n\nTheorem pal_app_rev: forall X (l: list X), pal (l ++ rev l).\nProof.\n intros.\n induction l.\n - simpl. apply Empty_P.\n - simpl. rewrite app_assoc. apply Add_P, IHl.\nQed.\n\nTheorem pal_rev: forall X (l: list X), pal l -> l = rev l.\nProof.\n intros.\n induction H.\n - reflexivity.\n - reflexivity.\n - simpl. rewrite rev_app_distr. rewrite <- IHpal. reflexivity.\nQed.\n\n(* Exercise palindrome_converse *)\n(* \n First we prove that:\n If the Prop has the following property:\n If a Prop is true for all the numbers less than n, then it's true for n.\n Then we can conclude the Prop is true for all natural numbers n.\n*)\nLemma Prop_induction_for_nat: forall (P: nat -> Prop),\n (forall n, (forall m, m < n -> P m) -> P n) ->\n (forall n, P n).\nProof.\n intros. \n apply H.\n induction n.\n - intros. inversion H0.\n - apply H in IHn as Hn.\n intros.\n inversion H0.\n + apply Hn.\n + apply IHn. unfold lt. apply H2.\nQed.\n\n(* \n Then we prove a special nat induction way which is:\n The Prop is true for 0 and 1, and if the Prop is true for n, then it's true for (n + 2).\n From this we can conclude that the Prop is true for all n.\n We cannot use simple induction here because even and odd should be split, so we use the\n Prop_induction_for_nat we state before.\n*)\nLemma nat_induction: forall (P: nat -> Prop),\n P 0 -> P 1 -> (forall n, P n -> P (n + 2)) ->\n (forall n, P n).\nProof.\n intros.\n apply Prop_induction_for_nat.\n intros m H2.\n destruct m.\n - apply H.\n - destruct m.\n + apply H0.\n + assert (I: S (S m) = m + 2). { rewrite -> plus_comm. reflexivity. }\n rewrite I. apply H1.\n apply H2. unfold lt.\n apply le_S. apply le_n.\nQed.\n\n(*\n Next, we think about Prop connected to the list.\n Because we want to prove palindromes_converse Theorem, so we need to reduce the length\n twice a step. Then we need the following Lemma. It state if we can prove that forall n, \n lists that have length n satisfy Prop, we can prove all the lists satisfy the Prop.\n This lemma is quite easy to prove though, by connecting n with (length l).\n*)\nLemma length_induction: forall X (P: list X -> Prop),\n (forall n l, length l = n -> P l) ->\n forall l, P l.\nProof.\n intros.\n apply H with (n := length l).\n reflexivity.\nQed.\n\n(*\n This is Lemma state that \"list l is empty\" equals to \"list (rev l) is empty\"\n*)\nLemma rev_empty_eq_empty: forall X (l: list X), rev l = [] <-> l = [].\nProof.\n split.\n - intros. \n destruct l eqn: Hl.\n + reflexivity.\n + rewrite <- rev_involutive with (l := (x :: l0)).\n rewrite H. reflexivity.\n - intros. rewrite H. reflexivity.\nQed.\n\n(*\n This is a Lemma shows that if a list has length (n + 2), we can get its head and tail\n off the list, then its length becomes n.\n*)\nLemma list_length_SS: forall X (l: list X) n,\n (length l = n + 2) -> exists l' x y, l = [x] ++ l' ++ [y] /\\ length l' = n.\nProof.\n intros.\n destruct l.\n - rewrite <- plus_comm in H. simpl in H. discriminate.\n - rewrite <- plus_comm in H. simpl in H. injection H as H.\n destruct (rev l) eqn: Hr.\n + assert (Hempty: l = []).\n { apply rev_empty_eq_empty, Hr. }\n rewrite Hempty in H. simpl in H. discriminate.\n + exists (rev l0), x, x0.\n assert(I: l = rev l0 ++ [x0]).\n { rewrite <- rev_involutive with (l := l).\n rewrite Hr. simpl. reflexivity. }\n split.\n * rewrite I. simpl. reflexivity.\n * rewrite -> I in H. \n rewrite app_length in H. \n simpl in H.\n rewrite <- plus_n_Sm in H.\n injection H as H.\n rewrite <- plus_n_O in H.\n apply H.\nQed.\n\n(* \n This is a Lemma shows our induction about palindromes:\n i) Empty list satisfies the Prop\n ii) List which has only one element satisfies.\n iii) If we have a satisfied list l, we can add an element to the list head and add\n add an element to its tail, the new list still satisfies.\n If a Prop satisfies all the point above, then it's true for all the list.\n\n To prove this, we start with a induction on length using length_induction.\n and we make Pn as our new Prop (nat (here is length) -> Prop).\n i) try to prove Pn 0 is true.\n ii) try to prove Pn 1 is true.\n iii) try to prove if Pn n is true, then Pn (n + 2) is true.\n In this step, we may use the Lemma list_length_SS above to get the head and tail\n of the list and reduce the length by 2, so that we can use Pn n.\n iv) if we prove the things above, then we can prove forall list it is true.\n By introducing the length n of any list, and using nat_induction to prove Pn n is \n true).\n*)\nLemma palindrome_induction: forall X (P: list X -> Prop),\n P [] ->\n (forall x: X, P [x]) ->\n (forall (x y: X) (l: list X), P l -> P (x :: l ++ [y])) ->\n (forall l, P l).\nProof. \n intros.\n apply length_induction.\n remember (fun n => (forall l, length l = n -> P l)) as Pn.\n assert (Pn0: Pn 0).\n {\n rewrite HeqPn. intros. destruct l0.\n - apply H.\n - simpl in H2. discriminate.\n }\n assert (Pn1: Pn 1).\n {\n rewrite HeqPn. intros.\n destruct l0.\n - apply H.\n - destruct l0.\n + apply H0.\n + simpl in H2. discriminate.\n }\n assert (PnTrans: forall n, Pn n -> Pn (n + 2)).\n {\n rewrite HeqPn.\n intros.\n apply list_length_SS in H3 as H4.\n destruct H4 as [l' [x [y [H4 H5]]]].\n apply H2 in H5.\n rewrite H4. apply H1, H5.\n }\n intros n.\n assert (Pnn: Pn n).\n { apply nat_induction. apply Pn0. apply Pn1. apply PnTrans. }\n rewrite HeqPn in Pnn.\n apply Pnn.\nQed.\n\nLemma equal_length_eq: forall X (l1 l2: list X),\n l1 = l2 -> length l1 = length l2.\nProof.\n intros.\n rewrite H.\n reflexivity.\nQed.\n\nLemma app_one: forall X (l1 l2: list X) x y, l1 ++ [x] = l2 ++ [y] -> l1 = l2 /\\ x = y.\nProof.\n intros.\n generalize dependent l2.\n induction l1.\n - intros. destruct l2.\n + split. reflexivity. inversion H. rewrite H1 in H. reflexivity.\n + apply equal_length_eq in H. injection H as H.\n rewrite app_length in H. simpl in H. rewrite plus_comm in H. discriminate.\n - intros. destruct l2. \n + apply equal_length_eq in H. injection H as H.\n rewrite app_length in H. simpl in H. rewrite plus_comm in H. discriminate.\n + simpl. inversion H. rewrite H1 in *.\n apply IHl1 in H2. destruct H2 as [H2 H3]. split.\n * rewrite H2. reflexivity.\n * apply H3.\nQed.\n\nLemma rev_back_eq_front: forall X (l: list X) x,\n rev (l ++ [x]) = x :: rev l.\nProof.\n intros.\n induction l.\n - reflexivity.\n - simpl. rewrite IHl. simpl. reflexivity.\nQed.\n\n(*\n We can use palindrome_induction to prove this theorem, with P := l => l = rev l -> pal l.\n Length 0, and length 1 is easy to prove.\n How about length n + 2? We can use the result of length n to prove that x = y.\n*)\nTheorem palindrome_converse: forall X (l: list X), l = rev l -> pal l.\nProof.\n intros X l.\n apply palindrome_induction with (P := fun l => l = rev l -> pal l).\n - intros. apply Empty_P.\n - intros. apply One_P.\n - intros. simpl in *.\n replace (x :: l0 ++ [y]) with ((x :: l0) ++ [y]) in *.\n apply app_one in H0.\n destruct H0 as [H1 H2].\n simpl. rewrite H2 in *. apply Add_P.\n apply H. rewrite rev_back_eq_front in H1.\n injection H1 as H1. apply H1.\n simpl. reflexivity.\nQed.\n\n(* Exercise NoDup *)\nInductive NoDup {X: Type}: list X -> Prop :=\n | Empty_ND: NoDup []\n | Add_ND: forall x l, NoDup l -> ~ (In x l) -> NoDup (x :: l).\n\nDefinition disjoint {X: Type} (l1 l2: list X) :=\n forall x, In x l1 -> ~ (In x l2).\n\nExample NoDupTest1: NoDup [1;2;3;4].\nProof.\n apply Add_ND. apply Add_ND. apply Add_ND. apply Add_ND. apply Empty_ND.\n - simpl. unfold not. intros. apply H.\n - simpl. unfold not. intros. destruct H as [H | H]. \n + apply eqb_eq in H. simpl in H. discriminate H.\n + apply H.\n - simpl. unfold not. intros. destruct H as [H | [H | H]].\n + apply eqb_eq in H. discriminate H.\n + apply eqb_eq in H. discriminate H.\n + apply H.\n - simpl. unfold not. intros. destruct H as [H | [H | [H | H]]].\n + apply eqb_eq in H. discriminate H.\n + apply eqb_eq in H. discriminate H.\n + apply eqb_eq in H. discriminate H.\n + apply H.\nQed.\n\nTheorem NoDup_app: forall X (l1 l2: list X),\n NoDup l1 -> NoDup l2 ->\n disjoint l1 l2 ->\n NoDup (l1 ++ l2).\nProof.\n intros X l1 l2.\n intros H1.\n induction H1.\n - intros. simpl. apply H.\n - intros. simpl. apply Add_ND. apply IHNoDup.\n + apply H0.\n + unfold disjoint in *. intros. apply H2. simpl. right. apply H3.\n + unfold not. intros. apply In_app_iff in H3.\n destruct H3 as [H3 | H3].\n * apply H in H3. apply H3.\n * unfold not in H2. apply H2 with (x0 := x).\n { simpl. left. reflexivity. }\n { apply H3. }\nQed.\n\n(* Exercise pigeonhole_principle *)\nLemma in_split: forall (X: Type) (x: X) (l: list X),\n In x l -> exists l1 l2, l = l1 ++ x :: l2.\nProof.\n intros X x l.\n induction l.\n - intros. simpl in H. destruct H.\n - intros. simpl in H.\n destruct H as [H | H].\n + exists []. exists l. simpl. rewrite H. reflexivity.\n + apply IHl in H.\n destruct H as [l1 [l2 H]].\n exists (x0 :: l1). exists l2. simpl. rewrite H. reflexivity.\nQed.\n\nInductive repeats {X: Type}: list X -> Prop :=\n | First_R: forall l x, In x l -> repeats (x :: l)\n | Add_R: forall l x, repeats l -> repeats (x :: l).\n\nTheorem pigeonhole_principle: forall (X: Type) (l1 l2: list X),\n excluded_middle -> (forall x, In x l1 -> In x l2) ->\n length l2 < length l1 ->\n repeats l1.\nProof.\n intros X l1.\n induction l1 as [|x l1' IHl1'].\n - intros. simpl in H1. inversion H1.\n - intros. simpl in H1.\n assert(Hex: In x l1' \\/ ~ In x l1').\n { apply H. }\n destruct Hex as [Hex | Hex].\n + apply First_R, Hex.\n + apply Add_R.\n assert(I: In x l2). { apply H0. simpl. left. reflexivity. }\n apply in_split in I.\n destruct I as [l1 [l3 I]].\n apply IHl1' with (l2 := l1 ++ l3).\n * apply H.\n * intros.\n rewrite I in H0.\n assert (H': x <> x0). \n { intros contra. rewrite <- contra in H2. apply Hex in H2. apply H2. }\n assert (H3: In x0 l1' <-> In x0 (x :: l1')).\n { split.\n - intros. simpl. right. apply H3. \n - intros. destruct H3.\n + apply H' in H3. inversion H3.\n + apply H3. }\n rewrite H3 in H2.\n apply H0 in H2.\n apply In_app_iff in H2.\n apply In_app_iff.\n destruct H2.\n { left. apply H2. }\n { right. simpl in H2.\n destruct H2.\n - apply H' in H2. inversion H2.\n - apply H2.\n }\n * rewrite I in H1. \n rewrite app_length, plus_comm in H1.\n simpl in H1. unfold lt in *.\n apply le_pred in H1. simpl in H1.\n rewrite app_length, plus_comm.\n apply H1.\nQed.\n\n(* Extended Exercise: A Verified Regular-Expression Matcher *)\nRequire Export Coq.Strings.Ascii.\nDefinition string := list ascii.\n\nLemma provable_equiv_true: forall (P: Prop), P -> (P <-> True).\nProof.\n intros.\n split.\n - intros. constructor.\n - intros. apply H.\nQed.\n\nLemma not_equiv_false: forall (P: Prop), ~P -> (P <-> False).\nProof.\n intros.\n split.\n - intros. apply H in H0. apply H0.\n - intros. exfalso. apply H0.\nQed.\n\nLemma null_matches_none: forall (s: string), (s =~ EmptySet) <-> False.\nProof.\n intros.\n apply not_equiv_false.\n unfold not.\n intros. inversion H.\nQed.\n\nLemma empty_matches_eps: forall (s: string), (s =~ EmptyStr) <-> s = [].\nProof.\n intros. split.\n - intros. inversion H. reflexivity.\n - intros. rewrite H. apply MEmpty.\nQed.\n\nLemma empty_nomatch_ne: forall (a: ascii) (s: string), (a :: s =~ EmptyStr) <-> False.\nProof.\n intros. apply not_equiv_false.\n unfold not. intros.\n inversion H.\nQed.\n\nLemma char_nomatch_char: forall (a b: ascii) s, b <> a -> (b :: s =~ Char a) <-> False.\nProof.\n intros. apply not_equiv_false.\n unfold not. intros.\n inversion H0. apply H, H4.\nQed.\n\nLemma char_eps_suffix: forall (a: ascii) s, a :: s =~ Char a <-> s = [].\nProof.\n intros. split.\n - intros. inversion H. reflexivity.\n - intros. rewrite H. apply MChar.\nQed.\n\nLemma app_exists: forall (s: string) re0 re1,\n s =~ App re0 re1 <-> exists s0 s1, s = s0 ++ s1 /\\ s0 =~ re0 /\\ s1 =~ re1.\nProof.\n intros. split.\n - intros. inversion H.\n exists s1, s2.\n split.\n + reflexivity.\n + split. apply H3. apply H4.\n - intros. destruct H as [s0 [s1 [H1 [H2 H3]]]].\n rewrite H1. apply MApp. apply H2. apply H3.\nQed.\n\n(* Exercise app_ne *)\nLemma app_nil_l: forall X (l: list X), [] ++ l = l.\nProof. reflexivity. Qed.\n\nLemma app_ne: forall (a: ascii) s re0 re1,\n a :: s =~ (App re0 re1) <->\n ([] =~ re0 /\\ a :: s =~ re1) \\/\n (exists s0 s1, s = s0 ++ s1 /\\ a :: s0 =~ re0 /\\ s1 =~ re1).\nProof.\n intros. split.\n - intros. inversion H.\n destruct s1.\n + left. split. apply H3. apply H4.\n + right. exists s1, s2. simpl in H1. injection H1. intros.\n split. symmetry. apply H5.\n split. rewrite <- H6. apply H3.\n apply H4.\n - intros. destruct H as [H | H].\n + destruct H as [H1 H2].\n rewrite <- app_nil_l with (l := (a :: s)).\n apply MApp. apply H1. apply H2.\n + destruct H as [s0 [s1 [H1 [H2 H3]]]].\n replace (a :: s) with ((a :: s0) ++ s1).\n apply MApp. apply H2. apply H3.\n simpl. rewrite H1. reflexivity.\nQed.\n\nLemma union_disj: forall (s: string) re0 re1,\n s =~ Union re0 re1 <-> s =~ re0 \\/ s =~ re1.\nProof.\n intros. split.\n - intros. inversion H.\n + left. apply H2.\n + right. apply H1.\n - intros. destruct H as [H1 | H2].\n + apply MUnionL, H1.\n + apply MUnionR, H2.\nQed.\n\n(* Exercise star_ne *)\nLemma star_ne: forall (a: ascii) s re, a :: s =~ Star re <->\n exists s0 s1, s = s0 ++ s1 /\\ a :: s0 =~ re /\\ s1 =~ Star re.\nProof.\n intros. split.\n - intros.\n remember (Star re) as re'.\n remember (a :: s) as s'.\n induction H.\n + intros. inversion Heqs'.\n + intros. inversion Heqre'.\n + intros. inversion Heqre'.\n + intros. inversion Heqre'.\n + intros. inversion Heqre'.\n + intros. inversion Heqs'.\n + intros.\n destruct s1.\n * simpl in Heqs'.\n apply IHexp_match2 in Heqre'. apply Heqre'. apply Heqs'.\n * simpl in Heqs'.\n injection Heqs' as H1 H2.\n exists s1, s2. split.\n { rewrite H2. reflexivity. }\n { split. rewrite <- H1. injection Heqre' as Hre. rewrite <- Hre. apply H.\n apply H0.\n }\n - intros. destruct H as [s0 [s1 [H1 [H2 H3]]]].\n rewrite H1. \n replace (a :: s0 ++ s1) with ((a :: s0) ++ s1).\n apply MStarApp.\n + apply H2.\n + apply H3.\n + reflexivity.\nQed.\n\nDefinition refl_matches_eps m :=\n forall re : @reg_exp ascii, reflect ([ ] =~ re) (m re).\n\n(* Exercise match_eps *)\nPrint reg_exp. \nFixpoint match_eps (re: @reg_exp ascii) : bool :=\n match re with\n | EmptySet => false\n | EmptyStr => true\n | Char t => false\n | App re0 re1 => (match_eps re0) && (match_eps re1)\n | Union re0 re1 => (match_eps re0) || (match_eps re1)\n | Star re => true\n end.\n\nLemma app_nil_both_nil: forall X (l1 l2: list X),\n l1 ++ l2 = [] <-> l1 = [] /\\ l2 = [].\nProof.\n split.\n - intros. induction l1.\n + simpl in H. split. reflexivity. apply H.\n + simpl in H. discriminate H.\n - intros. destruct H as [H1 H2].\n rewrite H1, H2. reflexivity.\nQed.\n\nLemma match_eps_refl: refl_matches_eps match_eps.\nProof.\n unfold refl_matches_eps.\n intros.\n apply iff_reflect.\n split.\n - intros. \n induction re.\n + inversion H.\n + reflexivity.\n + inversion H.\n + inversion H.\n destruct s1 eqn: Hs1.\n * simpl in *. rewrite H1 in H4.\n apply andb_true_iff.\n split. apply IHre1, H3. apply IHre2, H4.\n * simpl in *.\n discriminate.\n + inversion H. \n * simpl in *.\n apply orb_true_iff. left. apply IHre1, H2.\n * simpl in *.\n apply orb_true_iff. right. apply IHre2, H1.\n + reflexivity.\n - intros. induction re.\n + discriminate H.\n + apply MEmpty.\n + discriminate H.\n + simpl in H. apply andb_true_iff in H. destruct H as [H1 H2].\n apply IHre1 in H1; apply IHre2 in H2.\n assert(H: [] ++ [] =~ App re1 re2).\n { apply MApp. apply H1. apply H2. }\n simpl in H. apply H.\n + simpl in H. apply orb_true_iff in H. destruct H as [H1 | H2].\n * apply IHre1 in H1. apply MUnionL. apply H1.\n * apply IHre2 in H2. apply MUnionR. apply H2.\n + apply MStar0.\nQed.\n\nDefinition is_der re (a: ascii) re' :=\n forall s, a :: s =~ re <-> s =~ re'.\n\nDefinition derives d := forall a re, is_der re a (d a re).\n\n(* Exercise derive *)\nFixpoint derive (a: ascii) (re: @reg_exp ascii): @reg_exp ascii :=\n match re with\n | EmptySet => EmptySet\n | EmptyStr => EmptyStr\n | Char t => \n if (nat_of_ascii a) =? (nat_of_ascii t) then EmptyStr \n else re\n | App re1 re2 => \n if (match_eps re1) then Union (derive a re2) (App (derive a re1) re2)\n else App (derive a re1) re2\n | Union re1 re2 => Union (derive a re1) (derive a re2)\n | Star re => Star (derive a re)\n end.\n(* Not sure about it *)\n\nExample c := ascii_of_nat 99.\nExample d := ascii_of_nat 100.\n\nExample test_der0 : match_eps (derive c (EmptySet)) = false.\nProof. reflexivity. Qed.\n\nExample test_der1 : match_eps (derive c (Char c)) = true.\nProof. reflexivity. Qed.\n\nExample test_der2 : match_eps (derive c (Char d)) = false.\nProof. reflexivity. Qed.\n\nExample test_der3 : match_eps (derive c (App (Char c) EmptyStr)) = true.\nProof. reflexivity. Qed.\n\nExample test_der4 : match_eps (derive c (App EmptyStr (Char c))) = true.\nProof. reflexivity. Qed.\n\nExample test_der5 : match_eps (derive c (Star (Char c))) = true.\nProof. reflexivity. Qed.\n\nExample test_der6 :\n match_eps (derive d (derive c (App (Char c) (Char d)))) = true.\nProof. reflexivity. Qed.\n\nExample test_der7 :\n match_eps (derive d (derive c (App (Char d) (Char c)))) = false.\nProof. reflexivity. Qed.\n\n(* Exercise derive_corr *)\nLemma derive_corr : derives derive.\nProof.\n unfold derives.\n unfold is_der.\n split.\n - generalize dependent a.\n generalize dependent s.\n induction re.\n + intros. inversion H.\n + intros. subst. inversion H.\n + intros. subst. inversion H.\n simpl. rewrite <- Induction.eqb_refl. apply MEmpty.\n + intros. simpl.\n apply app_ne in H.\n destruct H as [[H1 H2] | [s0 [s1 [H1 [H2 H3]]]]].\n * destruct (match_eps re1) eqn: Hmatch.\n { apply MUnionL. apply IHre2. apply H2. }\n { admit. }\n * destruct (match_eps re1) eqn: Hmatch.\n { admit. }\n { admit. }\n + intros. simpl. inversion H; subst.\n * apply MUnionL. apply IHre1. apply H2.\n * apply MUnionR. apply IHre2. apply H1.\n + intros. simpl.\n apply star_ne in H.\n destruct H as [s1 [s2 [H1 [H2 H3]]]].\n admit.\n - intros.\n generalize dependent s.\n generalize dependent a.\n induction re.\n + intros. inversion H.\n + intros. \n\nAdmitted.\n\nDefinition matches_regex m: Prop :=\n forall (s: string) re, reflect (s =~ re) (m s re).\n\n(* Exercise regex_match *)\nFixpoint regex_match (s: string) (reg: @reg_exp ascii) : bool.\nAdmitted.\n\n(* Exercise regex_refl *)\nTheorem regex_refl: matches_regex regex_match.\nProof.\nAdmitted.\n\n", "meta": {"author": "Galaxies99", "repo": "Logical-Foundations", "sha": "de2406647c0c22838b096a0dce346eb4d4be17e9", "save_path": "github-repos/coq/Galaxies99-Logical-Foundations", "path": "github-repos/coq/Galaxies99-Logical-Foundations/Logical-Foundations-de2406647c0c22838b096a0dce346eb4d4be17e9/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.9161096187428011, "lm_q1q2_score": 0.8610636621022842}} {"text": "Module NatPlayground2.\n\n(* 加 *)\nFixpoint plus (n : nat) (m : nat) : nat :=\n match n with\n | O => m\n | S n' => S (plus n' m)\n end.\n\nCompute (plus 3 2).\n\n(* 乘 *)\nFixpoint mult (n m : nat) : nat :=\n match n with\n | O => O\n | S n' => plus m (mult n' m)\n end.\n\nExample test_mult1: (mult 3 3) = 9.\nProof. simpl. reflexivity. Qed.\n\n(* 减 *)\nFixpoint minus (n m:nat) : nat :=\n match n, m with\n | O , _ => O\n | S _ , O => n\n | S n', S m' => minus n' m'\n end.\n\nExample test_minus1: (minus 3 2) = 1.\nProof. simpl. reflexivity. Qed.\n\n(* 幂 *)\nFixpoint exp (base power : nat) : nat :=\n match power with\n | O => S O\n | S p => mult base (exp base p)\n end.\n\nExample test_exp1: (exp 2 10) = 1024.\nProof. simpl. reflexivity. Qed.\n\nEnd NatPlayground2.", "meta": {"author": "TysonSir", "repo": "coq", "sha": "3d5cd319a377acbdad1bec34061d298043c9bc18", "save_path": "github-repos/coq/TysonSir-coq", "path": "github-repos/coq/TysonSir-coq/coq-3d5cd319a377acbdad1bec34061d298043c9bc18/week2/demo_4_calc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446440948805, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.860740114816141}} {"text": "From LF Require Export Basics.\n\n\n Theorem plus_n_O : forall n:nat, n = n + 0.\n Proof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *) reflexivity.\n - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity. Qed.\n \n Theorem minus_n_n : forall n,\n minus n n = 0.\n Proof.\n (* WORKED IN CLASS *)\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n simpl. reflexivity.\n - (* n = S n' *)\n simpl. rewrite -> IHn'. reflexivity. Qed. \n \n Theorem mult_0_r : forall n:nat,\n n * 0 = 0.\n Proof.\n intros n. induction n.\n - reflexivity.\n - simpl. rewrite->IHn. reflexivity.\n Qed.\n\n Theorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\n Proof.\n intros n m. induction n.\n - simpl. reflexivity.\n - simpl. rewrite->IHn. reflexivity. \n Qed.\n\n Theorem plus_comm : forall n m : nat,\n n + m = m + n.\n Proof.\n intros n m. induction n.\n - simpl. rewrite<-plus_n_O. reflexivity.\n - simpl. rewrite->IHn. rewrite->plus_n_Sm. reflexivity.\n Qed.\n\n Theorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\n Proof.\n intros n m p. induction n.\n - simpl. reflexivity.\n - simpl. rewrite->IHn. reflexivity. \n Qed.\n \n Fixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\n Lemma double_plus: forall n, double n = n+n .\n Proof.\n intros n . induction n.\n - reflexivity.\n - simpl. rewrite->IHn. rewrite->plus_n_Sm. reflexivity. \n Qed.\n\n Theorem evenb_S : forall n:nat,\n evenb (S n) = negb (evenb n).\n Proof.\n intros n. induction n.\n - simpl. reflexivity.\n - rewrite->IHn. rewrite->negb_involutive. simpl. reflexivity.\n Qed.\n \n Theorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\n Proof.\n intros n m.\n assert (H: 0 + n = n). { reflexivity. }\n rewrite -> H.\n reflexivity. Qed.\n \n Theorem plus_swap: forall n m p: nat,\n n+ (m+p) = m + (n+p).\n Proof.\n intros n m p.\n rewrite->plus_assoc.\n assert (H: n+m=m+n). { rewrite->plus_comm. reflexivity. }\n rewrite->H.\n rewrite<-plus_assoc. \n reflexivity.\n Qed.\n \n Theorem mult_plus_distr_1: forall n m:nat,\n n* S m = n + n * m.\n Proof.\n intros n m. induction n.\n - simpl. reflexivity.\n - simpl. rewrite->IHn. rewrite->plus_swap. reflexivity.\n Qed.\n \n Theorem mult_comm: forall m n:nat,\n m*n = n*m .\n Proof.\n intros m n. induction m.\n - simpl. rewrite->mult_0_r. reflexivity.\n - simpl. rewrite->IHm. rewrite->mult_plus_distr_1. reflexivity. \n Qed.\n \n\n Theorem leb_refl : forall n:nat,\n true = (n <=? n).\n Proof.\n intros n. induction n.\n - reflexivity.\n - simpl. rewrite<-IHn. reflexivity.\n Qed.\n\n Theorem zero_nbeq_S : forall n:nat,\n 0 =? (S n) = false.\n Proof.\n intros n. reflexivity.\n Qed.\n \n Theorem andb_false_r : forall b : bool,\n andb b false = false.\n Proof.\n intros b. destruct b.\n - reflexivity.\n - reflexivity.\n Qed.\n\n Theorem plus_ble_compat_l : forall n m p : nat,\n n <=? m = true -> (p + n) <=? (p + m) = true.\n Proof.\n intros n m p. intros H. induction p.\n - simpl. rewrite->H. reflexivity.\n - simpl. rewrite->IHp. reflexivity.\n Qed.\n\n Theorem S_nbeq_0 : forall n:nat,\n (S n) =? 0 = false.\n Proof.\n reflexivity.\n Qed.\n\n Theorem mult_1_l : forall n:nat, 1 * n = n.\n Proof.\n intros n. simpl. rewrite->plus_n_O. reflexivity.\n Qed.\n\n Theorem all3_spec : forall b c : bool,\n orb\n (andb b c)\n (orb (negb b)\n (negb c))\n = true.\n Proof.\n intros b c. destruct b. destruct c.\n - reflexivity.\n - reflexivity.\n - reflexivity.\n Qed.\n \n Theorem mult_plus_distr_r : forall n m p : nat,\n (n + m) * p = (n * p) + (m * p).\n Proof.\n intros n m p. \n induction p.\n {rewrite->mult_0_r. rewrite->mult_0_r. rewrite->mult_0_r. reflexivity. }\n {\n rewrite->mult_plus_distr_1. rewrite->mult_plus_distr_1. rewrite->mult_plus_distr_1.\n rewrite->plus_swap. rewrite->IHp.\n rewrite<-plus_assoc. rewrite<-plus_assoc. rewrite->plus_swap.\n reflexivity.\n }\n Qed.\n\n Theorem mult_assoc : forall n m p : nat,\n n * (m * p) = (n * m) * p.\n Proof.\n intros n m p.\n induction n.\n - reflexivity.\n - simpl. rewrite->IHn. rewrite<-mult_plus_distr_r. reflexivity.\n Qed. \n\n Theorem eqb_refl: forall n:nat,\n true = (n =? n).\n Proof.\n intros n. induction n.\n - reflexivity.\n - simpl. rewrite->IHn. reflexivity. \n Qed.\n\n Theorem plus_swap': forall n m p:nat,\n n + (m+p) = m+ (n+p) .\n Proof.\n intros n m p. \n rewrite->plus_assoc.\n replace (n+m) with (m+n). \n - rewrite<-plus_assoc. reflexivity.\n - rewrite->plus_comm. reflexivity. \n Qed.\n \n Theorem bin_to_nat_pres_incr: forall n:bin,\n bin_to_nat (incr n) = S (bin_to_nat n).\n Proof.\n intros n. induction n.\n - reflexivity.\n - reflexivity.\n - {simpl. \n rewrite->IHn. \n rewrite->plus_n_Sm.\n replace (bin_to_nat n + S (bin_to_nat n)) with (S (bin_to_nat n) + (bin_to_nat n)).\n - rewrite->plus_n_Sm. reflexivity.\n - rewrite->plus_comm. reflexivity. \n }\n Qed.\n \n Fixpoint nat_to_bin (n:nat):bin:=\n match n with \n |O => Z\n |S n => incr (nat_to_bin n)\n end.\n\n Lemma nat_to_bin_pres_incr: forall n:nat,\n incr (nat_to_bin n) = nat_to_bin (S n).\n Proof.\n intros n. induction n.\n - reflexivity.\n - reflexivity.\n Qed.\n\n Theorem nat_bin_nat: forall n,\n bin_to_nat (nat_to_bin n) =n .\n Proof.\n intros n. induction n.\n - reflexivity.\n - simpl. rewrite->bin_to_nat_pres_incr. rewrite->IHn. reflexivity.\n Qed.\n \n \n", "meta": {"author": "Err0rzz", "repo": "Softwarefoundation", "sha": "6338d7a4e2ab153309f51efc2738d3a76249a116", "save_path": "github-repos/coq/Err0rzz-Softwarefoundation", "path": "github-repos/coq/Err0rzz-Softwarefoundation/Softwarefoundation-6338d7a4e2ab153309f51efc2738d3a76249a116/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377302496858, "lm_q2_score": 0.8976952968970955, "lm_q1q2_score": 0.8604748123435597}} {"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\nModule NatList. \n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as here: *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n(** Here are two simple functions for extracting the first and\n second components of a pair. The definitions also illustrate how\n to do pattern matching on two-argument constructors. *)\n\nDefinition fst (p : natprod) : nat :=\n match p with\n | pair x y => x\n end.\n\nDefinition snd (p : natprod) : nat :=\n match p with\n | pair x y => y\n end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new pair notation can be used both in expressions and in\n pattern matches (indeed, we've actually seen this already in the\n [Basics] chapter, in the definition of the [minus] function --\n this works because the pair notation is also provided as part of\n the standard library): *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n match p with\n | (x,y) => x\n end.\n\nDefinition snd' (p : natprod) : nat :=\n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n match p with\n | (x,y) => (y,x)\n end.\n\n(** Let's try to prove a few simple facts about pairs.\n\n If we state things in a particular (and slightly peculiar) way, we\n can complete proofs with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** Notice that, unlike its behavior with [nat]s, [destruct]\n generates just one subgoal here. That's because [natprod]s can\n only be constructed in one way. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\nintros.\ndestruct p.\nsimpl.\nreflexivity.\nQed.\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\nintros. destruct p.\nsimpl. reflexivity. \nQed.\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n type of _lists_ of numbers like this: \"A list is either the empty\n list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n declarations, but in case you are interested, here is roughly\n what's going on. The [right associativity] annotation tells Coq\n how to parenthesize expressions involving several uses of [::] so\n that, for example, the next three declarations mean exactly the\n same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\n\n Notation \"x + y\" := (plus x y)\n (at level 50, left associativity).\n\n the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n you read them in a [.v] file. The inner brackets, around 3, indicate\n a list, but the outer brackets, which are invisible in the HTML\n rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n part should be displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head (with default) and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\").\n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, recommended (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist:=\n match l with\n | [] => []\n | O::xs => nonzeros xs\n | S(n)::xs => S(n)::(nonzeros xs)\n end.\n\n\nExample test_nonzeros:\n nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\n\nFixpoint oddmembers (l:natlist) : natlist:=\n match l with\n | [] => []\n | x::xs => match oddb x with\n | true => x::oddmembers xs\n | false => oddmembers xs\n end\n end.\n\nExample test_oddmembers:\n oddmembers [0;1;0;2;3;0;0] = [1;3].\n(* FILL IN HERE *)\nProof.\n reflexivity.\nQed.\n (* GRADE_THEOREM 0.5: NatList.test_oddmembers *)\n\nDefinition countoddmembers (l:natlist) : nat:= length (oddmembers l).\n \n\nExample test_countoddmembers1:\n countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed. \nExample test_countoddmembers2:\n countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed. \n\nExample test_countoddmembers3:\n countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist:=\n match l1 with\n | [] => match l2 with\n | [] => []\n | y::ys => l2\n end\n | x::xs => match l2 with\n | []=> l1\n | y::ys => x::y::alternate xs ys\n end\n end.\n \nExample test_alternate1:\n alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n(* FILL IN HERE *)\nProof. reflexivity. Qed.\n\nExample test_alternate2:\n alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\n\nExample test_alternate3:\n alternate [1;2;3] [4] = [1;4;2;3].\nProof. reflexivity. Qed.\n\nExample test_alternate4:\n alternate [] [20;30] = [20;30].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n can appear multiple times rather than just once. One possible\n implementation is to represent a bag of numbers as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, recommended (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat:=\n match s with\n | [] => 0\n | x::xs => match beq_nat x v with\n | true => 1 + count v xs\n | false => count v xs\n end\n end.\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n the elements of [a] and of [b]. (Mathematicians usually define\n [union] on multisets a little bit differently -- using max instead\n of sum -- which is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag:=app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity. Qed.\n(* GRADE_THEOREM 0.5: NatList.test_sum1 *)\n\nDefinition add (v:nat) (s:bag) : bag:= v::s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\n(* FILL IN HERE *)\nProof. reflexivity. Qed.\n\n(* GRADE_THEOREM 0.5: NatList.test_add1 *)\n(* GRADE_THEOREM 0.5: NatList.test_add2 *)\n\nDefinition member (v:nat) (s:bag) : bool:=\n match count v s with\n | O => false\n | S n => true\n end.\n \nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\n\n(* GRADE_THEOREM 0.5: NatList.test_member1 *)\n(* GRADE_THEOREM 0.5: NatList.test_member2 *)\n\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more [bag] functions for you to practice with. *)\n\n(** When [remove_one] is applied to a bag without the number to remove,\n it should return the same bag unchanged. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag:=\n match s with\n | [] => []\n | x::xs => match beq_nat x v with\n | true => xs\n | false => x:: remove_one v xs\n end\n end.\n\nExample test_remove_one1:\n count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one2:\n count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one3:\n count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_one4:\n count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag:=\n match s with\n | [] => []\n | x::xs => match beq_nat x v with\n | true => remove_all v xs\n | false => x:: remove_all v xs\n end\n end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n \nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. reflexivity. Qed.\nCompute member 2 [2;4;1].\nFixpoint subset (s1:bag) (s2:bag) : bool:=\n match s1 with\n | [] => true\n | x::[] => member x s2\n | x::xs => match member x s2 with\n | true => subset xs (remove_one x s2)\n | false => subset xs s2\n end \n end.\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (bag_theorem) *)\n(** Write down an interesting theorem [bag_theorem] about bags\n involving the functions [count] and [add], and prove it. Note\n that, since this problem is somewhat open-ended, it's possible\n that you may come up with a theorem which is true, but whose proof\n requires techniques you haven't learned yet. Feel free to ask for\n help if you get stuck! *)\n\n(*\nTheorem bag_theorem : ...\nProof.\n ...\nQed.\n*)\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ...because the [[]] is substituted into the\n \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n the match) in the definition of [app], allowing the match itself\n to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons n l' *)\n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n It is important to work through the details of each one, using Coq\n and thinking about what each step achieves. Otherwise it is more\n or less guaranteed that the exercises will make no sense when you\n get to them. 'Nuff said. *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n little less familiar than standard natural number induction, but\n the idea is equally simple. Each [Inductive] declaration defines\n a set of data values that can be built up using the declared\n constructors: a boolean can be either [true] or [false]; a number\n can be either [O] or [S] applied to another number; a list can be\n either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two arguments together establish\n the truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n intros.\n induction l1 as [| hd tl IHl1'].\n - simpl. reflexivity. \n - simpl. rewrite IHl1'.\n reflexivity.\nQed.\n (** Notice that, as when doing induction on natural numbers, the\n [as...] clause provided to the [induction] tactic gives a name to\n the induction hypothesis corresponding to the smaller list [l1']\n in the [cons] case. Once again, this Coq proof is not especially\n illuminating as a static written document -- it is easy to see\n what's going on if you are reading the proof in an interactive Coq\n session and you can see the current goal and context at each\n point, but this state is not visible in the written-down parts of\n the Coq proof. So a natural-language proof -- one written for\n human readers -- will need to include more explicit signposts; in\n particular, it will help the reader stay oriented if we remind\n them exactly what the induction hypothesis is in the second\n case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n (the induction hypothesis). We must show\n\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n By the definition of [++], this follows from\n\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n which is immediate from the induction hypothesis. [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n lists, suppose we use [app] to define a list-reversing function\n [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => rev t ++ [h]\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Properties of [rev] *)\n\n(** Now let's prove some theorems about our newly defined [rev].\n For something a bit more challenging than what we've seen, let's\n prove that reversing a list does not change its length. Our first\n attempt gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = [] *)\n reflexivity.\n - (* l = n :: l' *)\n (* This is the tricky case. Let's begin as usual\n by simplifying. *)\n simpl.\n (* Now we seem to be stuck: the goal is an equality\n involving [++], but we don't have any useful equations\n in either the immediate context or in the global\n environment! We can make a little progress by using\n the IH to rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n would have enabled us to make progress and prove it as a separate\n lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Note that, to make the lemma as general as possible, we\n quantify over _all_ [natlist]s, not just those that result from an\n application of [rev]. This should seem natural, because the truth\n of the goal clearly doesn't depend on the list having been\n reversed. Moreover, it is easier to prove the more general\n property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons *)\n simpl. rewrite -> app_length, plus_comm.\n simpl. rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n _Theorem_: For all lists [l1] and [l2],\n [length (l1 ++ l2) = length l1 + length l2].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n length ([] ++ l2) = length [] + length l2,\n\n which follows directly from the definitions of\n [length] and [++].\n\n - Next, suppose [l1 = n::l1'], with\n\n length (l1' ++ l2) = length l1' + length l2.\n\n We must show\n\n length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n This follows directly from the definitions of [length] and [++]\n together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n\n length (rev []) = length [],\n\n which follows directly from the definitions of [length]\n and [rev].\n\n - Next, suppose [l = n::l'], with\n\n length (rev l') = length l'.\n\n We must show\n\n length (rev (n :: l')) = length (n :: l').\n\n By the definition of [rev], this follows from\n\n length ((rev l') ++ [n]) = S (length l')\n\n which, by the previous lemma, is the same as\n\n length (rev l') + length [n] = S (length l').\n\n This follows directly from the induction hypothesis and the\n definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n After the first few, we might find it easier to follow proofs that\n give fewer details (which can easily work out in our own minds or\n on scratch paper if necessary) and just highlight the non-obvious\n steps. In this more compressed style, the above proof might look\n like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n for any [l] (this follows by a straightforward induction on [l]).\n The main property again follows by induction on [l], using the\n observation together with the induction hypothesis in the case\n where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for our\n present purposes. *)\n\n\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, e.g., using [rewrite]. But in order to refer to a\n theorem, we need to know its name! Indeed, it is often hard even\n to remember what theorems have been proven, much less what they\n are called.\n\n Coq's [Search] command is quite helpful with this. Typing\n [Search foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following line\n to see a list of theorems that we have proved about [rev]: *)\n\n(* Search rev. *)\n\n(** Keep [Search] in mind as you do the following exercises and\n throughout the rest of the book; it can save you a lot of time!\n\n If you are using ProofGeneral, you can run [Search] with [C-c\n C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n l ++ [] = l.\nProof.\n intros.\n induction l as [| hd tl IHl'].\n - reflexivity.\n - simpl. rewrite -> IHl'. simpl. \n reflexivity.\nQed.\n\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n intros. induction l1 as [| hd tl IHl'].\n - simpl. rewrite -> app_nil_r. reflexivity.\n - simpl. rewrite -> IHl'. rewrite -> app_assoc. reflexivity.\n Qed.\n\n\n Theorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros.\n induction l.\n - reflexivity.\n - simpl. rewrite rev_app_distr. rewrite IHl.\n reflexivity.\nQed.\n (** There is a short solution to the next one. If you find yourself\n getting tangled up, step back and try to look for a simpler\n way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\nintros.\ninduction l1.\n- rewrite app_assoc. reflexivity.\n-simpl. rewrite IHl1. reflexivity.\n Qed.\n (** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros.\n induction l1.\n - reflexivity.\n - simpl. destruct n.\n + rewrite IHl1. reflexivity.\n + simpl. rewrite IHl1. reflexivity.\nQed.\n (** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool:=\n match l1 with\n | [] => match l2 with\n | [] => true\n | x::xs => false\n end\n | x::xs =>match l2 with\n | [] => false\n | y::ys => match beq_nat x y with\n | true => andb true (beq_natlist xs ys) \n | false => false\n end\n end\n end.\n \n\nExample test_beq_natlist1 :\n (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\nExample test_beq_natlist2 :\n beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\nExample test_beq_natlist3 :\n beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\n intros.\n induction l as [| hd tl IHl'].\n - reflexivity.\n - simpl.\n rewrite <- beq_nat_refl.\n rewrite IHl'.\n reflexivity.\n Qed.\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** Here are a couple of little theorems to prove about your\n definitions about bags above. *)\n\n(** **** Exercise: 1 star (count_member_nonzero) *)\nTheorem count_member_nonzero : forall (s : bag),\n leb 1 (count 1 (1 :: s)) = true.\nProof.\n intros.\n simpl.\n reflexivity.\nQed.\n\n(** The following lemma about [leb] might help you in the next exercise. *)\n\nTheorem ble_n_Sn : forall n,\n leb n (S n) = true.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* 0 *)\n simpl. reflexivity.\n - (* S n' *)\n simpl. rewrite IHn'. reflexivity. Qed.\n\n(** **** Exercise: 3 stars, advanced (remove_decreases_count) *)\nTheorem remove_decreases_count: forall (s : bag),\n leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof. intros.\ninduction s.\n- reflexivity. \n- simpl. destruct n.\n + simpl. rewrite ble_n_Sn. reflexivity.\n + simpl. rewrite IHs. reflexivity.\nQed.\n\n (** **** Exercise: 3 stars, optional (bag_count_sum) *)\n(** Write down an interesting theorem [bag_count_sum] about bags\n involving the functions [count] and [sum], and prove it using\n Coq. (You may find that the difficulty of the proof depends on\n how you defined [count]!) *)\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective -- that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\n (There is a hard way and an easy way to do this.) *)\n\n(* FILL IN HERE *)\n(** [] *)\nTheorem rev_injective: forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\nProof.\n intros.\n rewrite <- rev_involutive.\n rewrite <- H.\n rewrite rev_involutive.\n reflexivity.\nQed.\n\n\n (* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n element of some list. If we give it type [nat -> natlist -> nat],\n then we'll have to choose some number to return when the list is\n too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with\n | true => a\n | false => nth_bad l' (pred n)\n end\n end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n can't tell whether that value actually appears on the input\n without further processing. A better alternative is to change the\n return type of [nth_bad] to include an error value as a possible\n outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption.\n\n(** We can then change the above definition of [nth_bad] to\n return [None] when the list is too short and [Some a] when the\n list has enough members and [a] appears at position [n]. We call\n this new function [nth_error] to indicate that it may result in an\n error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => match beq_nat n O with\n | true => Some a\n | false => nth_error l' (pred n)\n end\n end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n examples are elided. Click on a box if you want to see one.)\n\n This example is also an opportunity to introduce one more small\n feature of Coq's programming language: conditional\n expressions... *)\n\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => if beq_nat n O then Some a\n else nth_error' l' (pred n)\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually supports conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_error) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_error (l : natlist) : natoption:=\n match l with | [] => None | x::xs => Some(x) end.\nExample test_hd_error1 : hd_error [] = None.\nProof. reflexivity. Qed.\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_error l).\nProof.\nintros.\ndestruct l.\n- reflexivity.\n- reflexivity.\nQed.\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n Coq, here is a simple _partial map_ data type, analogous to the\n map or dictionary data structures found in most programming\n languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n | Id : nat -> id.\n\n(** Internally, an [id] is just a number. Introducing a separate type\n by wrapping each nat with the tag [Id] makes definitions more\n readable and gives us the flexibility to change representations\n later if we wish. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition beq_id (x1 x2 : id) :=\n match x1, x2 with\n | Id n1, Id n2 => beq_nat n1 n2\n end.\n\n(** **** Exercise: 1 star (beq_id_refl) *)\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\nintros.\ndestruct x.\nsimpl. \nrewrite <- beq_nat_refl.\nreflexivity.\nQed.\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n \nInductive partial_map : Type :=\n | empty : partial_map\n | record : id -> nat -> partial_map -> partial_map.\n\n(** This declaration can be read: \"There are two ways to construct a\n [partial_map]: either using the constructor [empty] to represent an\n empty partial map, or by applying the constructor [record] to\n a key, a value, and an existing [partial_map] to construct a\n [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n partial map (or adds a new entry if the given key is not already\n present). *)\n\nDefinition update (d : partial_map)\n (x : id) (value : nat)\n : partial_map :=\n record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n key. It returns [None] if the key was not found and [Some val] if\n the key was associated with [val]. If the same key is mapped to\n multiple values, [find] will return the first one it\n encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n match d with\n | empty => None\n | record y v d' => if beq_id x y\n then Some v\n else find x d'\n end.\n\n\n(** **** Exercise: 1 star (update_eq) *)\nTheorem update_eq :\n forall (d : partial_map) (x : id) (v: nat),\n find x (update d x v) = Some v.\nProof.\n intros.\n simpl.\n rewrite <- beq_id_refl.\n reflexivity.\n Qed.\n\n(** **** Exercise: 1 star (update_neq) *)\nTheorem update_neq :\n forall (d : partial_map) (x y : id) (o: nat),\n beq_id x y = false -> find x (update d y o) = find x d.\nProof.\n intros.\n simpl.\n rewrite H.\n reflexivity.\n Qed.\nEnd PartialMap.\n\n(** **** Exercise: 2 stars (baz_num_elts) *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n | Baz1 : baz -> baz\n | Baz2 : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have?\n (Explain your answer in words, preferrably English.) \nNone, you can't construct any, because there is no base case.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n", "meta": {"author": "gpfarina", "repo": "logical-foundations-exercises", "sha": "49335480409aeb7d0bfebcea4f888717fe097366", "save_path": "github-repos/coq/gpfarina-logical-foundations-exercises", "path": "github-repos/coq/gpfarina-logical-foundations-exercises/logical-foundations-exercises-49335480409aeb7d0bfebcea4f888717fe097366/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699844, "lm_q2_score": 0.9343951566034812, "lm_q1q2_score": 0.8603814073098343}} {"text": "Require Import Arith Omega.\n\nDefinition Even (n:nat) : Prop :=\n exists p:nat, n = 2*p. \n\nDefinition Odd (n:nat) : Prop :=\n exists p:nat, n = S (2*p).\n\n\n Lemma Even_not_Odd : forall n, Even n -> ~ Odd n. \n Proof.\n intros n [p Hp] [q Hq]; rewrite Hp in Hq. \n omega.\n Qed.\n\n(** Specification of a boolean test for even-ness \n*)\n\nInductive even_spec (n:nat) : bool -> Prop :=\n| even_true : forall (Heven : Even n), even_spec n true \n| even_false : forall (Hodd : Odd n), even_spec n false.\n\nDefinition even_test_ok (f : nat -> bool) :=\n forall n:nat, even_spec n (f n).\n\n\n\nFixpoint even_bool (n:nat) :=\n match n with\n | 0 => true\n | 1 => false\n | S (S p)=> even_bool p\nend.\n\n(** For proving even_bool's correctness, we shall use an induction principle\n adaptated to its control structure *)\n\n\nLemma nat_double_rect : forall (P:nat->Type),\n P 0 -> P 1 -> (forall p, P p -> P (S (S p))) ->\n forall n:nat, P n.\nProof.\n intros P H0 H1 HS.\n assert (X : forall n, (P n * P (S n)%type)).\n - induction n as [| p IHp]; [auto | destruct IHp;auto].\n - intro n; now destruct (X n).\nQed.\n\n \nLemma even_spec_SS : forall n b, even_spec n b -> even_spec (S (S n)) b.\nProof.\n intros n p [[q Hq] | [q Hq]]; constructor;exists (S q);omega.\nQed.\n\nLemma even_bool_correct : even_test_ok even_bool. \nProof.\n intro n;induction n using nat_double_rect.\n constructor;exists 0;trivial.\n constructor;exists 0;trivial.\n cbn;apply even_spec_SS;assumption. \nQed.\n\n\n(** even_bool_correct can now be used with destruct tactic :\n\n\nCheck even_spec_ind.\n\neven_spec_ind\n : forall (n : nat) (P : bool -> Prop),\n (Even n -> P true) ->\n (Odd n -> P false) -> forall b : bool, even_spec n b -> P b\n\n\n*)\n\nLemma even_bool_false (f: nat->bool) (H: even_test_ok f):\n forall n, Odd n <-> f n = false.\nProof. \n intros n ;destruct (H n).\n- split;try discriminate;intro;destruct (Even_not_Odd n);auto.\n- tauto. \nQed.\n\n\n\n\n\n\n\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch9_function_specification/SRC/even_odd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263737, "lm_q2_score": 0.908617906212312, "lm_q1q2_score": 0.8600946899803414}} {"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Coq.omega.Omega.\nRequire Import Coq.omega.Omega.\nRequire Export Logic.\n\nInductive ev : nat->Prop :=\n | ev_0 : ev 0\n | ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\nTheorem ev_4: ev 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0.\n Qed.\n\nTheorem ev_4': ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\nTheorem ev_plus4: forall n, ev n -> ev (4+n).\nProof.\n intros n. simpl. intros Hn.\n apply ev_SS. apply ev_SS. apply Hn.\n Qed.\n\n(* Exercise ev_double *)\nTheorem ev_double: forall n,\n ev (double n).\nProof.\n intros n. induction n as [| n' IHn'].\n - simpl. apply ev_0.\n - simpl. apply ev_SS. apply IHn'.\n Qed.\n\nTheorem ev_minus2: forall n,\n ev n -> ev (pred (pred n)).\nProof.\n intros n E.\n inversion E as [| n' E'].\n - simpl. apply ev_0.\n - simpl. apply E'.\n Qed.\n\nTheorem evSS_ev: forall n,\n ev (S (S n)) -> ev n.\nProof.\n intros n E.\n inversion E.\n apply H0.\n Qed.\n\nTheorem one_not_even: ~ev 1.\nProof.\n intros H. inversion H. Qed.\n\n(* Exercise inversion_practice *)\nTheorem SSSSev__even: forall n,\n ev (S (S (S (S n)))) -> ev n.\nProof.\n intros n H. inversion H.\n inversion H1.\n apply H3.\n Qed.\n\nTheorem even5_nonsense: \n ev 5 -> 2 + 2 = 9.\nProof.\n intros H. inversion H.\n inversion H1. inversion H3.\n Qed.\n\nLemma ev_even: forall n,\n ev n -> exists k, n = double k.\nProof.\n intros n E.\n induction E as [| n' E' IH].\n - exists 0. reflexivity.\n - destruct IH as [k' HK'].\n rewrite HK'. exists (S k'). reflexivity.\n Qed.\n\n\nTheorem ev_even_iff: forall n,\n ev n <-> exists k, n = double k.\nProof.\n intros n. split.\n - apply ev_even.\n - intros [k HK]. rewrite HK.\n apply ev_double.\n Qed.\n\n(* Exercise ev_sum *)\nTheorem ev_sum: forall n m,\n ev n -> ev m -> ev (n + m).\nProof.\n intros n m eqn eqm.\n induction eqn as [| n' eqn' IHN].\n - simpl. apply eqm.\n - simpl. apply ev_SS. apply IHN.\n Qed.\n\n(* Exercise ev_alternate *)\nInductive ev' : nat->Prop := \n | ev'_0 : ev' 0\n | ev'_2 : ev' 2\n | ev'_sum : forall n m,\n ev' n -> ev' m -> ev' (n+m).\n\nLemma add_two: forall n,\n n + 2 = S (S n).\nProof. intros n. induction n as [| n' IHn'].\n - reflexivity.\n - simpl. rewrite IHn'. reflexivity.\n Qed.\n\nTheorem ev'_ev : forall n,\n ev' n <-> ev n.\nProof.\n intros n. split.\n - intros H. \n induction H as [| |n' m' IHN'].\n + apply ev_0.\n + apply ev_SS. apply ev_0.\n + apply ev_sum.\n ++ apply IHIHN'.\n ++ apply IHev'1.\n - intros H. \n induction H as [| n' IHN].\n + apply ev'_0.\n + rewrite <- add_two.\n apply ev'_sum.\n apply IHIHN.\n apply ev'_2.\n Qed.\n\n(* Exercise ev_ev__ev *)\nTheorem ev_ev__ev: forall n m,\n ev (n+m) -> ev n -> ev m.\nProof.\n intros n m eqnm eqn.\n induction eqn as [| n' IHN].\n - simpl in eqnm. apply eqnm.\n - simpl in eqnm. inversion eqnm.\n apply IHIHN in H0.\n apply H0.\n Qed.\n\nLemma double_distr: forall n m,\n double (n+m) = double n + double m.\nProof.\n intros n m.\n induction n as [|n' IHn'].\n - simpl. reflexivity.\n - simpl. rewrite -> IHn'.\n reflexivity.\n Qed.\n\nTheorem plus_cancel: forall a b c,\n a + (b + c) = a + b + c.\nProof.\n intros a b c.\n rewrite -> plus_assoc.\n reflexivity.\n Qed.\n\n(* Exercise ev_plus_plus *)\nTheorem ev_plus_plus: forall n m p,\n ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n intros n m p eqnm eqnp.\n assert(H1:ev (n+m+(n+p))).\n { apply ev_sum with (n:=n+m)(m:=n+p). \n - apply eqnm. - apply eqnp. }\n assert(H2:n+m+(n+p)=n+m+n+p).\n { apply plus_cancel with (a:=n+m)(b:=n)(c:=p). }\n rewrite H2 in H1.\n assert(H3:n+m+n+p=n+n+m+p).\n { \n omega. }\n rewrite H3 in H1.\n apply ev_ev__ev with (n:=n+n)(m:=m+p).\n - rewrite <- (plus_assoc (n+n) m p) in H1.\n apply H1.\n - apply ev_even_iff.\n exists n. rewrite -> double_plus.\n reflexivity.\n Qed.\n \n\nModule Playground.\n\nInductive le : nat->nat->Prop := \n | le_n : forall n, le n n\n | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\nTheorem test_le1:\n 3 <= 3.\nProof.\n apply le_n. Qed.\n\nTheorem test_le2:\n 3 <= 6.\nProof.\n apply le_S. apply le_S. apply le_S. apply le_n.\n Qed.\n\nTheorem test_le3:\n (2 <= 1) -> 2 + 2 = 5.\nProof.\n intros H. inversion H. inversion H2.\n Qed.\n\nEnd Playground.\n\nDefinition lt(n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\nInductive square_of : nat->nat->Prop :=\n | sq : forall n:nat, square_of n (n*n).\n\nInductive next_nat : nat->nat->Prop :=\n | nn : forall n:nat, next_nat n (S n).\n\nInductive next_even : nat->nat->Prop :=\n | ne_1 : forall n, ev (S n) -> next_even n (S n)\n | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).\n\n\n(* Exercise le_exercise *)\nLemma le_trans: forall m n o,\n m<=n -> n<=o -> m<=o.\nProof.\n intros m n o lemn leno.\n induction leno as [| n' o' H].\n - apply lemn.\n - apply le_S. apply H.\n Qed.\n\nTheorem O_le_n : forall n,\n 0 <= n.\nProof.\n intros n. induction n as [| n' H].\n - apply le_n.\n - apply le_S in H. apply H.\n Qed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n n<=m -> S n <= S m.\nProof.\n intros n m eq. induction eq.\n - apply le_n.\n - apply le_S. apply IHeq.\n Qed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n S n <= S m -> n <= m.\nProof.\n intros n m eq. inversion eq.\n - apply le_n.\n - apply le_trans with (m:=n)(n:=(S n))(o:=m).\n + apply le_S. reflexivity.\n + apply H0.\n Qed.\n\nTheorem le_plus_l: forall a b,\n a <= a + b.\nProof.\n intros a b.\n induction a as [| a'].\n - simpl. apply O_le_n.\n - simpl. apply n_le_m__Sn_le_Sm.\n apply IHa'.\n Qed.\n\nTheorem plus_lt: forall n1 n2 m,\n n1 + n2 < m ->\n n1 < m /\\ n2 < m.\nProof.\n unfold lt.\n intros n1 n2 m eq1. split.\n - assert (n1 <= n1+n2).\n { apply le_plus_l with (a:=n1)(b:=n2). }\n apply n_le_m__Sn_le_Sm in H.\n apply le_trans with (m:=S n1)(n:=S (n1+n2))(o:=m).\n + apply H.\n + apply eq1.\n - assert (n2 <= n2+n1).\n { apply le_plus_l with (a:=n2)(b:=n1). }\n rewrite plus_comm in H.\n apply n_le_m__Sn_le_Sm in H.\n apply le_trans with (m:=S n2)(n:=S (n1+n2))(o:=m).\n + apply H.\n + apply eq1.\n Qed.\n\nTheorem lt_S: forall n m,\n n < m ->\n n < S m.\nProof.\n unfold lt. intros n m eq.\n apply le_S in eq. apply eq.\n Qed.\n\n\nTheorem leb_complete: forall n m,\n leb n m = true -> \n n <= m.\nProof.\n intros n m eq.\n generalize dependent m.\n induction n as [| n'].\n - intros n eq. apply O_le_n.\n - induction m as [| m'].\n + intros eq. simpl in eq. inversion eq.\n + intros eq. simpl in eq.\n apply IHn' in eq.\n apply n_le_m__Sn_le_Sm in eq.\n apply eq.\n Qed.\n\nTheorem leb_refl : forall n,\n leb n n = true.\nProof.\n induction n as [|n'].\n - simpl. reflexivity.\n - simpl. apply IHn'.\n Qed.\n\nTheorem n_leb_m__n_leb_Sm : forall n m,\n leb n m = true ->\n leb n (S m) = true.\nProof.\n intros n m eq.\n generalize dependent m.\n induction n as [|n'].\n - intros m eq. simpl. reflexivity.\n - intros m eq. simpl. induction m as [|m'].\n + simpl in eq. inversion eq.\n + simpl in eq. apply IHn' in eq.\n apply eq.\n Qed.\n\nTheorem leb_correct : forall n m,\n n <= m ->\n leb n m = true.\nProof.\n intros n m eq.\n generalize dependent n.\n induction m as [|m'].\n - intros n eq. inversion eq. simpl. reflexivity.\n - intros n eq. inversion eq.\n + simpl. apply leb_refl.\n + apply IHm' in H0. \n apply n_leb_m__n_leb_Sm.\n apply H0.\n Qed.\n\nTheorem leb_true_trans : forall n m o,\n leb n m = true ->\n leb m o = true ->\n leb n o = true.\nProof.\n intros n m o eqnm eqmoo.\n apply leb_complete in eqnm.\n apply leb_complete in eqmoo.\n assert(H:n<=o).\n { apply le_trans with (m:=n)(n:=m)(o:=o).\n apply eqnm. apply eqmoo. }\n apply leb_correct in H.\n apply H.\n Qed.\n\n(* Exercise leb_iff *)\nTheorem leb_iff : forall n m,\n leb n m = true <-> n <= m.\nProof.\n intros n m. split.\n - apply leb_complete.\n - intros eq. apply leb_correct.\n apply eq.\n Qed.\n\nModule R.\n\n(* Exercise R_provability *)\nInductive R : nat->nat->nat->Prop :=\n | c1: R 0 0 0 \n | c2: forall m n o, R m n o -> R (S m) n (S o)\n | c3: forall m n o, R m n o -> R m (S n) (S o)\n | c4: forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n | c5: forall m n o, R m n o -> R n m o.\n\nExample prov1: (R 1 1 2).\nProof.\n apply c2.\n apply c3.\n apply c1.\n Qed.\n\nExample prov2: (R 2 2 6).\nProof.\n Admitted.\n\n(* Exercise R_fact *)\nDefinition fR:nat->nat->nat :=\n fun a =>\n fun b =>\n a + b.\n\nTheorem R_equiv_fR: forall m n o,\n R m n o <-> fR m n = o.\nProof.\n intros m n o.\n split.\n - intros eqR. unfold fR.\n induction eqR.\n + reflexivity.\n + simpl. rewrite IHeqR. reflexivity.\n + rewrite <- IHeqR. rewrite <- plus_n_Sm.\n reflexivity.\n + simpl in IHeqR. inversion IHeqR.\n rewrite <- plus_n_Sm in H0.\n inversion H0.\n reflexivity.\n + rewrite -> plus_comm in IHeqR. \n apply IHeqR.\n - generalize dependent o.\n unfold fR.\n induction m as [|m IHm'].\n + induction n as [|n IHn'].\n * simpl in *. \n intros o eq. rewrite <- eq. apply c1.\n * intros o eq. simpl in *.\n rewrite <- eq.\n apply c3. apply IHn'. reflexivity.\n + induction n as [|n IHn'].\n * simpl in *. \n intros o eq.\n rewrite -> plus_comm in eq.\n simpl in *. rewrite <- eq.\n apply c2. apply IHm'.\n rewrite -> plus_comm. simpl.\n reflexivity.\n * intros o eq.\n simpl in eq. rewrite <- plus_n_Sm in eq.\n rewrite <- eq.\n apply c2. apply IHm'.\n rewrite <- plus_n_Sm.\n reflexivity.\n Qed.\n\n\nEnd R.\n\n(* Exercise subsequence *)\n\n\n\n(* Exercise R_provability2 *)\n\nInductive R:nat->list nat->Prop :=\n | c1: R 0 []\n | c2: forall n l, \n R n l ->\n R (S n) (n::l) \n | c3: forall n l,\n R (S n) l ->\n R n l.\n\nExample Rlist_prov1: R 2 [1;0].\nProof.\n apply c2. apply c2. apply c1.\n Qed.\n\nExample Rlist_prov2: R 1 [1;2;1;0].\nProof.\n apply c3. apply c2. apply c3. apply c3.\n apply c2. apply c2. apply c2. apply c1.\n Qed.\n\nExample Rlist_prov3: R 6 [3;2;1;0].\nProof.\n Admitted.\n\nInductive reg_exp{T:Type} : Type :=\n | EmptySet : reg_exp\n | EmptyStr : reg_exp\n | Char : T->reg_exp\n | App: reg_exp->reg_exp->reg_exp\n | Union: reg_exp->reg_exp->reg_exp\n | Star: reg_exp->reg_exp.\n\n Inductive exp_match {T} : list T -> reg_exp -> Prop :=\n| MEmpty : exp_match [] EmptyStr\n| MChar : forall x, exp_match [x] (Char x)\n| MApp : forall s1 re1 s2 re2,\n exp_match s1 re1 ->\n exp_match s2 re2 ->\n exp_match (s1 ++ s2) (App re1 re2)\n| MUnionL : forall s1 re1 re2,\n exp_match s1 re1 ->\n exp_match s1 (Union re1 re2)\n| MUnionR : forall re1 s2 re2,\n exp_match s2 re2 ->\n exp_match s2 (Union re1 re2)\n| MStar0 : forall re, exp_match [] (Star re)\n| MStarApp : forall s1 s2 re,\n exp_match s1 re ->\n exp_match s2 (Star re) ->\n exp_match (s1 ++ s2) (Star re).\n\n Notation \"s =~ re\" := (exp_match s re) (at level 80).\n\nExample reg_exp_ex1: [1] =~ Char 1.\nProof.\n apply MChar.\n Qed.\n\nExample reg_exp_ex2: [1;2] =~ App (Char 1) (Char 2).\nProof.\n apply (MApp [1] _ [2]).\n - apply MChar.\n - apply MChar.\n Qed.\n\nExample reg_exp_ex3: ~([1;2] =~ Char 1).\nProof.\n intros H. inversion H.\n Qed.\n\nFixpoint reg_exp_of_list{T}(l:list T) :=\n match l with \n | [] => EmptyStr\n | x::l' => App (Char x) (reg_exp_of_list l')\n end.\n\nExample reg_exp_ex4: [1;2;3] =~ reg_exp_of_list [1;2;3].\nProof.\n simpl. apply (MApp [1]).\n { apply MChar. }\n apply (MApp [2]).\n { apply MChar. }\n apply (MApp [3]).\n { apply MChar. }\n apply MEmpty.\n Qed.\n\nLemma MStar1:\n forall T s (re:@reg_exp T),\n s =~ re ->\n s =~ Star re.\nProof.\n intros T s re H.\n rewrite <- (app_nil_r _ s).\n apply (MStarApp s [] re).\n - apply H.\n - apply MStar0.\n Qed.\n\n(* Exercise exp_match_ex1 *)\nLemma empty_is_empty: forall T (s:list T),\n ~(s =~ EmptySet).\nProof.\n intros T s. unfold not. intros eq.\n inversion eq.\n Qed.\n\nLemma MUnion': forall T (s:list T)\n (re1 re2 : @reg_exp T),\n s =~ re1 \\/ s =~ re2 ->\n s =~ Union re1 re2.\nProof.\n intros T s re1 re2 [H | H].\n - apply MUnionL. apply H.\n - apply MUnionR. apply H.\n Qed.\n\nLemma MStar': forall T (ss:list (list T))\n (re:reg_exp),\n (forall s, In s ss -> s =~ re) ->\n fold app ss [] =~ Star re.\nProof.\n intros T ss re eq.\n induction ss as [|hh tt IHs'].\n - simpl. apply MStar0.\n - simpl. Admitted.\n\n(* Exercise reg_exp_of_list *)\nLemma reg_exp_of_list_spec: forall T (s1 s2:list T),\n s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof. \n intros T s1 s2. split.\n - intros eq. induction s2 as [|hh tt IHs'].\n + simpl in eq. inversion eq. reflexivity.\n + simpl in *. Admitted.\n\nFixpoint re_chars{T}(re:reg_exp) : list T :=\n match re with\n | EmptySet => []\n | EmptyStr => []\n | Char x => [x]\n | App re1 re2 => re_chars re1 ++ re_chars re2\n | Union re1 re2 => re_chars re1 ++ re_chars re2\n | Star re => re_chars re\n end.\n\nTheorem in_re_match: forall T (s:list T)\n (re:reg_exp)(x:T),\n s =~ re ->\n In x s ->\n In x (re_chars re).\nProof.\n intros T s re x Hmatch Hin.\n induction Hmatch\n as [\n |x'\n |s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n |s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n |re |s1 s2 re Hmatch1 IH1 Hmatch2 IH2 \n ].\n - simpl. apply Hin.\n - simpl. simpl in Hin. apply Hin.\n - simpl. rewrite in_app_iff in *.\n destruct Hin as [Hin | Hin].\n + left. apply (IH1 Hin).\n + right. apply (IH2 Hin).\n - simpl. rewrite in_app_iff.\n left. apply (IH Hin).\n - simpl. rewrite in_app_iff.\n right. apply (IH Hin).\n - simpl. inversion Hin.\n - simpl. apply in_app_iff in Hin.\n destruct Hin as [Hin | Hin].\n + apply (IH1 Hin).\n + apply (IH2 Hin).\n Qed.\n\n(* Exercise re_not_empty *)\n\n\nLemma star_app: forall T (s1 s2 : list T)\n (re:@reg_exp T),\n s1 =~ Star re ->\n s2 =~ Star re ->\n s1 ++ s2 =~ Star re.\nProof.\n intros T s1 s2 re H1.\n remember (Star re) as re'.\n generalize dependent s2.\n induction H1.\n - inversion Heqre'.\n - inversion Heqre'.\n - inversion Heqre'.\n - inversion Heqre'.\n - inversion Heqre'.\n - inversion Heqre'.\n intros s2 H. simpl. apply H.\n - inversion Heqre'.\n rewrite H0 in *.\n intros ss2 H1.\n rewrite <- app_assoc. \n apply MStarApp.\n + apply H1_.\n + apply ((IHexp_match2 Heqre') ss2).\n apply H1.\n Qed.\n\n(* Exercise exp_match_ex2 *)\n\n(* Exercise pumping *)\n\nTheorem filter_not_empty_In: forall n l,\n filter (beq_nat n) l <> [] ->\n In n l.\nProof.\n intros n l. induction l as [|m l' IHl'].\n - simpl. intros H. apply H. reflexivity.\n - simpl. destruct (beq_nat n m) eqn:H.\n + intros _.\n rewrite beq_nat_true_iff in H.\n left. symmetry. apply H.\n + intros H'. right. apply IHl'. apply H'.\n Qed.\n\nModule FirstTry.\n\nInductive reflect: Prop->bool->Prop :=\n | ReflectT: forall(P:Prop), P->reflect P true\n | ReflectF: forall(P:Prop), ~P->reflect P false.\n\nEnd FirstTry.\n\nInductive reflect(P:Prop): bool->Prop :=\n | ReflectT: P->reflect P true\n | ReflectF: ~P->reflect P false.\n\nTheorem iff_reflect: forall P b,\n (P <-> b=true) ->\n reflect P b.\nProof.\n intros P b eq. destruct b.\n - apply ReflectT. apply eq. reflexivity.\n - apply ReflectF. unfold not. intros HP.\n apply eq in HP. inversion HP.\n Qed.\n\n(* Exercise reflect_iff *)\nTheorem reflect_iff: forall P b,\n reflect P b -> (P <-> b = true).\nProof.\n intros P b eq.\n destruct b.\n - split.\n + intros HP. reflexivity.\n + intros _. inversion eq. apply H.\n - split.\n + intros HP. inversion eq. apply H in HP.\n inversion HP.\n + intros HFalse. inversion HFalse.\n Qed.\n\nLemma beq_natP: forall n m,\n reflect (n=m) (beq_nat n m).\nProof.\n intros n m. apply iff_reflect.\n rewrite beq_nat_true_iff.\n reflexivity.\n Qed.\n\nTheorem filter_not_empty_In': forall n l,\n filter (beq_nat n) l <> [] ->\n In n l.\nProof.\n intros n l. induction l as [|m l' IHl'].\n - simpl. intros H. apply H. reflexivity.\n - simpl. destruct (beq_natP n m) as [H | H].\n + intros _. rewrite H. left. reflexivity.\n + intros H'. right. apply IHl'. apply H'.\n Qed.\n\n(* Exercise beq_natP_practice *)\nFixpoint count n l :=\n match l with\n | [] => 0\n | m::l' =>\n (if beq_nat n m then 1 else 0) + count n l'\n end.\n\nTheorem beq_natP_practice' : forall n l,\n count n l = 0 ->\n ~(In n l).\nProof. unfold not.\n intros n l eq.\n induction l as [|hh tt IHl'].\n - simpl. intros F. apply F.\n - simpl. intros [H|H].\n + rewrite H in *. apply IHl'.\n simpl in *.\n Search beq_nat.\n rewrite Induction.beq_nat_refl in eq.\n inversion eq.\n simpl in eq.\n rewrite Induction.beq_nat_refl in eq.\n inversion eq.\n + apply IHl'.\n simpl in *.\n destruct (beq_nat n hh).\n * inversion eq.\n * simpl in eq. apply eq.\n * apply H.\n Qed.\n\nTheorem beq_natP_practice : forall n l,\n count n l = 0 ->\n ~(In n l).\nProof.\n unfold not. intros n l. induction l as [|m l' IHl'].\n - simpl. intros _ F. apply F.\n - simpl in *. destruct (beq_natP n m) as [H|H].\n + intros eq [H1|H1].\n * inversion eq.\n * inversion eq.\n + simpl in *. intros eq [H1|H1].\n * rewrite H1 in H. apply H. reflexivity.\n * apply IHl' in eq. \n ** apply eq.\n ** apply H1.\n Qed.\n\n(* Exercise nostutter *)\n\n(* Exercise filter_challenge *)\n\n(* Exercise filter_challenge2 *)\n\n(* Exercise palindromes *)\n\n(* Exercise palindrome_converse *)\n\n(* Exercise NoDup *)\n\n(* Exercise pigeonhole principle *)", "meta": {"author": "rpgzysb", "repo": "SoftwareFoundation", "sha": "4f987efcec24d880908edcb4f1c1cd3926c60291", "save_path": "github-repos/coq/rpgzysb-SoftwareFoundation", "path": "github-repos/coq/rpgzysb-SoftwareFoundation/SoftwareFoundation-4f987efcec24d880908edcb4f1c1cd3926c60291/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068041, "lm_q2_score": 0.9046505293168445, "lm_q1q2_score": 0.8597897908847232}} {"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export MoreCoq.\n\n(** In previous chapters, we have seen many examples of factual\n claims (_propositions_) and ways of presenting evidence of their\n truth (_proofs_). In particular, we have worked extensively with\n _equality propositions_ of the form [e1 = e2], with\n implications ([P -> Q]), and with quantified propositions \n ([forall x, P]). \n\n This chapter will take us on a first tour of the\n propositional (logical) side of Coq.\n In particular, we will expand our repertoire of primitive\n propositions to include _user-defined_ propositions, not just\n equality propositions (which are more-or-less \"built in\" to Coq). \n*)\n\n\n(* ##################################################### *)\n(** * Inductively Defined Propositions *)\n\n(** As a running example, let's\n define a simple property of natural numbers -- we'll call it\n \"[beautiful].\" *)\n\n(** Informally, a number is [beautiful] if it is [0], [3], [5], or the\n sum of two [beautiful] numbers. \n\n More pedantically, we can define [beautiful] numbers by giving four\n rules:\n\n - Rule [b_0]: The number [0] is [beautiful].\n - Rule [b_3]: The number [3] is [beautiful]. \n - Rule [b_5]: The number [5] is [beautiful]. \n - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is\n their sum. *)\n\n(** We will see many definitions like this one during the rest\n of the course, and for purposes of informal discussions, it is\n helpful to have a lightweight notation that makes them easy to\n read and write. _Inference rules_ are one such notation: *)\n(**\n ----------- (b_0)\n beautiful 0\n \n ------------ (b_3)\n beautiful 3\n\n ------------ (b_5)\n beautiful 5 \n\n beautiful n beautiful m\n --------------------------- (b_sum)\n beautiful (n+m) \n*)\n\n(** Each of the textual rules above is reformatted here as an\n inference rule; the intended reading is that, if the _premises_\n above the line all hold, then the _conclusion_ below the line\n follows. For example, the rule [b_sum] says that, if [n] and [m]\n are both [beautiful] numbers, then it follows that [n+m] is\n [beautiful] too. If a rule has no premises above the line, then\n its conclusion hold unconditionally.\n\n These rules _define_ the property [beautiful]. That is, if we\n want to convince someone that some particular number is [beautiful],\n our argument must be based on these rules. For a simple example,\n suppose we claim that the number [5] is [beautiful]. To support\n this claim, we just need to point out that rule [b_5] says so.\n Or, if we want to claim that [8] is [beautiful], we can support our\n claim by first observing that [3] and [5] are both [beautiful] (by\n rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n is therefore [beautiful] by rule [b_sum]. This argument can be\n expressed graphically with the following _proof tree_: *)\n(**\n ----------- (b_3) ----------- (b_5)\n beautiful 3 beautiful 5\n ------------------------------- (b_sum)\n beautiful 8 \n Of course, there are other ways of using these rules to argue that\n [8] is [beautiful], for instance:\n ----------- (b_5) ----------- (b_3)\n beautiful 5 beautiful 3\n ------------------------------- (b_sum)\n beautiful 8 \n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty) *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* Infinitely many*)\n(** [] *)\n\n(** In Coq, we can express the definition of [beautiful] as\n follows: *)\n\nInductive beautiful : nat -> Prop :=\n b_0 : beautiful 0\n| b_3 : beautiful 3\n| b_5 : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n\n(** The first line declares that [beautiful] is a proposition -- or,\n more formally, a family of propositions \"indexed by\" natural\n numbers. (That is, for each number [n], the claim that \"[n] is\n [beautiful]\" is a proposition.) Such a family of propositions is\n often called a _property_ of numbers. Each of the remaining lines\n embodies one of the rules for [beautiful] numbers.\n\n The rules introduced this way have the same status as proven \n theorems; that is, they are true axiomatically. \n So we can use Coq's [apply] tactic with the rule names to prove \n that particular numbers are [beautiful]. *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n (* This simply follows from the rule [b_3]. *)\n apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n (* First we use the rule [b_sum], telling Coq how to\n instantiate [n] and [m]. *)\n apply b_sum with (n:=3) (m:=5).\n (* To solve the subgoals generated by [b_sum], we must provide\n evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n have rules for both. *)\n apply b_3.\n apply b_5.\nQed.\n\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n intros n B.\n apply b_sum with (n:=8) (m:=n).\n apply eight_is_beautiful.\n apply B.\nQed.\n \n(** **** Exercise: 2 stars (b_timesm) *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n intros.\n induction m as [|m']. simpl. apply b_0.\n simpl. apply b_sum with (n := n) (m := m' * n).\n apply H. apply IHm'.\n Qed.\n\n(* ####################################################### *)\n(** ** Induction Over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n declaration tells Coq not only that the constructors [b_0], [b_3],\n [b_5] and [b_sum] are ways to build evidence, but also that these\n two constructors are the _only_ ways to build evidence that\n numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n [beautiful n], then we know that [E] must have one of four shapes:\n\n - [E] is [b_0] (and [n] is [O]),\n - [E] is [b_3] (and [n] is [3]), \n - [E] is [b_5] (and [n] is [5]), or \n - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n evidence that [n1] is beautiful and [E2] is evidence that [n2]\n is beautiful). *)\n \n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n n] to see how it was constructed, using the tactics we already\n know. In particular, we can use the [induction] tactic that we\n have already seen for reasoning about inductively defined _data_\n to reason about inductively defined _evidence_.\n\n To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree) *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n notation.\n-----------\ngorgeous 0\n\ngorgeous n\n---------------\ngorgeous(3 + n)\n\n\ngorgeous n\n----------------\ngorgeous(5 + n)\n\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13) *)\nTheorem gorgeous_plus13: forall n, \n gorgeous n -> gorgeous (13+n).\nProof.\n intros.\n apply g_plus5 with (n := 8 + n).\n apply g_plus5 with (n := 3 + n).\n apply g_plus3 with (n := n).\n apply H.\n Qed.\n\n(** It seems intuitively obvious that, although [gorgeous] and\n [beautiful] are presented using slightly different rules, they are\n actually the same property in the sense that they are true of the\n same numbers. Indeed, we can prove this. *)\n\nTheorem gorgeous__beautiful : forall n, \n gorgeous n -> beautiful n.\nProof.\n intros n H.\n induction H as [|n'|n'].\n Case \"g_0\".\n apply b_0.\n Case \"g_plus3\". \n apply b_sum. apply b_3.\n apply IHgorgeous.\n Case \"g_plus5\".\n apply b_sum. apply b_5. apply IHgorgeous. \nQed.\n\n(** Notice that the argument proceeds by induction on the _evidence_ [H]! *) \n\n(** Let's see what happens if we try to prove this by induction on [n]\n instead of induction on the evidence [H]. *)\n\nTheorem gorgeous__beautiful_FAILED : forall n, \n gorgeous n -> beautiful n.\nProof.\n intros. induction n as [| n'].\n Case \"n = 0\". apply b_0.\n Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n useful induction hypothesis. Knowing how the property we are\n interested in behaves on the predecessor of [n] doesn't help us\n prove that it holds for [n]. Instead, we would like to be able to\n have induction hypotheses that mention other numbers, such as [n -\n 3] and [n - 5]. This is given precisely by the shape of the\n constructors for [gorgeous]. *)\n\n\n\n\n(** **** Exercise: 2 stars (gorgeous_sum) *)\nTheorem gorgeous_sum : forall n m,\n gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n intros.\n induction H.\n simpl. apply H0.\n apply g_plus3 with (n := n+m). apply IHgorgeous.\n apply g_plus5 with (n := n+m). apply IHgorgeous.\n Qed.\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n intros.\n induction H.\n apply g_0.\n apply g_plus3 with (n := 0). apply g_0.\n apply g_plus5 with (n := 0). apply g_0.\n apply gorgeous_sum. apply IHbeautiful1. apply IHbeautiful2.\n Qed.\n\n(** **** Exercise: 3 stars, optional (g_times2) *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y) = z + x + y.\nProof.\n intros. \n rewrite -> plus_swap. apply plus_assoc. Qed.\n\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n intros n H. simpl. \n induction H.\n simpl. apply g_0.\n apply g_plus3 with (n := n + (3 + n + 0)).\n rewrite -> helper_g_times2. apply g_plus3 with (n := n + n + 0).\n rewrite <- plus_assoc. apply IHgorgeous.\n apply g_plus5 with (n := n + (5 + n + 0)).\n rewrite -> helper_g_times2. apply g_plus5 with (n := n + n + 0).\n rewrite <- plus_assoc. apply IHgorgeous.\n Qed.\n\n(* ####################################################### *)\n(** ** From Boolean Functions to Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n number for evenness, yielding [true] if so. We can use this\n function to define the _proposition_ that some number [n] is\n even: *)\n\nDefinition even (n:nat) : Prop := \n evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n returns [true] when applied to [n].\" \n\n Note that here we have given a name\n to a proposition using a [Definition], just as we have\n given names to expressions of other sorts. This isn't a fundamentally\n new kind of proposition; it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n directly. Instead of going via the [evenb] function (\"a number is\n even if a certain computation yields [true]\"), we can say what the\n concept of evenness means by giving two different ways of\n presenting _evidence_ that a number is even. *)\n\nInductive ev : nat -> Prop :=\n | ev_0 : ev O\n | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(** This definition says that there are two ways to give\n evidence that a number [m] is even. First, [0] is even, and\n [ev_0] is evidence for this. Second, if [m = S (S n)] for some\n [n] and we can give evidence [e] that [n] is even, then [m] is\n also even, and [ev_SS n e] is the evidence. *)\n\n\n(** **** Exercise: 1 star (double_even) *)\n\nTheorem double_even : forall n,\n ev (double n).\nProof.\n intros.\n induction n as [|n'].\n simpl. apply ev_0.\n simpl. apply ev_SS. apply IHn'.\n Qed.\n\n(** *** Discussion: Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n phrased in two different ways -- indirectly, via a boolean testing\n function [evenb], or directly, by inductively describing what\n constitutes evidence for evenness. These two ways of defining\n evenness are about equally easy to state and work with. Which we\n choose is basically a question of taste.\n\n However, for many other properties of interest, the direct\n inductive definition is preferable, since writing a testing\n function may be awkward or even impossible. \n\n One such property is [beautiful]. This is a perfectly sensible\n definition of a set of numbers, but we cannot translate its\n definition directly into a Coq Fixpoint (or into a recursive\n function in any other common programming language). We might be\n able to find a clever way of testing this property using a\n [Fixpoint] (indeed, it is not too hard to find one in this case),\n but in general this could require arbitrarily deep thinking. In\n fact, if the property we are interested in is uncomputable, then\n we cannot define it as a [Fixpoint] no matter how hard we try,\n because Coq requires that all [Fixpoint]s correspond to\n terminating computations.\n\n On the other hand, writing an inductive definition of what it\n means to give evidence for the property [beautiful] is\n straightforward. *)\n\n\n\n\n(** **** Exercise: 1 star (ev__even) *)\n(** Here is a proof that the inductive definition of evenness implies\n the computational one. *)\n\nTheorem ev__even : forall n,\n ev n -> even n.\nProof.\n intros n E. induction E as [| n' E'].\n Case \"E = ev_0\". \n unfold even. reflexivity.\n Case \"E = ev_SS n' E'\". \n unfold even. apply IHE'. \nQed.\n\n(** Could this proof also be carried out by induction on [n] instead\n of [E]? If not, why not? *)\n\n(* No, for the same reason we couldn't with gorgeous__beautiful, we need\n** an induction hypothesis where each inductive step is concerned with\n** n-2, not n-1 *)\n(** [] *)\n\n(** The induction principle for inductively defined propositions does\n not follow quite the same form as that of inductively defined\n sets. For now, you can take the intuitive view that induction on\n evidence [ev n] is similar to induction on [n], but restricts our\n attention to only those numbers for which evidence [ev n] could be\n generated. We'll look at the induction principle of [ev] in more\n depth below, to explain what's really going on. *)\n\n(** **** Exercise: 1 star (l_fails) *)\n(** The following proof attempt will not succeed.\n Theorem l : forall n,\n ev n.\n Proof.\n intros n. induction n.\n Case \"O\". simpl. apply ev_0.\n Case \"S\".\n ...\n Intuitively, we expect the proof to fail because not every\n number is even. However, what exactly causes the proof to fail?\n\n(* We have no rule in our inductive definition regarding ev (S n) *)\n*)\n\n\n(** [] *)\n\n(** **** Exercise: 2 stars (ev_sum) *)\n(** Here's another exercise requiring induction. *)\n\nTheorem ev_sum : forall n m,\n ev n -> ev m -> ev (n+m).\nProof. \n intros. induction H.\n simpl. apply H0. \n simpl. apply ev_SS. apply IHev.\n Qed.\n\n(* ####################################################### *)\n(** ** [Inversion] on Evidence *)\n\n(** Another situation where we want to analyze evidence for evenness\n is when proving that, if [n] is even, then [pred (pred n))] is\n too. In this case, we don't need to do an inductive proof. The\n right tactic turns out to be [inversion]. *)\n\nTheorem ev_minus2: forall n,\n ev n -> ev (pred (pred n)). \nProof.\n intros n E.\n inversion E as [| n' E'].\n Case \"E = ev_0\". simpl. apply ev_0. \n Case \"E = ev_SS n' E'\". simpl. apply E'. Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n) *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* You will get stuck with ev (pred n') *)\n(** [] *)\n\n\n(** Another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n ev (S (S n)) -> ev n.\nProof.\n intros n E. \n inversion E as [| n' E']. \n apply E'. Qed.\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n Until now, we've only used [inversion] on equality\n propositions, to utilize injectivity of constructors or to\n discriminate between different constructors. But we see here\n that [inversion] can also be applied to analyzing evidence\n for inductively defined propositions.\n\n (You might also expect that [destruct] would be a more suitable\n tactic to use here. Indeed, it is possible to use [destruct], but \n it often throws away useful information, and the [eqn:] qualifier\n doesn't help much in this case.) \n\n Here's how [inversion] works in general. Suppose the name\n [I] refers to an assumption [P] in the current context, where\n [P] has been defined by an [Inductive] declaration. Then,\n for each of the constructors of [P], [inversion I] generates\n a subgoal in which [I] has been replaced by the exact,\n specific conditions under which this constructor could have\n been used to prove [P]. Some of these subgoals will be\n self-contradictory; [inversion] throws these away. The ones\n that are left represent the cases that must be proved to\n establish the original goal.\n\n In this particular case, the [inversion] analyzed the construction\n [ev (S (S n))], determined that this could only have been\n constructed using [ev_SS], and generated a new subgoal with the\n arguments of that constructor as new hypotheses. (It also\n produced an auxiliary equality, which happens to be useless here.)\n We'll begin exploring this more general behavior of inversion in\n what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice) *)\nTheorem SSSSev__even : forall n,\n ev (S (S (S (S n)))) -> ev n.\nProof.\n intros.\n inversion H. inversion H1.\n apply H3. Qed.\n\n(** The [inversion] tactic can also be used to derive goals by showing\n the absurdity of a hypothesis. *)\n\nTheorem even5_nonsense : \n ev 5 -> 2 + 2 = 9.\nProof.\n intros.\n inversion H. inversion H1. inversion H3.\n Qed.\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev) *)\n(** Finding the appropriate thing to do induction on is a\n bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n ev (n+m) -> ev n -> ev m.\nProof.\n intros.\n induction H0. simpl in H. apply H.\n simpl in H. inversion H. apply IHev in H2.\n apply H2. Qed.\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus) *)\n(** Here's an exercise that just requires applying existing lemmas. No\n induction or even case analysis is needed, but some of the rewriting\n may be tedious. *)\n(*Theorem ev_sum : forall n m,\n ev n -> ev m -> ev (n+m).\n\nTheorem double_even : forall n,\n ev (double n).\n*)\nTheorem ev_plus_plus : forall n m p, \n ev (n+m) -> ev (n+p) -> ev (m+p).\nProof. \n intros. apply ev_ev__ev with (n := n+n) (m := m+p).\n replace (n+n + (m + p)) with ((n +m) + (n+p)).\n apply ev_sum. apply H. apply H0.\n rewrite -> plus_swap. rewrite -> plus_assoc. rewrite -> plus_assoc.\n rewrite -> plus_assoc. reflexivity.\n rewrite <- double_plus.\n apply double_even.\n Qed.\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 4 stars (palindromes) *)\n(** A palindrome is a sequence that reads the same backwards as\n forwards.\n\n - Define an inductive proposition [pal] on [list X] that\n captures what it means to be a palindrome. (Hint: You'll need\n three cases. Your definition should be based on the structure\n of the list; just having a single constructor\n c : forall l, l = rev l -> pal l\n may seem obvious, but will not work very well.)\n \n - Prove that \n forall l, pal (l ++ rev l).\n - Prove that \n forall l, pal l -> l = rev l.\n*)\n(*\nInductive ev : nat -> Prop :=\n | ev_0 : ev O\n | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n*)\n(*\nInductive pal : list nat -> Prop := \n |empty : pal nil\n |single : forall (x : nat), pal [x]\n |palCons : forall (x : nat) (l : list nat), pal l -> pal (x :: (l ++ [x])).\n*)\n\nInductive pal : forall (X : Type) (l : list X), Prop :=\n |empty : forall X, pal X nil\n |single : forall X (x : X), pal X [x]\n |palCons : forall X (x : X) (l : list X), pal X l -> \n pal X (x :: (snoc l x))\n.\n\n(** **** Exercise: 5 stars, optional (palindrome_converse) *)\n(** Using your definition of [pal] from the previous exercise, prove\n that\n forall l, l = rev l -> pal l.\n*)\n\nTheorem Pal_App_Rev : forall (X : Type) (l : list X), pal X (l ++ rev l).\nProof.\n intros.\n induction l.\n simpl. apply empty.\n simpl. Admitted.\n\nLemma Align : forall (X : Type) (x : X) (l l' : list X), \n x::l = rev l ++[x] -> x :: l' ++ [x] = x :: rev l' ++ [x].\nProof.\n induction l'.\n intros. simpl. reflexivity.\n intros. apply IHl' in H. Admitted.\n\nTheorem revPal : forall (X : Type) (l : list X), l = rev l -> pal X l.\nProof.\n intros.\n induction l. apply empty.\n simpl in H. rewrite -> SnocApp in H. Admitted.\n\nInductive natBy2 : nat -> Prop :=\n |natBy2_0 : natBy2 0\n |natBy2_1 : natBy2 1\n |natBy2_SS : forall n, natBy2 n -> natBy2 (S(S n)).\n\nTheorem palRev : forall (X : Type) (l : list X), pal X l -> l = rev l.\nProof.\n intros.\n \n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (subsequence) *)\n(** A list is a _subsequence_ of another list if all of the elements\n in the first list occur in the same order in the second list,\n possibly with some extra elements in between. For example,\n [1,2,3]\n is a subsequence of each of the lists\n [1,2,3]\n [1,1,1,2,2,3]\n [1,2,7,3]\n [5,6,1,9,9,2,7,3,8]\n but it is _not_ a subsequence of any of the lists\n [1,2]\n [1,3]\n [5,6,2,1,7,3,8]\n\n - Define an inductive proposition [subseq] on [list nat] that\n captures what it means to be a subsequence. (Hint: You'll need\n three cases.)\n\n - Prove that subsequence is reflexive, that is, any list is a\n subsequence of itself. \n\n - Prove that for any lists [l1], [l2], and [l3], if [l1] is a\n subsequence of [l2], then [l1] is also a subsequence of [l2 ++\n l3].\n\n - (Optional, harder) Prove that subsequence is transitive -- that\n is, if [l1] is a subsequence of [l2] and [l2] is a subsequence\n of [l3], then [l1] is a subsequence of [l3]. Hint: choose your\n induction carefully!\n*)\n\nInductive subseq : forall (l1 l2 : list nat), Prop := \n |subseqNil : forall (l2 : list nat), subseq [] l2\n |subseqEq : forall (x : nat) (l1 l2 : list nat), subseq l1 l2 ->\n subseq (x::l1) (x::l2)\n |subseqNE : forall (x : nat) (l1 l2 : list nat), subseq l1 l2 -> \n subseq l1 (x::l2).\n\nTheorem SubseqRefl : forall (l : list nat), subseq l l.\nProof.\n intros. induction l.\n apply subseqNil.\n apply subseqEq. apply IHl. Qed.\n\nTheorem SubseqExtra : forall (l1 l2 l3 : list nat), subseq l1 l2 ->\n subseq l1 (l2 ++ l3).\nProof. \n intros. induction H.\n apply subseqNil.\n simpl. apply subseqEq. apply IHsubseq.\n simpl. apply subseqNE. apply IHsubseq. \n Qed.\n\nTheorem SubseqTrans : forall (l1 l2 l3 : list nat), subseq l1 l2 -> subseq l2 l3 ->\n subseq l1 l3.\nProof.\n intros. generalize dependent l1.\n induction H0.\n { intros. destruct l1. apply subseqNil.\n inversion H. }\n { intros. \n \n\n induction H. intros. apply subseqNil.\n intros. Admitted.\n\n(** **** Exercise: 2 stars, optional (R_provability) *)\n(** Suppose we give Coq the following definition:\n Inductive R : nat -> list nat -> Prop :=\n | c1 : R 0 []\n | c2 : forall n l, R n l -> R (S n) (n :: l)\n | c3 : forall n l, R (S n) l -> R n l.\n Which of the following propositions are provable?\n\n - [R 2 [1,0]] yes\n - [R 1 [1,2,1,0]] yes\n - [R 6 [3,2,1,0]] yes\n*)\n \n(** [] *)\n\n\n(* $Date: 2013-07-01 18:48:47 -0400 (Mon, 01 Jul 2013) $ *)\n\n\n", "meta": {"author": "lexxx320", "repo": "PersonalProjects", "sha": "bc83fb250467b013d9db9fe535ff7bd314632d4c", "save_path": "github-repos/coq/lexxx320-PersonalProjects", "path": "github-repos/coq/lexxx320-PersonalProjects/PersonalProjects-bc83fb250467b013d9db9fe535ff7bd314632d4c/software_foundations/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.9161096153072138, "lm_q1q2_score": 0.8594244345836326}} {"text": "Inductive bin : Type :=\n | Z \n | B0 (n : bin)\n | B1 (n : bin).\n\nFixpoint incr (m : bin) : bin :=\n match m with \n | Z => B1 Z \n | B0 n => B1 n \n | B1 n => B0 (incr n)\n end. \n \nFixpoint bin_to_nat (m:bin) : nat :=\n match m with \n | Z => O \n | B0 n => 2 * bin_to_nat n \n | B1 n => 1 + 2 * bin_to_nat n \n end. \n\nFixpoint nat_to_bin (n:nat) : bin :=\n match n with \n | O => Z \n | S n' => incr (nat_to_bin n')\n end. \n \nLemma n_plus_0_eq_n : forall n : nat, \n n + 0 = n. \nProof. \n intros n. induction n as [| n' IHn'].\n - reflexivity.\n - simpl. rewrite -> IHn'. reflexivity.\n Qed. \n\nLemma plus_n_Sm : forall n m : nat, \n S (n + m) = n + (S m). \nProof. \n intros n. induction n as [| n' IHn']. \n - simpl. reflexivity. \n - induction m as [| m' IHm'].\n + simpl. rewrite -> IHn'. reflexivity. \n + simpl. rewrite -> IHn'. reflexivity.\n Qed.\n\nLemma btn_incr_b_eq_S_btn_b : forall b : bin, \n bin_to_nat (incr b) = S(bin_to_nat b).\nProof. \n intros b. induction b as [| b' | b'].\n - reflexivity.\n - reflexivity.\n - \n simpl. rewrite -> n_plus_0_eq_n. rewrite -> n_plus_0_eq_n. \n rewrite -> IHb'. \n rewrite -> plus_n_Sm. \n reflexivity.\n Qed.\n\nTheorem nat_bin_nat : forall n, \n bin_to_nat (nat_to_bin n) = n.\nProof.\n intros n. induction n as [| n' IHn'].\n - reflexivity.\n - simpl. rewrite -> btn_incr_b_eq_S_btn_b. rewrite -> IHn'. reflexivity.\n Qed.", "meta": {"author": "Kevin-TD", "repo": "coq_learning", "sha": "2c725a27ff6c930010e217f505923f9207b070d6", "save_path": "github-repos/coq/Kevin-TD-coq_learning", "path": "github-repos/coq/Kevin-TD-coq_learning/coq_learning-2c725a27ff6c930010e217f505923f9207b070d6/induction/exercises/nat_bin_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.912436159286392, "lm_q1q2_score": 0.8591993075563565}} {"text": "(*************)\n(* Induction *)\n(*************)\n\nRequire Import Nat.\n\n(*\n Let's prove that zero is a left identity\n for addition.\n*)\n\nTheorem zero_plus_n : forall n, 0 + n = n.\nProof.\n intro.\n simpl.\n reflexivity.\nQed.\n\n(*\n Great, that was easy! Now let's prove\n that zero is also a right identity.\n*)\n\nTheorem n_plus_zero : forall n, n + 0 = n.\nProof.\n intro.\n simpl. (* Uh oh, nothing happened! *)\nAbort.\n\n(* Recall the definition of addition. *)\n\nPrint add.\n\n(*\n From this, it's clear why 0 + n = n.\n But how do we prove n + 0 = n?\n We need induction.\n*)\n\nCheck nat_ind.\n\n(*\n Let's use that induction principle to\n prove that zero is a neutral element\n of addition.\n*)\n\nTheorem n_plus_zero : forall n, n + 0 = n.\nProof.\n intro.\n\n (*\n Instead of applying `nat_ind` directly,\n it is easier to use the `induction`\n tactic.\n *)\n induction n.\n\n (* Two subgoals are generated: *)\n - simpl.\n reflexivity.\n - simpl.\n rewrite IHn.\n reflexivity.\nQed.\n\nPrint n_plus_zero.\n\n(* Let's prove addition is associative. *)\n\nTheorem plus_assoc :\n forall n m p,\n n + (m + p) = (n + m) + p.\nProof.\n intros.\n induction n.\n - simpl.\n reflexivity.\n - simpl.\n rewrite IHn.\n reflexivity.\nQed.\n", "meta": {"author": "stepchowfun", "repo": "coq-intro", "sha": "d5989c557f57885cc46ade267c43a8443c6bed3b", "save_path": "github-repos/coq/stepchowfun-coq-intro", "path": "github-repos/coq/stepchowfun-coq-intro/coq-intro-d5989c557f57885cc46ade267c43a8443c6bed3b/coq/Lesson3_Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104933824753, "lm_q2_score": 0.888758801595206, "lm_q1q2_score": 0.8589058319476406}} {"text": "(** * Lists: Working with Structured Data *)\n\nAdd LoadPath \".\".\nRequire Export Induction.\n\nModule NatList. \n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as in this definition: *)\n\nInductive natprod : Type :=\n pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\n(** We can construct an element of [natprod] like this: *)\n\nCheck (pair 3 5).\n\n(** *** *)\n\n(** Here are two simple function definitions for extracting the\n first and second components of a pair. (The definitions also\n illustrate how to do pattern matching on two-argument\n constructors.) *)\n\nDefinition fst (p : natprod) : nat := \n match p with\n | pair x y => x\n end.\nDefinition snd (p : natprod) : nat := \n match p with\n | pair x y => y\n end.\n\nEval compute in (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** *** *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this notation is provided as part of the standard\n library): *)\n\nEval compute in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat := \n match p with\n | (x,y) => x\n end.\nDefinition snd' (p : natprod) : nat := \n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod := \n match p with\n | (x,y) => (y,x)\n end.\n\n(** *** *)\n\n(** Let's try and prove a few simple facts about pairs. If we\n state the lemmas in a particular (and slightly peculiar) way, we\n can prove them with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** Note that [reflexivity] is not enough if we state the lemma in a\n more natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** *** *)\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct].\n\n Notice that, unlike for [nat]s, [destruct] doesn't generate an\n extra subgoal here. That's because [natprod]s can only be\n constructed in one way. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p.\n destruct p as [n m].\n simpl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros p.\n rewrite <- snd_fst_is_swap.\n simpl. reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n describe the type of _lists_ of numbers like this: \"A list is\n either the empty list or else a pair of a number and another\n list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n\n(** *** *)\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following two declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n but in case you are interested, here is roughly what's going on.\n\n The [right associativity] annotation tells Coq how to parenthesize\n expressions involving several uses of [::] so that, for example,\n the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\nNotation \"x + y\" := (plus x y) \n (at level 50, left associativity).\n The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (By the way, it's worth noting in passing that expressions like \"[1\n + 2 :: [3]]\" can be a little confusing when you read them in a .v\n file. The inner brackets, around 3, indicate a list, but the outer\n brackets, which are invisible in the HTML rendering, are there to\n instruct the \"coqdoc\" tool that the bracketed part should be\n displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(** *** Repeat *)\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist := \n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(** *** Length *)\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat := \n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(** *** Append *)\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist := \n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y) \n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\"). \n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\n(** *** Head (with default) and Tail *)\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil \n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | nil => nil\n | 0 :: t => nonzeros t\n | n :: t => n :: nonzeros t\n end.\n\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof.\n simpl nonzeros. reflexivity.\nQed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | nil => nil\n | n :: t => if oddb n then n :: oddmembers t else oddmembers t\n end.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof.\n simpl. reflexivity.\nQed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n match l with\n | nil => 0\n | n :: t => if oddb n then 1 + countoddmembers t else countoddmembers t\n end.\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\nProof.\n simpl. reflexivity.\nQed.\n\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\nProof.\n simpl. reflexivity.\nQed.\n\nExample test_countoddmembers3: countoddmembers nil = 0.\nProof.\n simpl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l1, l2 with\n | nil, l => l\n | l, nil => l\n | h1 :: t1, h2 :: t2 => h1 :: h2 :: alternate t1 t2\n end. \n\n\nExample test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof.\n simpl. reflexivity.\nQed.\nExample test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].\nProof.\n simpl. reflexivity.\nQed.\nExample test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].\nProof.\n simpl. reflexivity.\nQed.\nExample test_alternate4: alternate [] [20;30] = [20;30].\nProof.\n simpl. reflexivity.\nQed. \n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n multiple times instead of just once. One reasonable\n implementation of bags is to represent a bag of numbers as a\n list. *)\n\nDefinition bag := natlist. \n\n(** **** Exercise: 3 stars (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat := \n match s with\n | nil => 0\n | x :: t => count v t + (if beq_nat x v then 1 else 0)\n end.\n\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof.\n simpl. reflexivity.\nQed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof.\n simpl. reflexivity.\nQed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof.\n simpl. reflexivity.\nQed.\n\nDefinition add (v:nat) (s:bag) : bag := v :: s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof.\n simpl. reflexivity.\nQed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof.\n simpl. reflexivity.\nQed.\n\nDefinition member (v:nat) (s:bag) : bool := ble_nat 1 (count v s).\n\nExample test_member1: member 1 [1;4;1] = true.\nProof.\n reflexivity.\nQed.\nExample test_member2: member 2 [1;4;1] = false.\nProof.\n reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag := \n match s with \n | nil => nil\n | x :: t => if beq_nat x v then t else x :: remove_one v t\n end. \n\nExample test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof.\n reflexivity.\nQed.\nExample test_remove_one2: count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof.\n reflexivity.\nQed.\nExample test_remove_one3: count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof.\n reflexivity.\nQed.\nExample test_remove_one4: count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof.\n reflexivity.\nQed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | x :: t => if beq_nat x v then remove_all v t else x :: remove_all v t\n end. \n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof.\n reflexivity.\nQed.\n\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof.\n reflexivity.\nQed.\n\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof.\n reflexivity.\nQed.\n\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof.\n simpl. reflexivity.\nQed.\n\n\nFixpoint subset (s1:bag) (s2:bag) : bool := \n match s1, s2 with\n | nil, _ => true\n | _, nil => false\n | x :: t, s2 => if member x s2 then subset t (remove_all x s2) else false\n end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof.\n simpl. reflexivity.\nQed.\n\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof.\n simpl. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars (bag_theorem) *)\n(** Write down an interesting theorem [bag_theorem] about bags involving\n the functions [count] and [add], and prove it. Note that, since this\n problem is somewhat open-ended, it's possible that you may come up\n with a theorem which is true, but whose proof requires techniques\n you haven't learned yet. Feel free to ask for help if you get\n stuck! *)\nTheorem bag_count_add :\n forall v n bag, count v bag = n -> count v (add v bag) = S n.\nProof.\n intros v n bag.\n simpl. intros H.\n rewrite H.\n assert (forall m, beq_nat m m = true) as HH. \n induction m.\n reflexivity.\n simpl. rewrite IHm. reflexivity.\n rewrite HH. apply plus_comm.\nQed.\n\nTheorem bag_count_add2 :\n forall v v' n bag, beq_nat v' v = false -> count v bag = n -> count v (add v' bag) = n.\nProof.\n intros v v' n bag.\n simpl. intros H0 H1.\n rewrite H1.\n rewrite H0.\n rewrite plus_0_r. reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match position\n in the definition of [app], allowing the match itself to be\n simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n l'\". \n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n It is very important to work through the details of each one,\n using Coq and thinking about what each step achieves. Otherwise\n it is more or less guaranteed that the exercises will make no\n sense... *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n perhaps a little less familiar than standard natural number\n induction, but the basic idea is equally simple. Each [Inductive]\n declaration defines a set of data values that can be built up from\n the declared constructors: a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to a number; a\n list can be either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two things together establish the\n truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist, \n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3). \nProof.\n intros l1 l2 l3. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons n l1'\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n static written document -- it is easy to see what's going on if\n you are reading the proof in an interactive Coq session and you\n can see the current goal and context at each point, but this state\n is not visible in the written-down parts of the Coq proof. So a\n natural-language proof -- one written for human readers -- will\n need to include more explicit signposts; in particular, it will\n help the reader stay oriented if we remind them exactly what the\n induction hypothesis is in the second case. *)\n\n(** *** Informal version *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3], \n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n (the induction hypothesis). We must show\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]] \n By the definition of [++], this follows from\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n which is immediate from the induction hypothesis. []\n*)\n\n(** *** Another example *)\n(**\n Here is a similar example to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist, \n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n\n(** *** Reversing a list *)\n(** For a slightly more involved example of an inductive proof\n over lists, suppose we define a \"cons on the right\" function\n [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist := \n match l with\n | nil => [v]\n | h :: t => h :: (snoc t v)\n end.\n\n(** ... and use it to define a list-reversing function [rev]\n like this: *)\n\nFixpoint rev (l:natlist) : natlist := \n match l with\n | nil => nil\n | h :: t => snoc (rev t) h\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** *** Proofs about reverse *)\n(** Now let's prove some more list theorems using our newly\n defined [snoc] and [rev]. For something a little more challenging\n than the inductive proofs we've seen so far, let's prove that\n reversing a list does not change its length. Our first attempt at\n this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = []\".\n reflexivity.\n Case \"l = n :: l'\".\n (* This is the tricky case. Let's begin as usual \n by simplifying. *)\n simpl. \n (* Now we seem to be stuck: the goal is an equality \n involving [snoc], but we don't have any equations \n in either the immediate context or the global \n environment that have anything to do with [snoc]! \n\n We can make a little progress by using the IH to \n rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation about [snoc] that would have\n enabled us to make progress and prove it as a separate lemma. \n*)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n length (snoc l n) = S (length l).\nProof.\n intros n l. induction l as [| n' l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n' l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed. \n\n(**\n Note that we make the lemma as _general_ as possible: in particular,\n we quantify over _all_ [natlist]s, not just those that result\n from an application of [rev]. This should seem natural, \n because the truth of the goal clearly doesn't depend on \n the list having been reversed. Moreover, it is much easier\n to prove the more general property. \n*)\n \n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons\".\n simpl. rewrite -> length_snoc. \n rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems: \n\n _Theorem_: For all numbers [n] and lists [l],\n [length (snoc l n) = S (length l)].\n \n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (snoc [] n) = S (length []),\n which follows directly from the definitions of\n [length] and [snoc].\n\n - Next, suppose [l = n'::l'], with\n length (snoc l' n) = S (length l').\n We must show\n length (snoc (n' :: l') n) = S (length (n' :: l')).\n By the definitions of [length] and [snoc], this\n follows from\n S (length (snoc l' n)) = S (S (length l')),\n]] \n which is immediate from the induction hypothesis. [] *)\n \n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n \n _Proof_: By induction on [l]. \n\n - First, suppose [l = []]. We must show\n length (rev []) = length [],\n which follows directly from the definitions of [length] \n and [rev].\n \n - Next, suppose [l = n::l'], with\n length (rev l') = length l'.\n We must show\n length (rev (n :: l')) = length (n :: l').\n By the definition of [rev], this follows from\n length (snoc (rev l') n) = S (length l')\n which, by the previous lemma, is the same as\n S (length (rev l')) = S (length l').\n This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n and pedantic. After the first few, we might find it easier to\n follow proofs that give fewer details (since we can easily work\n them out in our own minds or on scratch paper if necessary) and\n just highlight the non-obvious steps. In this more compressed\n style, the above proof might look more like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that\n length (snoc l n) = S (length l)\n for any [l]. This follows by a straightforward induction on [l].\n The main property now follows by another straightforward\n induction on [l], using the observation together with the\n induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and on how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for\n present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, using [rewrite], and later we will see other ways\n of reusing previous theorems. But in order to refer to a theorem,\n we need to know its name, and remembering the names of all the\n theorems we might ever want to use can become quite difficult! It\n is often hard even to remember what theorems have been proven,\n much less what they are named.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following to\n see a list of theorems that we have proved about [rev]: *)\n\n(* SearchAbout rev. *)\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the course; it can save you a lot of time! *)\n\n(** Also, if you are using ProofGeneral, you can run [SearchAbout]\n with [C-c C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist, \n l ++ [] = l. \nProof.\n (* FILL IN HERE *) Admitted.\n\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** There is a short solution to the next exercise. If you find\n yourself getting tangled up, step back and try to look for a\n simpler way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n snoc l n = l ++ [n].\nProof.\n (* FILL IN HERE *) Admitted.\n\n\nTheorem distr_rev : forall l1 l2 : natlist,\n rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n (* FILL IN HERE *) admit.\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\n (* FILL IN HERE *) Admitted.\nExample test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\n (* FILL IN HERE *) Admitted.\nExample test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.\n (* FILL IN HERE *) Admitted.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 2 stars (list_design) *)\n(** Design exercise: \n - Write down a non-trivial theorem [cons_snoc_app]\n involving [cons] ([::]), [snoc], and [app] ([++]). \n - Prove it. *) \n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n definitions about bags earlier in the file. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\n(** The following lemma about [ble_nat] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n ble_nat n (S n) = true.\nProof.\n intros n. induction n as [| n'].\n Case \"0\". \n simpl. reflexivity.\n Case \"S n'\".\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *) \n(** Write down an interesting theorem [bag_count_sum] about bags \n involving the functions [count] and [sum], and prove it.*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nThere is a hard way and an easy way to solve this exercise.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n\n(** One use of [natoption] is as a way of returning \"error\n codes\" from functions. For example, suppose we want to write a\n function that returns the [n]th element of some list. If we give\n it type [nat -> natlist -> nat], then we'll have to return some\n number when the list is too short! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with \n | true => a \n | false => index_bad (pred n) l' \n end\n end.\n\n(** *** *)\n(** On the other hand, if we give it type [nat -> natlist ->\n natoption], then we can return [None] when the list is too short\n and [Some a] when the list has enough members and [a] appears at\n position [n]. *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption. \n\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => match beq_nat n O with \n | true => Some a\n | false => index (pred n) l' \n end\n end.\n\nExample test_index1 : index 0 [4;5;6;7] = Some 4.\nProof. reflexivity. Qed.\nExample test_index2 : index 3 [4;5;6;7] = Some 7.\nProof. reflexivity. Qed.\nExample test_index3 : index 10 [4;5;6;7] = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n small feature of Coq's programming language: conditional\n expressions... *)\n\n(** *** *)\n\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => if beq_nat n O then Some a else index' (pred n) l'\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_opt (l : natlist) : natoption :=\n (* FILL IN HERE *) admit.\n\nExample test_hd_opt1 : hd_opt [] = None.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_opt l).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Dictionaries *)\n\n(** As a final illustration of how fundamental data structures\n can be defined in Coq, here is the declaration of a simple\n [dictionary] data type, using numbers for both the keys and the\n values stored under these keys. (That is, a dictionary represents\n a finite map from numbers to numbers.) *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n | empty : dictionary \n | record : nat -> nat -> dictionary -> dictionary. \n\n(** This declaration can be read: \"There are two ways to construct a\n [dictionary]: either using the constructor [empty] to represent an\n empty dictionary, or by applying the constructor [record] to\n a key, a value, and an existing [dictionary] to construct a\n [dictionary] with an additional key to value mapping.\" *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n (record key value d).\n\n(** Here is a function [find] that searches a [dictionary] for a\n given key. It evaluates evaluates to [None] if the key was not\n found and [Some val] if the key was mapped to [val] in the\n dictionary. If the same key is mapped to multiple values, [find]\n will return the first one it finds. *)\n\nFixpoint find (key : nat) (d : dictionary) : natoption := \n match d with \n | empty => None\n | record k v d' => if (beq_nat key k) \n then (Some v) \n else (find key d')\n end.\n\n\n\n(** **** Exercise: 1 star (dictionary_invariant1) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n (find k (insert k v d)) = Some v.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),\n beq_nat m n = false -> find m d = find m (insert n o d).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\nEnd Dictionary.\n\nEnd NatList.\n\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)\n\n", "meta": {"author": "jam231", "repo": "Software-Foundations", "sha": "c9a889edd379333153ffcf14fbdfba050b357000", "save_path": "github-repos/coq/jam231-Software-Foundations", "path": "github-repos/coq/jam231-Software-Foundations/Software-Foundations-c9a889edd379333153ffcf14fbdfba050b357000/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.9184802456988517, "lm_q1q2_score": 0.8582234984704125}} {"text": "\n\nInductive bool : Type :=\n| true : bool\n| false : bool.\n\nDefinition negb (b:bool) : bool :=\n match b with\n | true => false\n | false => true\n end.\n\nDefinition andb (b1:bool) (b2:bool) : bool :=\n match b1 with\n | true => b2\n | false => false\n end.\n\nDefinition orb (b1:bool) (b2:bool) : bool :=\n match b1 with\n | true => true\n | false => b2\n end.\n\n\n\nExample test_orb1: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb2: (orb false false) = false.\nProof. simpl. reflexivity. Qed.\nExample test_orb3: (orb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb4: (orb true true) = true.\nProof. simpl. reflexivity. Qed.\n\n\nInfix \"&&\" := andb.\nInfix \"||\" := orb.\n\nExample test_Orb5: false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n match b1 with\n | true => match b2 with\n | true => false\n | false => true\n end\n\n | false => match b2 with\n | true => true\n | false => true\n end\n end.\n\nExample test_nandb1: (nandb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb2: (nandb false false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb3: (nandb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb4: (nandb true true) = false.\nProof. simpl. reflexivity. Qed.\n\nCheck negb.\n\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n match b1 with\n | true => match b2 with\n | true => match b3 with\n | true => true\n | false => false\n end\n | false => false\n end\n | false => false\n \n end.\n\n\nExample test_andb31: (andb3 true true true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_andb32: (andb3 false true true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb33: (andb3 true false true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb34: (andb3 true true false) = false.\nProof. simpl. reflexivity. Qed.\n\nCheck test_andb34.\n\n\nModule Factorial.\n\n\nFixpoint factorial (n:nat) : nat :=\n match n with\n | O => 1\n | S i => (S i) * factorial ((S i) - 1) \nend.\n\nExample test_factorial1: (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. simpl. reflexivity. Qed.\n\nNotation \"x + y\" := (plus x y)\n (at level 50, left associativity)\n : nat_scope.\n\nCheck (0 + 3).\n\nEnd Factorial.\n\nModule blt_nat.\n\nFixpoint beq_nat (n m : nat) : bool :=\n match n with\n | O => match m with\n | O => true\n | S i' => false\n end\n | S n' => match m with\n | O => false\n | S m' => beq_nat n' m'\n end\n end.\n\nFixpoint leb (n m : nat) : bool :=\n match n with\n | O => true\n | S n' =>\n match m with\n | 0 => false\n | S m' => leb n' m'\n end\n end.\n\nDefinition blt_nat (n m : nat) : bool :=\n match beq_nat n m with\n | true => false\n | false => leb n m\nend.\n\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\nEnd blt_nat.\n\nTheorem plus_0_l : forall n : nat, 0 + n = n.\nProof.\n intros n. reflexivity. Qed.\n\nTheorem plus_1_l : forall n : nat, 1 + n = S n.\nProof.\n intros n. reflexivity. Qed.\n\nTheorem mult_0_l : forall n : nat, 0 * n = 0.\nProof.\n intros n. reflexivity. Qed.\n\n(* Theorem plus id example : forall (n m:nat), *)\n(* n = m → *)\n(* n + n = m + m. *)\n\nTheorem plus_id_example : forall n m : nat,\n n = m -> n + n = m + m.\nProof.\n intros n m.\n intros H.\n rewrite <- H.\n reflexivity.\nQed.\n \n\nTheorem plus_id_exercise : forall n m o : nat,\nn = m -> m = o -> n + m = m + o.\nProof.\n intros n m o.\n intros hnm hmo.\n rewrite hnm.\n rewrite <- hmo.\n reflexivity.\nQed.\n\n(* Theorem mult 0 plus : ∀ n m : nat, *)\n(* (0 + n) × m = n × m. *)\n(* Proof. *)\n(* intros n m. *)\n(* rewrite → plus O n. *)\n(* reflexivity. Qed. *)\n\n\nTheorem mult_0_plus : forall n m : nat,\n (0 + n) * m = n * m.\n Proof.\n intros n m.\n rewrite plus_O_n.\n reflexivity.\n Qed.\n\nTheorem mult_S_1 : forall n m : nat,\n m = S n ->\n m * (1 + n) = m * m.\nProof.\n intros n m.\n intros hmsn.\n rewrite plus_1_l.\n rewrite hmsn.\n reflexivity.\nQed.\n\n\n\n\nFixpoint beq_nat (n m : nat) : bool :=\n match n with\n | O => match m with\n | O => true\n | S i' => false\n end\n | S n' => match m with\n | O => false\n | S m' => beq_nat n' m'\n end\nend.\n\nTheorem beq_nat_refl : forall n : nat,\n true = beq_nat n n.\n Proof.\n intro n.\n induction n.\n reflexivity.\n simpl.\n rewrite <- IHn.\n reflexivity.\nQed.\n\n\nModule caseanyl.\n(* Theorem plus 1 neq 0 : ∀ n : nat, *)\n(* beq nat (n + 1) 0 = false. *)\n(* Proof. *)\n\nTheorem plus_1_neq_0 : forall n : nat,\n beq_nat (n + 1) 0 = false.\nProof.\n intros n.\n destruct n as [| n'].\n - reflexivity.\n - reflexivity.\n Qed.\n\n(* Theorem negb involutive : ∀ b : bool, *)\n(* negb (negb b) = b. *)\n(* Proof. *)\n\nTheorem negb_involutive : forall b : bool,\n negb (negb b) = b.\nProof.\n intros b. destruct b.\n - reflexivity.\n - reflexivity.\nQed.\n\n\nTheorem plus_1_neq_0' : forall n : nat,\n beq_nat (n + 1) 0 = false.\nProof.\n intros [|n'].\n - reflexivity.\n - reflexivity.\nQed.\n \n\n(* Attempt #1 *)\nTheorem andb_true_elim2 : forall b c : bool,\n andb b c = true -> c = true.\nProof.\n intros b c.\n intros hbct.\n destruct b as [|].\n - destruct c as [|].\n + reflexivity.\n + simpl andb in hbct. rewrite hbct. reflexivity.\n - destruct c as [|].\n + reflexivity.\n + simpl andb in hbct. rewrite hbct. reflexivity.\nQed. \n\n\n(* Attemp #2 To Make it cleaner, not sure if it really is cleaner afterall. *)\nTheorem andb_true_elim2' : forall b c : bool,\n andb b c = true -> c = true.\nProof.\n intros b c.\n intros hbct.\n destruct b as [|]. destruct c as [|].\n - reflexivity.\n - simpl andb in hbct. rewrite hbct. reflexivity.\n - destruct c as [|].\n + reflexivity.\n + simpl andb in hbct. rewrite hbct. reflexivity.\nQed. \n(* Theorem zero nbeq plus 1 : ∀ n : nat, *)\n(* beq nat 0 (n + 1) = false. *)\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n beq_nat 0 (n + 1) = false.\nProof.\n intros [|n'].\n - simpl. reflexivity.\n - simpl. reflexivity.\nQed.\n\nEnd caseanyl.\n\n\nTheorem indentity_fn_aplied_twice :\n forall (f : bool -> bool),\n (forall (x : bool), f x = x ) ->\n forall (b : bool), f (f b) = b.\nProof.\n intros f hfx b.\n rewrite hfx. rewrite hfx.\n reflexivity.\nQed.\n\nTheorem negation_fn_aplied_twice :\n forall (f : bool -> bool),\n (forall (x : bool), f x = negb x ) ->\n forall (b : bool), f (f b) = b.\nProof.\n intros f hnx b.\n rewrite hnx. rewrite hnx. \n destruct b as [|].\n - simpl. reflexivity.\n - simpl. reflexivity.\nQed.\n\n\nTheorem andb_eq_orb :\n forall (b c : bool),\n (andb b c = orb b c) ->\n b = c.\nProof.\n intros b c.\n destruct b as [|]. destruct c as [|].\n - simpl. reflexivity.\n - simpl. intros hft. rewrite hft. reflexivity.\n - simpl. intros hfc. rewrite hfc. reflexivity.\nQed.\n\n\n\n(* Need to think about how to implement this properly. *)\nInductive bin : Type :=\n| Zip : bin\n| Dos : bin -> bin\n| SDos : bin -> bin.\n\nFixpoint incr (n : bin) : bin :=\n match n with\n | Zip => SDos Zip\n | Dos i => SDos i\n | SDos i => Dos (incr i)\nend.\n\nFixpoint bin_to_nat (n : bin) : nat :=\n match n with\n | Zip => 0\n | Dos i => 2 * (bin_to_nat i)\n | SDos i => 2 * (bin_to_nat i) + 1\nend.\n\nDefinition test_bin_incr_1 : bin_to_nat Zip = 0.\nProof. simpl. reflexivity. Qed.\n\nDefinition test_bin_incr_2 : bin_to_nat (incr Zip) = 1.\nProof. simpl. reflexivity. Qed.\n\nDefinition test_bin_incr_3 : bin_to_nat (incr (incr Zip)) = 2.\nProof. simpl. reflexivity. Qed.\n\nDefinition test_bin_incr_4 : bin_to_nat (incr (incr Zip)) = S ( S (bin_to_nat Zip)).\nProof. simpl. reflexivity. Qed.\n\nDefinition test_bin_incr_5 : bin_to_nat (incr (incr (incr ( SDos Zip)))) = 4.\nProof. simpl. reflexivity. Qed.", "meta": {"author": "robkorn", "repo": "coq-software-foundations", "sha": "95522c89a964ee00b68cb0e1f7f1600943a95936", "save_path": "github-repos/coq/robkorn-coq-software-foundations", "path": "github-repos/coq/robkorn-coq-software-foundations/coq-software-foundations-95522c89a964ee00b68cb0e1f7f1600943a95936/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.9207896677397366, "lm_q1q2_score": 0.8576810540549749}} {"text": "Require Export DMFP.Day13_induction.\n\n(* ################################################################# *)\n(** * Existential Quantification *)\n\n(** Another important logical connective is _existential\n quantification_. To say that there is some [x] of type [T] such\n that some property [P] holds of [x], we write [exists x : T,\n P]. As with [forall], the type annotation [: T] can be omitted if\n Coq is able to infer from the context what the type of [x] should\n be.\n\n The notion of \"existential\" is a common one in mathematics, but\n you may not be familiar with its precise meaning. It might be\n easier to understand [exists] as the \"dual\" of [forall]. When we\n say [forall x : T, P], we mean to say that:\n\n - Given any possible value [v] of type [T],\n\n - the proposition [P] holds when we replace [x] with [v].\n\n So, for example, when we say [forall n : nat, n + 0 = n], we mean\n that we [0 + 0 = 0] (choosen [0] for [n]) and [1 + 0 = 1]\n (choosing [1] for [n]) and [47 + 0 = 47] (choosing [47] for [n]).\n When we say that [exists x : T, P], we mean that\n\n - There is at least one value [v] of type [T], such that\n\n - the proposition [P] holds when we replace [x] with [v].\n\n For example, [exists n : nat, S n = 48] means \"there is (at least\n one) natural number [n] such that the successor of [n] is 48\". It\n turns out that this [S n = 48] for exactly _one_ [n]: 47. But it\n need not be so: the proposition [exists l : list nat, length l =\n 1] means that \"there exists a list of naturals [l] such that\n [length l] is 1\". There are many such lists: [ [1] ], [ [1337] ],\n and so on.\n\n *)\n\n(** PROP ::= EXPR1 = EXPR2\n | forall x : TYPE, PROP\n | PROP1 -> PROP2\n | PROP1 /\\ PROP2\n | PROP1 \\/ PROP2\n | True\n | ~ PROP\n | False\n | PROP1 <-> PROP2\n | exists x : TYPE, PROP <---- NEW!\n *)\n\n(** To prove a statement of the form [exists x, P], we must show that\n [P] holds for some specific choice of value for [x], known as the\n _witness_ of the existential. This is done in two steps: First,\n we explicitly tell Coq which witness [t] we have in mind by\n invoking the tactic [exists t]. Then we prove that [P] holds after\n all occurrences of [x] are replaced by [t]. *)\n\nLemma four_is_even : exists n : nat, 4 = n + n.\nProof.\n (* We want to show 4 is even, so we need to find a number [n] such\n that [n + n = 4]. If we try 2 we have [2 + 2 = 4], which seems\n to work. *)\n exists 2. reflexivity.\nQed.\n\n(** Conversely, if we have an existential hypothesis [exists x, P] in\n the context, we can destruct it to obtain a witness [x] and a\n hypothesis stating that [P] holds of [x]. *)\n\nTheorem exists_example_2 : forall n,\n (exists m, n = 4 + m) ->\n (exists o, n = 2 + o).\nProof.\n (* WORKED IN CLASS *)\n intros n [m Hm]. (* note implicit [destruct] here *)\n exists (2 + m).\n apply Hm. Qed.\n\n(** **** Exercise: 1 star, standard, especially useful (dist_not_exists)\n\n Prove that \"[P] holds for all [x]\" implies \"there is no [x] for\n which [P] does not hold.\" (Hint: [destruct H as [x E]] works on\n existential assumptions!) *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n intros X P H [x Hx].\n apply Hx. apply H.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, especially useful (dist_not_forall)\n\n Prove that \"there exists an [x] for which [P] holds\" implies \"it\n is not the case that for all [x] [P] does not hold.\" (Hint:\n [destruct H as [x E]] works on existential assumptions!) *)\nTheorem dist_not_forall : forall (X:Type) (P : X -> Prop),\n (exists x, P x) -> ~ (forall x, ~ P x).\nProof.\n unfold not.\n intros X P [x Hx].\n intros H. assert ( Hx' : P x -> False).\n -apply H.\n -apply Hx'. apply Hx.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (dist_exists_or)\n\n Prove that existential quantification distributes over\n disjunction. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Propositions and Booleans *)\n\n(** We've seen two different ways of encoding logical facts in Coq:\n with _booleans_ (of type [bool]), and with _propositions_ (of type\n [Prop]).\n\n For instance, to claim that a number [n] is even, we can say\n either\n - (1) that [evenb n] returns [true], or\n - (2) that there exists some [k] such that [n = double k].\n\n Indeed, these two notions of evenness are equivalent, as\n can easily be shown with a couple of auxiliary lemmas.\n\n Of course, it would be very strange if these two characterizations\n of evenness did not describe the same set of natural numbers!\n Fortunately, we can prove that they do... *)\n\n(** We first need three helper lemmas. *)\n(** **** Exercise: 2 stars, standard, optional (evenb_S)\n\n One inconvenient aspect of our definition of [evenb n] is the\n recursive call on [n - 2]. This makes proofs about [evenb n]\n harder when done by induction on [n], since we may need an\n induction hypothesis about [n - 2]. The following lemma gives an\n alternative characterization of [evenb (S n)] that works better\n with induction: *)\n\nTheorem evenb_S : forall n : nat,\n evenb (S n) = negb (evenb n).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\nTheorem evenb_double : forall k, evenb (double k) = true.\nProof.\n intros k. induction k as [|k' IHk'].\n - reflexivity.\n - simpl. apply IHk'.\nQed.\n\n(** **** Exercise: 3 stars, standard (evenb_double_conv) *)\nTheorem evenb_double_conv : forall n,\n exists k, n = if evenb n then double k\n else S (double k).\nProof.\n intros n. induction n as [| n' Hn'].\n -exists 0. simpl. reflexivity.\n -destruct Hn'. rewrite evenb_S. destruct evenb.\n +simpl. exists x. rewrite H. reflexivity.\n +simpl. exists (S x). simpl. rewrite H. reflexivity.\nQed.\n(** [] *)\n\nTheorem even_bool_prop : forall n,\n evenb n = true <-> exists k, n = double k.\nProof.\n intros n. split.\n - intros H. destruct (evenb_double_conv n) as [k Hk].\n rewrite Hk. rewrite H. exists k. reflexivity.\n - intros [k Hk]. rewrite Hk. apply evenb_double.\nQed.\n\n(** In view of this theorem, we say that the boolean\n computation [evenb n] _reflects_ the logical proposition\n [exists k, n = double k]. *)\n\n(** However, even when the boolean and propositional formulations of a\n claim are equivalent from a purely logical perspective, they need\n not be equivalent _operationally_.\n\n Equality provides an extreme example: knowing that [eqb n m =\n true] is generally of little direct help in the middle of a proof\n involving [n] and [m]; however, if we convert the statement to the\n equivalent form [n = m], we can rewrite with it. *)\n\n(** The case of even numbers is also interesting. Recall that,\n when proving the backwards direction of [even_bool_prop] (i.e.,\n [evenb_double], going from the propositional to the boolean\n claim), we used a simple induction on [k]. On the other hand, the\n converse (the [evenb_double_conv] exercise) required a clever\n generalization, since we can't directly prove [(exists k, n =\n double k) -> evenb n = true]. *)\n\n(** For these examples, the propositional claims are more useful than\n their boolean counterparts, but this is not always the case. For\n instance, we cannot test whether a general proposition is true or\n not in a function definition; as a consequence, the following code\n fragment is rejected: *)\n\nFail Definition is_even_prime n :=\n if n = 2 then true\n else false.\n\n(** Coq complains that [n = 2] has type [Prop], while it expects\n an elements of [bool] (or some other inductive type with two\n elements). The reason for this error message has to do with the\n _computational_ nature of Coq's core language, which is designed\n so that every function that it can express is computable and\n total. One reason for this is to allow the extraction of\n executable programs from Coq developments. As a consequence,\n [Prop] in Coq does _not_ have a universal case analysis operation\n telling whether any given proposition is true or false, since such\n an operation would allow us to write non-computable functions.\n\n Although general non-computable properties cannot be phrased as\n boolean computations, it is worth noting that even many\n _computable_ properties are easier to express using [Prop] than\n [bool], since recursive function definitions are subject to\n significant restrictions in Coq. For instance, later we'll shows\n how to define the property that two lists are permutations of each\n a given string using [Prop]. Doing the same with [bool] would\n amount to the [is_permutation_of] function we wrote on day\n 6... which (as we'll see) is more complicated, harder to\n understand, and harder to reason about than the [Prop] we'll\n define.\n\n Conversely, an important side benefit of stating facts using\n booleans is enabling some proof automation through computation\n with Coq terms, a technique known as _proof by reflection_.\n Consider the following statement: *)\n\nExample even_1000 : exists k, 1000 = double k.\n\n(** The most direct proof of this fact is to give the value of [k]\n explicitly. *)\n\nProof. exists 500. reflexivity. Qed.\n\n(** On the other hand, the proof of the corresponding boolean\n statement is even simpler: *)\n\nExample even_1000' : evenb 1000 = true.\nProof. reflexivity. Qed.\n\n(** What is interesting is that, since the two notions are equivalent,\n we can use the boolean formulation to prove the other one without\n mentioning the value 500 explicitly: *)\n\nExample even_1000'' : exists k, 1000 = double k.\nProof. apply even_bool_prop. reflexivity. Qed.\n\n(** Although we haven't gained much in terms of proof size in\n this case, larger proofs can often be made considerably simpler by\n the use of reflection. As an extreme example, the Coq proof of\n the famous _4-color theorem_ uses reflection to reduce the\n analysis of hundreds of different cases to a boolean computation.\n We won't cover reflection in any real detail, but it serves as a\n good example showing the complementary strengths of booleans and\n general propositions. *)\n\n(** As we go on to prove more interesting (and challenging!) things\n about our programs, the various iff lemmas relating computation to\n logic will surely come in handy. *)\n\n(* ================================================================= *)\n(** ** Classical vs. Constructive Logic *)\n\n(** We have seen that it is not possible to test whether or not a\n proposition [P] holds while defining a Coq function. You may be\n surprised to learn that a similar restriction applies to _proofs_!\n In other words, the following intuitive reasoning principle is not\n derivable in Coq: *)\n\nDefinition excluded_middle := forall P : Prop,\n P \\/ ~ P.\n\n(** To understand operationally why this is the case, recall\n that, to prove a statement of the form [P \\/ Q], we use the [left]\n and [right] tactics, which effectively require knowing which side\n of the disjunction holds. But the universally quantified [P] in\n [excluded_middle] is an _arbitrary_ proposition, which we know\n nothing about. We don't have enough information to choose which\n of [left] or [right] to apply, just as Coq doesn't have enough\n information to mechanically decide whether [P] holds or not inside\n a function. *)\n\n(** However, if we happen to know that [P] is reflected in some\n boolean term [b], then knowing whether it holds or not is trivial:\n we just have to check the value of [b]. *)\n\nTheorem restricted_excluded_middle : forall P b,\n (P <-> b = true) -> P \\/ ~ P.\nProof.\n (* Let a proposition P and boolean b be given.\n Assume that P holds if and only if [b = true].\n We must show [P \\/ ~ P].\n *)\n intros P [] H.\n (* We go by cases on [b].\n\n If b is true, by our assumption we know P holds, so we have [P].\n\n Otherwise, we likewise know by our assumption that P does not\n hold, so we have [~P]. *)\n - left. rewrite H. reflexivity.\n - right. rewrite H. intros contra. discriminate contra.\nQed.\n\n(** In particular, the excluded middle is valid for equations [n = m],\n between natural numbers [n] and [m]. *)\n\nTheorem restricted_excluded_middle_eq : forall (n m : nat),\n (forall n m, n = m <-> eqb n m = true) -> (* we'll prove this on day 15 *)\n n = m \\/ n <> m.\nProof.\n intros n m eqb_true_iff.\n apply (restricted_excluded_middle (n = m) (eqb n m)).\n apply eqb_true_iff.\nQed.\n\n(** It may seem strange that the general excluded middle is not\n available by default in Coq; after all, any given claim must be\n either true or false. Nonetheless, there is an advantage in not\n assuming the excluded middle: statements in Coq can make stronger\n claims than the analogous statements in standard mathematics.\n Notably, if there is a Coq proof of [exists x, P x], it is\n possible to explicitly exhibit a value of [x] for which we can\n prove [P x] -- in other words, every proof of existence is\n necessarily _constructive_. *)\n\n(** Logics like Coq's, which do not assume the excluded middle, are\n referred to as _constructive logics_.\n\n More conventional logical systems such as ZFC, in which the\n excluded middle does hold for arbitrary propositions, are referred\n to as _classical_. *)\n\n(** The following example illustrates why assuming the excluded middle\n may lead to non-constructive proofs:\n\n _Claim_: There exist irrational numbers [a] and [b] such that [a ^\n b] is rational.\n\n _Proof_: It is not difficult to show that [sqrt 2] is irrational.\n If [sqrt 2 ^ sqrt 2] is rational, it suffices to take [a = b =\n sqrt 2] and we are done. Otherwise, [sqrt 2 ^ sqrt 2] is\n irrational. In this case, we can take [a = sqrt 2 ^ sqrt 2] and\n [b = sqrt 2], since [a ^ b = sqrt 2 ^ (sqrt 2 * sqrt 2) = sqrt 2 ^\n 2 = 2]. []\n\n Do you see what happened here? We used the excluded middle to\n consider separately the cases where [sqrt 2 ^ sqrt 2] is rational\n and where it is not, without knowing which one actually holds!\n Because of that, we wind up knowing that such [a] and [b] exist but\n we cannot determine what their actual values are (at least, using\n this line of argument).\n\n As useful as constructive logic is, it does have its limitations:\n There are many statements that can easily be proven in classical\n logic but that have much more complicated constructive proofs, and\n there are some that are known to have no constructive proof at all!\n Fortunately, the excluded middle is known to be compatible with\n Coq's logic, allowing us to add it safely as an axiom. However, we\n will not need to do so in this book: the results that we cover can\n be developed entirely within constructive logic at negligible extra\n cost.\n\n It takes some practice to understand which proof techniques must be\n avoided in constructive reasoning, but arguments by contradiction,\n in particular, are infamous for leading to non-constructive proofs.\n Here's a typical example: suppose that we want to show that there\n exists [x] with some property [P], i.e., such that [P x]. We start\n by assuming that our conclusion is false; that is, [~ exists x, P\n x]. From this premise, it is not hard to derive [forall x, ~ P x].\n If we manage to show that this intermediate fact results in a\n contradiction, we arrive at an existence proof without ever\n exhibiting a value of [x] for which [P x] holds!\n\n The technical flaw here, from a constructive standpoint, is that we\n claimed to prove [exists x, P x] using a proof of [~ ~ (exists x, P\n x)]. Allowing ourselves to remove double negations from arbitrary\n statements is equivalent to assuming the excluded middle. Thus,\n this line of reasoning cannot be encoded in Coq without assuming\n additional axioms. *)\n\n(** **** Exercise: 2 stars, standard (forall_exists)\n\n In classical logic, [forall] and [exists] are _dual_: negating one\n gets you to the other. We saw some of this duality with\n [dist_not_exists] and [dist_not_forall].\n\n Only one of the following lemmas is provable in constructive\n logic. Which? Why isn't the other provable? *)\nLemma not_exists__forall_not : forall {X : Type} (P : X -> Prop),\n (~ exists x, P x) -> forall x, ~ P x.\nProof.\n intros X P H x H1. destruct H.\n exists x. apply H1.\nQed.\n\nLemma not_forall__exists_not : forall {X : Type} (P : X -> Prop),\n (~ forall x, P x) -> exists x, ~ P x.\nProof.\n unfold not.\n intros X P H. destruct H.\n intros x. \nAbort.\n\n(** In addition to doing one of these proofs, please briefly explain\n why the other doesn't work. *)\n\n(*The not_forall_exists_not does not work. It is because in the second one, you have to prove that P holds for all not X implies, there exists an x that does not hold for P. The issue is that exist is in the subgoal of the proof. Thus, when destruct or induction is applied on the forall statement, like in not_exists_forall_not, the exists x is destructed. And when we introduce x, we get up with property of x, which we cannot prove. *)\n\n(** [] *)\n\n(* 2021-10-04 14:37 *)\n", "meta": {"author": "Michaelcho1201", "repo": "Personal-work", "sha": "137d0a93555c62466d263a22dea2830f16a18a22", "save_path": "github-repos/coq/Michaelcho1201-Personal-work", "path": "github-repos/coq/Michaelcho1201-Personal-work/Personal-work-137d0a93555c62466d263a22dea2830f16a18a22/good work/Day14_exists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.9465966707651319, "lm_q1q2_score": 0.8576069501248285}} {"text": "From Coq Require Import Arith Lia.\n\n(* begin snippet exp2Def *)\nFixpoint exp2 (n:nat) : nat :=\n match n with\n 0 => 1\n | S i => 2 * exp2 i\n end.\n(* end snippet exp2Def *)\n\n\nLemma exp2_positive : forall i, 0 < exp2 i.\nProof.\n induction i; simpl; auto with arith. \nQed.\n\n\nLemma exp2_not_zero i : exp2 i <> 0.\nProof.\n specialize (exp2_positive i); intros H H0.\n rewrite H0 in H; apply (Nat.nlt_0_r _ H).\nQed.\n\n\nLemma exp2_gt_id : forall n, n < exp2 n.\nProof.\n induction n.\n - cbn; auto with arith.\n - cbn; generalize IHn; generalize (exp2 n); intros; lia.\nQed.\n\n\nLemma exp2S : forall n, exp2 (S n) = 2 * exp2 n.\nProof.\n unfold exp2; intros; simpl; ring. \nQed. \n\n\n \n", "meta": {"author": "coq-community", "repo": "hydra-battles", "sha": "2d211e0b5030d5f77aaaf6366b01fc64ed998c61", "save_path": "github-repos/coq/coq-community-hydra-battles", "path": "github-repos/coq/coq-community-hydra-battles/hydra-battles-2d211e0b5030d5f77aaaf6366b01fc64ed998c61/theories/ordinals/Prelude/Exp2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001757, "lm_q2_score": 0.9059898216525933, "lm_q1q2_score": 0.8576069484115959}} {"text": "(* This file is extracted from the TLC library.\n http://github.com/charguer/tlc\n DO NOT EDIT. *)\n\n(* -- DISCLAIMER: definitions in this file remain to be renamed,\n e.g. mmin and mmax. *)\n\n(**************************************************************************\n* TLC: A library for Coq *\n* Minimum/Maximum w.r.t. an order relation *\n**************************************************************************)\n\nSet Implicit Arguments.\nFrom SLF Require Import LibTactics LibLogic LibReflect LibOperation\n LibRelation LibOrder LibEpsilon.\nGeneralizable Variables A.\n\n(* This module offers the functions [mmin] and [mmax] which produce\n the minimum and maximum elements of a non-empty, bounded set. *)\n\n(**************************************************************************)\n(* * Lower bound and minimum*)\n\n(* [lower_bound le P x] means that [x] is a lower bound for the\n set [P] with respect to the ordering [le]. *)\n\nDefinition lower_bound A (le:binary A) (P:A->Prop) (x:A) :=\n forall y, P y -> le x y.\n\n(* [min_element le P x] means that [x] is a minimal element of\n [P], i.e., it is both a member of [P] and a lower bound for\n [P]. *)\n\nDefinition min_element A (le:binary A) (P:A->Prop) (x:A) :=\n P x /\\ lower_bound le P x.\n\n(* [mmin le P] is a minimal element of [P] with respect to [le],\n when such an element exists. *)\n\nDefinition mmin `{Inhab A} (le:binary A) (P:A->Prop) :=\n epsilon (min_element le P).\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Upper bound and maximum *)\n\n(* [upper_bound le P x] means that [x] is a lower bound for the\n set [P] with respect to the ordering [le]. *)\n\nDefinition upper_bound A (le:binary A) (P:A->Prop) (x:A) :=\n forall y, P y -> le y x.\n\n(* [max_element le P x] means that [x] is a maximal element of\n [P], i.e., it is both a member of [P] and a lower bound for\n [P]. *)\n\nDefinition max_element A (le:binary A) (P:A->Prop) (x:A) :=\n P x /\\ upper_bound le P x.\n\n(* [mmax le P] is a minimal element of [P] with respect to [le],\n when such an element exists. *)\n\nDefinition mmax `{Inhab A} (le:binary A) (P:A->Prop) :=\n epsilon (max_element le P).\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Least upper bound and greatest lower bound *)\n\n(* [lub le P x] means that [x] is a least upper bound\n for the set [P] with respect to the ordering [le]. *)\n\nDefinition lub A (le:binary A) (P:A->Prop) (x:A) :=\n min_element le (upper_bound le P) x.\n\n(* [glb le P x] means that [x] is a greatest lower bound\n for the set [P] with respect to the ordering [le]. *)\n\nDefinition glb A (le:binary A) (P:A->Prop) (x:A) :=\n max_element le (lower_bound le P) x.\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Connexion between lower and bounds *)\n\nLemma upper_bound_inverse : forall A (le:binary A),\n upper_bound le = lower_bound (inverse le).\nProof using.\n extens. intros P x. unfolds lower_bound, upper_bound. iff*.\nQed.\n\nLemma max_element_inverse : forall A (le:binary A) (P:A->Prop) (x:A),\n max_element le P x = min_element (inverse le) P x.\nProof using.\n extens. unfold max_element, min_element. rewrite* upper_bound_inverse.\nQed.\n\nLemma mmax_inverse : forall `{Inhab A} (le:binary A) (P:A->Prop),\n mmax le P = mmin (inverse le) P.\nProof using.\n intros. applys epsilon_eq. intros x. rewrite* max_element_inverse.\nQed.\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Elimination roperties *)\n\n(* [bounded_has_minimal le] means that, at type [A], it is\n the case that every non-empty set that admits a lower\n bound has a minimal element. *)\n\nDefinition bounded_has_minimal A (le:binary A) :=\n (* Recall that [ex P] means that [P] has an inhabitant; i.e.,\n it is equivalent to [exists x, P x]. *)\n forall P,\n ex P ->\n ex (lower_bound le P) ->\n ex (min_element le P).\n\n(* If the set [P] is non-empty and admits a lower bound, and if the type\n [A] is such that every such set has a minimal element, then [P] has a\n minimal element, and this element is [mmin le P]. *)\n\nLemma mmin_spec : forall `{Inhab A} (le:binary A) (P:A->Prop) m,\n m = mmin le P ->\n ex P ->\n ex (lower_bound le P) ->\n bounded_has_minimal le ->\n min_element le P m.\nProof using.\n intros. subst. unfold mmin. epsilon* m.\nQed.\n\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Application to [nat] *)\n\nFrom SLF Require Import LibNat.\n\n(* The type [nat] enjoys this property. *)\n\nLemma increment_lower_bound_nat : forall (P : nat->Prop) x,\n lower_bound le P x ->\n ~ P x ->\n lower_bound le P (x + 1)%nat.\nProof using.\n introv hlo ?. intros y ?.\n destruct (eq_nat_dec x y).\n { subst. tauto. }\n { forwards: hlo; eauto. nat_math. }\nQed.\n\nLemma bounded_has_minimal_nat :\n @bounded_has_minimal nat le.\nProof using.\n (* Assume a set [P], such that [y] is an inhabitant of [P]\n and [x] is a lower bound for [P]. *)\n intros P [ y ? ].\n (* We reason by induction on the difference [y + 1 - x].\n Reasoning with [y - x] would work too, but this choice\n is more elegant, as it makes the base case a contradiction,\n and avoids a little duplication. *)\n cut (\n forall (k x : nat), (y + 1 - x)%nat = k ->\n lower_bound le P x ->\n exists z, min_element le P z\n ). { intros ? [ x ? ]. eauto. }\n induction k; introv ? hlo.\n (* Base. *)\n (* Our hypotheses imply that [x] must be less than or equal to\n [y]. Because in this case the difference [y + 1 - x] is zero,\n this leads to a contradiction. *)\n { false. forwards: hlo; eauto. nat_math. }\n (* Step. *)\n (* Eeither [P x] holds, or it does not. If it does, then [x]\n is the desired minimal element. If it does not, this implies\n that [x + 1] is a lower bound for [P], and the induction\n hypothesis can be used. *)\n destruct (prop_inv (P x)).\n { exists x. split; eauto. }\n { eapply (IHk (x + 1)%nat). nat_math. eauto using increment_lower_bound_nat. }\nQed.\n\nHint Resolve bounded_has_minimal_nat : bounded_has_minimal.\n\n(* Furthermore, at type [nat], every set admits a lower bound. *)\n\nLemma admits_lower_bound_nat : forall (P : nat->Prop),\n ex (lower_bound le P).\nProof using.\n exists 0%nat. unfold lower_bound. nat_math.\nQed.\n\nHint Resolve admits_lower_bound_nat : admits_lower_bound.\n\n(* At type [nat], every non-empty set that admits an upper bound\n has a maximal element. *)\n\nLemma bounded_has_maximal_nat :\n @bounded_has_minimal nat (inverse le).\nProof using.\n (* Assume a set [P], such that [y] is an inhabitant of [P]\n and [x] is an upper bound for [P]. *)\n intros P [ y ? ] [ x h ].\n assert (y <= x).\n { forwards: h. eauto. eauto. }\n (* We apply our previous result to the image of [P] through\n the function that maps [i] to [x - i]. (We note that this\n function is its own inverse.) This yields a minimal\n element [z] of this image. Thus, [x - z] is the desired\n maximal element of [P]. *)\n assert (self_inverse: forall i, i <= x -> (x - (x - i))%nat = i).\n intros. nat_math.\n forwards [ z [ ? hz ]]: (@bounded_has_minimal_nat (fun i => P (x - i)%nat)).\n { exists (x - y)%nat. rewrite self_inverse by eauto. eauto. }\n { eauto using admits_lower_bound_nat. }\n exists (x - z)%nat.\n clear dependent y.\n split; [ assumption | ].\n intros y ?.\n assert (y <= x).\n { forwards: h. eauto. eauto. }\n forwards: hz (x - y)%nat.\n { rewrite self_inverse by eauto. eauto. }\n unfold inverse. nat_math.\nQed.\n\nHint Resolve bounded_has_maximal_nat : bounded_has_minimal.\n\nLemma mmin_spec_nat:\n forall (P:nat->Prop) m,\n m = mmin le P ->\n ex P ->\n P m /\\ (forall x, P x -> m <= x).\nProof using.\n introv E Q. applys (@mmin_spec _ _ _ P m E Q).\n applys admits_lower_bound_nat.\n applys bounded_has_minimal_nat.\nQed.\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Typeclasses *)\n\n(* [MMin P] is [mmin le P], in a context where the desired\n ordering can be inferred. *)\n\nDefinition MMin `{Inhab A} `{Le A} := mmin le.\n\n(* [MMax P] is [mmax le P], in a context where the desired\n ordering can be inferred. *)\n\nDefinition MMax `{Inhab A} `{Le A} := mmax le.\n\n\n\n(* 2021-08-11 15:24 *)\n", "meta": {"author": "blainehansen", "repo": "coq-playground", "sha": "93619e132a7fabf9d3b796465e253469815a0266", "save_path": "github-repos/coq/blainehansen-coq-playground", "path": "github-repos/coq/blainehansen-coq-playground/coq-playground-93619e132a7fabf9d3b796465e253469815a0266/SLF/LibMin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556619, "lm_q2_score": 0.9073122301325987, "lm_q1q2_score": 0.8574052607475101}} {"text": "Require Export SFBook.\n\n(* Prove the following basic property of doubling *)\n\nTheorem double_Sm : forall (n m : nat),\n n = S m -> n + n = S (S (m + m)).\nProof.\n intros n m H.\n rewrite H.\n simpl.\n rewrite <- plus_n_Sm.\n reflexivity.\nQed.\n\n\n(* Prove the following using destruct (either explicitly or implicitly). *)\n\nTheorem andb_false_l : forall b, b && true = b.\nProof.\n intros []; reflexivity.\nQed.\n\n(* Prove without destruct (either explicit or implicit). *)\n\nTheorem andb_false_l' : forall b, b && true = b.\nProof.\n intros.\n rewrite andb_commutative.\n simpl.\n reflexivity.\nQed.\n\n\n(* ******************************************************************************** *)\n\n(* The following is the erroneous \"mult3b\" function from the written part. Fix it (removing\n the \"Fail\" modifier)! *)\n\nFixpoint mult3b (n : nat) : bool :=\n match n with\n | O => true\n | S (S (S n')) => mult3b n'\n | _ => false\n end.\n\n(* Now use your function and \"filter\" to create a new function that takes a list of nats,\n and returns a list containing only those elements that are multiples of 3. *)\n\nDefinition extract_mult3s (l : list nat) : (list nat) :=\n filter mult3b l.\n\nExample test_extract_mult3s1 : extract_mult3s [1;3;9;2;7;3;5;0] = [3;9;3;0].\nProof. reflexivity. Qed.\n\n(* Next, use filter and an anonymous function to create a list that contains only those\n elements that are one smaller than a multiple of 3. *)\n\nDefinition extract_2mod3 (l : list nat) : (list nat) :=\n filter (fun n:nat => mult3b (S n)) l.\n\nExample test_2mod3_1 : extract_2mod3 [1;3;9;2;7;3;5;0] = [2;5].\nProof. reflexivity. Qed.\n\n(* ******************************************************************************** *)\n\n(* Define a function pair_flatten that takes a list of pairs of some type X, and\n produces a list of X that contains each individual item (no pairs). In other words,\n if called with the (list (nat*nat)) [(1,5);(2,4);(7,9)] it should return the list\n [1;5;2;4;7;9] *)\n\n(* FILL IN HERE *)\n\n(* State and prove a theorem [pair_flatten_len] that for any list of pairs [l] given\n to [pair_flatten_len], the length of the produced list is twice the length of the\n original list. *)\n\n(* FILL IN HERE *)\n\n(* ******************************************************************************** *)\n\n(* The following definition generalizes the definition of \"oddmembers\" from the book using\n the polymorphic list type. *)\n\nFixpoint oddmembers (l : list nat) : list nat :=\n match l with\n | nil => nil\n | h::t => match (evenb h) with\n | true => oddmembers t\n | false => h::(oddmembers t)\n end\n end.\n\n(* Prove the following theorem - note: maybe slightly too complex for the exam, but maybe\n as a final \"challenge\" problem (extra credit?) *)\n\nTheorem bigger_logic : forall (l : list nat),\n In 7 l <-> In 7 (oddmembers l).\nProof.\n (* FILL IN HERE *) Admitted.\n\n\n\n\n\n\n", "meta": {"author": "hpbrown92", "repo": "Coq-Solutions", "sha": "2467e185261bfe2dc043b2a49e353c8a9217b75e", "save_path": "github-repos/coq/hpbrown92-Coq-Solutions", "path": "github-repos/coq/hpbrown92-Coq-Solutions/Coq-Solutions-2467e185261bfe2dc043b2a49e353c8a9217b75e/Midterm-review.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868805, "lm_q2_score": 0.9284088079835903, "lm_q1q2_score": 0.8569576882880936}} {"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export exercise5.\nFrom Coq Require Import Setoids.Setoid.\n\nExample and_exercise :\n forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n intros. split.\n - destruct n.\n + reflexivity.\n + discriminate.\n - destruct m.\n + reflexivity.\n + rewrite <- plus_n_Sm in H. discriminate.\nQed.\n\nLemma proj1 : forall P Q : Prop,\n P /\\ Q -> P.\nProof.\n intros P Q HPQ.\n destruct HPQ as [HP _].\n apply HP.\nQed.\n\n(** **** Exercise: 1 star, standard, optional (proj2) *)\nLemma proj2 : forall P Q : Prop,\n P /\\ Q -> Q.\nProof.\n intros P Q [_ H].\n apply H.\nQed.\n\nTheorem and_commut : forall P Q : Prop,\n P /\\ Q -> Q /\\ P.\nProof.\n intros P Q [HP HQ].\n split.\n - (* left *) apply HQ.\n - (* right *) apply HP.\nQed.\n\n(* Exercise: 2 stars, standard (and_assoc) *)\n(* (In the following proof of associativity, notice how the\nnested intros pattern breaks the hypothesis H : P /\\ (Q /\\ R) down\ninto HP : P, HQ : Q, and HR : R. Finish the proof from there.) *)\nTheorem and_assoc : forall P Q R : Prop,\n P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n intros P Q R [HP [HQ HR]].\n split. split. apply HP. apply HQ. apply HR.\nQed.\n\nLemma or_intro_l : forall A B : Prop, A -> A \\/ B.\nProof.\n intros A B HA.\n left.\n apply HA.\nQed.\n\nLemma or_intro_r : forall A B : Prop, B -> A \\/ B.\nProof.\n intros A B HB.\n right.\n apply HB.\nQed.\n\nLemma mult_is_O :\n forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n intros. induction n.\n - left. reflexivity.\n - destruct m.\n + right. reflexivity.\n + inversion H.\nQed.\n\nLemma factor_is_O:\n forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n (* This pattern implicitly does case analysis on\n n = 0 \\/ m = 0 *)\n intros n m [Hn | Hm].\n - (* Here, n = 0 *)\n rewrite Hn. reflexivity.\n - (* Here, m = 0 *)\n rewrite Hm. rewrite <- mult_n_O.\n reflexivity.\nQed.\n\n(* Exercise: 1 star, standard (or_commut) *)\nTheorem or_commut : forall P Q : Prop,\n P \\/ Q -> Q \\/ P.\nProof.\n intros P Q [H1 | H2].\n - right. apply H1.\n - left. apply H2.\nQed.\n\nTheorem ex_falso_quodlibet: forall (P : Prop),\n\tFalse -> P.\nProof.\n\tintros P contra.\n\tdestruct contra.\nQed.\n\n\n(* Exercise: 2 stars, standard, optional (not_implies_our_not) *)\n(* Show that Coq's definition of negation implies the intuitive\none mentioned above. Hint: while getting accustomed to Coq's\ndefinition of not, you might find it helpful to unfold not near\nthe beginning of proofs. *)\nTheorem not_implies_our_not : forall (P : Prop),\n ~ P -> (forall (Q : Prop), P -> Q).\nProof.\n unfold not. intros.\n apply ex_falso_quodlibet.\n apply H. apply H0.\nQed.\n\nTheorem not_implies_our_not2 : forall (P : Prop),\n ~ P -> (forall (Q : Prop), P -> Q).\nProof.\n intros. destruct H. apply H0.\nQed.\n\n\n(* Inequality is a frequent enough form of negated statement that there is a special notation for it, x ≠ y: *)\nNotation \"x <> y\" := (~(x = y)).\n\n(** **** Exercise: 2 stars, advanced (double_neg_inf) *)\n(* Write an informal proof of double_neg:\nTheorem: P implies ~~P, for any proposition P. *)\nTheorem double_neg_inf : forall (P : Prop),\n P -> ~~ P.\nProof.\n intros. unfold not.\n intros. apply H0 in H. apply H.\nQed.\n\n\n(** **** Exercise: 2 stars, standard, especially useful (contrapositive) *)\nTheorem contrapositive : forall (P Q : Prop),\n (P -> Q) -> (~Q -> ~P).\nProof.\n unfold not. intros.\n apply H in H1. apply H0 in H1. apply H1.\nQed.\n\n\n(** **** Exercise: 1 star, standard (not_both_true_and_false) *)\nTheorem not_both_true_and_false : forall P : Prop,\n ~ (P /\\ ~P).\nProof.\n unfold not. intros P [H1 H2]. apply H2 in H1. apply H1.\nQed.\n\n(** **** Exercise: 2 stars, standard (de_morgan_not_or) *)\n(* De Morgan's Laws, named for Augustus De Morgan, describe how\nnegation interacts with conjunction and disjunction. The\nfollowing law says that \"the negation of a disjunction is the\nconjunction of the negations.\" There is a corresponding law\nde_morgan_not_and_not that we will return to at the end of thi\n chapter. *)\nTheorem de_morgan_not_or : forall (P Q : Prop),\n ~ (P \\/ Q) <-> ~P /\\ ~Q.\nProof.\n unfold not. intros.\n split.\n - split.\n + intros. apply H. apply or_intro_l. apply H0.\n + intros. apply H. apply or_intro_r. apply H0.\n - intros. destruct H0.\n + destruct H. apply H. apply H0.\n + destruct H. apply H1. apply H0.\nQed.\n\nTheorem iff_sym : forall P Q : Prop,\n (P <-> Q) -> (Q <-> P).\nProof.\n (* WORKED IN CLASS *)\n intros P Q [HAB HBA].\n split.\n - (* -> *) apply HBA.\n - (* <- *) apply HAB.\nQed.\n\nTheorem not_true_is_false : forall(b : bool),\n b <> true -> b = false.\nProof.\n intros. destruct b eqn: Hb.\n - unfold not in H. apply ex_falso_quodlibet.\n apply H. reflexivity.\n - reflexivity.\nQed.\n\nLemma not_true_iff_false : forall b,\n b <> true <-> b = false.\nProof.\n (* WORKED IN CLASS *)\n intros b. split.\n - (* -> *) apply not_true_is_false.\n - (* <- *)\n intros H. rewrite H. intros H'. discriminate H'.\nQed.\n\nTheorem or_distributes_over_and : forall P Q R : Prop,\n P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n unfold iff. intros. split.\n - intros. split.\n + destruct H.\n * apply or_intro_l. apply H.\n * apply proj1 in H. apply or_intro_r. apply H.\n + destruct H.\n * apply or_intro_l. apply H.\n * apply proj2 in H. apply or_intro_r. apply H.\n - intros [[|] [|]].\n + apply or_intro_l. apply H.\n + left. apply H.\n + left. apply H0.\n + right. split. apply H. apply H0.\nQed.\n\nLemma mul_eq_0 : forall (n m : nat),\n n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n intros. split.\n - apply mult_is_O.\n - apply factor_is_O.\nQed.\n\nTheorem or_assoc: forall P Q R : Prop,\n P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n intros. split.\n - intros [ H | [H | H] ].\n + left. left. apply H.\n + left. right. apply H.\n + right. apply H.\n - intros [ [H | H] | H].\n + left. apply H.\n + right. left. apply H.\n + right. right. apply H.\nQed.\n\nLemma mul_eq_0_ternary : forall n m p,\n n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n intros. \n rewrite mul_eq_0. rewrite mul_eq_0. rewrite or_assoc.\n reflexivity.\nQed.\n\nDefinition Even x := exists n: nat, x = double n.\n\n(** **** Exercise: 1 star, standard, especially useful (dist_not_exists) *)\n(* Prove that \"P holds for all x\" implies \"there is no x for which P does not\nhold.\" (Hint: destruct H as [x E] works on existential assumptions!) *)\nTheorem dist_not_exists : forall (X : Type) (P : X -> Prop),\n (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n unfold not. intros.\n destruct H0 as [x E]. apply E. apply H.\nQed.\n\n(** **** Exercise: 2 stars, standard (dist_exists_or) *)\n(* Prove that existential quantification distributes over disjunction. *)\nTheorem dist_exists_or : forall (X : Type) (P Q : X -> Prop),\n (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n intros. split.\n - intros. destruct H. destruct H.\n + left. exists x. apply H.\n + right. exists x. apply H.\n - intros. destruct H.\n + destruct H. exists x. left. apply H.\n + destruct H. exists x. right. apply H.\nQed.\n\n(** **** Exercise: 3 stars, standard, optional (leb_plus_exists) *)\nTheorem leb_plus_exists: forall n m,\n n <=? m = true -> exists x, m = n + x.\nProof.\n intros n. induction n as [|n' H].\n - intros. exists m. reflexivity.\n - destruct m.\n + simpl. discriminate.\n + simpl. intros. apply H in H0. destruct H0.\n rewrite H0. exists x. reflexivity.\nQed.\n\nTheorem plus_exists_leb : forall n m,\n exists x, m = n + x -> n <=? m = true.\nProof.\n intros. exists 0. rewrite add_0_r.\n intros. rewrite H. apply leb_refl.\nQed.\n\nFixpoint In {X : Type} (x : X) (l : list X) : Prop :=\n match l with\n | [] => False\n | x' :: l' => x' = x \\/ In x l'\n end.\n\nTheorem in_map :\n forall (A B : Type) (f : A -> B) (l : list A) (x : A),\n In x l ->\n In (f x) (map f l).\nProof.\n intros A B f l x. induction l as [| x' l' IHl].\n - simpl. intros. apply H.\n - simpl. intros [H | H].\n + left. rewrite H. reflexivity.\n + right. apply IHl. apply H.\nQed.\n\n(** **** Exercise: 3 stars, standard (In_map_iff) *)\nTheorem In_map_iff :\n forall (A B : Type) (f : A -> B) (l : list A) (y : B),\n In y (map f l) <->\n exists x, f x = y /\\ In x l.\nProof.\n intros A B f l y. split.\n - intros H. induction l as [| x' l' IHl].\n + simpl in H. simpl. apply ex_falso_quodlibet. apply H.\n + simpl in H. destruct H.\n * exists x'. simpl. split. apply H. left. reflexivity.\n * apply IHl in H. destruct H. exists x. simpl. split.\n destruct H. apply H. right. destruct H. apply H0.\n - intros. destruct H. destruct H. rewrite <- H. apply in_map. apply H0.\nQed.\n\n\n(** **** Exercise: 3 stars, standard, especially useful (All) *)\n(* Recall that functions returning propositions can be seen as properties of\ntheir arguments. For instance, if P has type nat -> Prop, then P n states that\nproperty P holds of n. *)\nFixpoint All {T : Type} (P : T -> Prop) (l : list T) : Prop :=\n match l with\n | [] => True\n | x' :: l' => P x' /\\ All P l'\n end.\n\nLemma ex_falso_quodlibet_ext : forall (T : Type) (P : T -> Prop),\n (forall x : T, False -> P x).\nProof.\nAdmitted.\n\nTheorem All_in :\n forall T (P : T -> Prop) (l : list T),\n (forall x, In x l -> P x) <->\n All P l.\nProof.\n intros. split.\n - induction l as [| x' l' IHl].\n + simpl. reflexivity.\n + simpl. intros. split.\n * apply H. left. reflexivity.\n * apply IHl. intros. apply H. right. apply H0.\n - induction l as [| x' l' IHl].\n + simpl. intros. apply ex_falso_quodlibet. apply H0.\n + simpl. intros. destruct H0.\n * rewrite H0 in H. apply proj1 in H. apply H.\n * destruct H. apply IHl. apply H1. apply H0.\nQed.\n\n(** **** Exercise: 2 stars, standard, optional (combine_odd_even) *)\n(* Complete the definition of the combine_odd_even function below. It takes as\narguments two properties of numbers, Podd and Peven, and it should return a\nproperty P such that P n is equivalent to Podd n when n is odd and equivalent\nto Peven n otherwise. *)\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n fun n => if odd n then Podd n else Peven n.\n\nTheorem combine_odd_even_intro :\n forall (Podd Peven : nat -> Prop) (n : nat),\n (odd n = true -> Podd n) ->\n (odd n = false -> Peven n) ->\n combine_odd_even Podd Peven n.\nProof.\n intros. unfold even in H, H0.\n unfold combine_odd_even.\n destruct n.\n - simpl. apply H0. simpl. reflexivity.\n - destruct (odd (S n)).\n + apply H. reflexivity.\n + apply H0. reflexivity.\nQed.\n\nTheorem combine_odd_even_elim_odd :\n forall (Podd Peven : nat -> Prop) (n : nat),\n combine_odd_even Podd Peven n ->\n odd n = true ->\n Podd n.\nProof.\n intros. unfold combine_odd_even in H.\n destruct (odd n).\n - apply H.\n - discriminate H0.\nQed.\n\nTheorem combine_odd_even_elim_even :\n forall (Podd Peven : nat -> Prop) (n : nat),\n combine_odd_even Podd Peven n ->\n odd n = false ->\n Peven n.\nProof.\n intros. unfold combine_odd_even in H.\n destruct (odd n).\n - discriminate.\n - apply H.\nQed.\n\nTheorem add_comm3 : forall x y z,\n x + (y + z) = (z + y) + x.\nProof.\n intros.\n rewrite add_comm.\n rewrite (add_comm y z).\n reflexivity.\nQed.\n\nTheorem in_not_nil : forall A (x : A) (l : list A),\n In x l -> l <> [].\nProof.\n intros. unfold not.\n intros. rewrite H0 in H.\n simpl in H. apply H.\nQed.\n\n(** **** Exercise: 4 stars, standard (tr_rev_correct) *)\n(* One problem with the definition of the list-reversing function rev\nthat we have is that it performs a call to app on each step; running\napp takes time asymptotically linear in the size of the list, which\nmeans that rev is asymptotically quadratic. We can improve this with\nthe following definitions: *)\nFixpoint rev_append {X} (l1 l2 : list X) : list X :=\n match l1 with\n | [] => l2\n | x :: l1' => rev_append l1' (x :: l2)\n end.\n\nDefinition tr_rev {X} (l : list X) : list X :=\n rev_append l [].\n\nAxiom functional_extensionality : forall (X Y : Type) (f g : X -> Y),\n(forall x : X, f x = g x) -> f = g.\n\nCompute (rev_append [1;2;3] [4;5;6]).\n\nLemma rev_append_rev_origin : forall X (l1 l2 : list X),\n rev_append l1 l2 = rev l1 ++ l2.\nProof.\n intros X l1. induction l1 as [| n' l' IHl]; intros.\n - reflexivity.\n - simpl. rewrite <- app_assoc. simpl. apply IHl.\nQed.\n\nTheorem tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n intros.\n apply functional_extensionality.\n induction x as [| x' l' IHx].\n - unfold tr_rev. reflexivity.\n - unfold tr_rev. simpl. apply rev_append_rev_origin.\nQed.\n\nLemma even_double : forall k,\n even (double k) = true.\nProof.\n intros. induction k as [| k' H].\n - reflexivity.\n - simpl. rewrite H. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, standard (even_double_conv) *)\nLemma even_double_conv : forall n, exists k,\n n = if even n then double k else S (double k).\nProof.\n intros. induction n as [| n' H].\n - simpl. exists 0. reflexivity.\n - rewrite even_S. destruct H.\n destruct (even n').\n + simpl. exists x. rewrite H. reflexivity.\n + simpl. exists (S x). rewrite double_incr. rewrite H. reflexivity.\nQed.\n\nTheorem even_bool_prop : forall n,\n even n = true <-> Even n.\nProof.\n intros. split.\n (* Apply the theorem on n, so we obtain some k. *)\n - intros. destruct (even_double_conv n) as [k Hk].\n rewrite Hk. rewrite H. unfold Even. exists k. reflexivity.\n - unfold Even. intros. destruct H. rewrite H. apply even_double.\nQed.\n\nTheorem eqb_eq : forall n m : nat,\n n =? m = true <-> n = m.\nProof.\n intros. split.\n - apply eqb_true.\n - intros. rewrite H. rewrite eqb_refl. reflexivity.\nQed.\n\nExample not_even_1001 : ~(Even 1001).\nProof.\n rewrite <- even_bool_prop.\n unfold not.\n intros.\n discriminate.\nQed.\n\n\n(** **** Exercise: 2 stars, standard (logical_connectives) *)\n(* The following theorems relate the propositional connectives studied in this chapter\nto the corresponding boolean operations. *)\nTheorem andb_true_iff : forall b1 b2 : bool,\n andb b1 b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n intros. split.\n - intros. destruct b1.\n + destruct b2.\n * split. reflexivity. reflexivity.\n * split. discriminate. discriminate.\n + destruct b2.\n * split. discriminate. discriminate.\n * split. discriminate. discriminate.\n - intros [H1 H2]. rewrite H1. rewrite H2. reflexivity.\nQed.\n\n\nTheorem orb_ture_iff : forall b1 b2 : bool,\n orb b1 b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n intros. split.\n - intros. destruct b1.\n + destruct b2.\n * left. reflexivity.\n * left. reflexivity.\n + destruct b2.\n * right. reflexivity.\n * discriminate.\n - intros [H1 | H2].\n + unfold orb. rewrite H1. reflexivity.\n + unfold orb. rewrite H2. destruct b1.\n * reflexivity.\n * reflexivity.\nQed.\n\n(** **** Exercise: 1 star, standard (eqb_neq) *)\n(* The following theorem is an alternate \"negative\" formulation of eqb_eq\nthat is more convenient in certain situations.\n(We'll see examples in later chapters.) Hint: not_true_iff_false. *)\nTheorem eqb_neq : forall x y : nat,\n x =? y = false <-> x <> y.\nProof.\n intros. unfold not. split.\n - intros. rewrite H0 in H. rewrite eqb_refl in H. discriminate.\n - intros. apply not_true_iff_false. unfold not. intros.\n apply eqb_eq in H0. apply H. apply H0.\nQed.\n\n(** **** Exercise: 3 stars, standard (eqb_list) *)\n(* Given a boolean operator eqb for testing equality of elements of some type A,\nwe can define a function eqb_list for testing equality of lists with elements in A.\nComplete the definition of the eqb_list function below. To make sure that your\ndefinition is correct, prove the lemma eqb_list_true_iff. *)\nFixpoint eqb_list {A : Type} (eqb : A -> A -> bool) (l1 l2 : list A) : bool :=\n match l1, l2 with\n | [], [] => true\n | [], _ => false\n | _, [] => false\n | (n1 :: l1'), (n2 :: l2') => andb (eqb n1 n2) (eqb_list eqb l1' l2')\n end.\n\nTheorem eqb_list_true_iff :\n forall A (eqb : A -> A -> bool),\n (forall a1 a2, eqb a1 a2 = true <-> a1 = a2) ->\n forall l1 l2, eqb_list eqb l1 l2 = true <-> l1 = l2.\nProof.\n intros A eqb H. induction l1.\n - destruct l2.\n + simpl. split. intros. reflexivity. intros. reflexivity.\n + simpl. split. intros. discriminate. intros. discriminate.\n - destruct l2.\n + simpl. split. intros. discriminate. intros. discriminate.\n + (* non-trivial. *)\n simpl. split. intros.\n * apply andb_true_iff in H0. destruct H0 as [H1 H2].\n apply H in H1. apply IHl1 in H2. rewrite H1, H2. reflexivity.\n * intros. injection H0 as H'. apply andb_true_iff. split.\n apply H. apply H'. apply IHl1. apply H0.\nQed.\n\n(** **** Exercise: 2 stars, standard, especially useful (All_forallb) *)\n(* Prove the theorem below, which relates forallb, from the exercise forall_exists_challenge\nin chapter Tactics, to the All property defined above. *)\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n match l with\n | [] => true\n | n :: l' => andb (test n) (forallb test l')\n end.\n\nTheorem forallb_true_iff : forall X test (l : list X),\n forallb test l = true <-> All (fun x => test x = true) l.\nProof.\n intros. split.\n - intros. induction l.\n + reflexivity.\n + simpl in H. apply andb_true_iff in H. destruct H as [H1 H2].\n simpl. split.\n * apply H1.\n * apply IHl in H2. apply H2.\n - intros. induction l.\n + reflexivity.\n + simpl. apply andb_true_iff. split.\n * simpl in H. destruct H as [H _]. apply H.\n * simpl in H. destruct H as [_ H]. apply IHl in H. apply H.\nQed.\n\nTheorem de_facto_not_trivial : forall P b,\n (P <-> b = true) -> P \\/ ~P.\nProof.\n intros P [] H.\n - left. rewrite H. reflexivity.\n - right. rewrite H. discriminate.\nQed.\n\nDefinition excluded_middle := forall P : Prop,\n P \\/ ~ P.\n\nLemma helper : forall P,\n ~(P /\\ ~P).\nProof.\n unfold not. intros P [H1 H2].\n apply H2. apply H1.\nQed.\n\n(** **** Exercise: 3 stars, standard (excluded_middle_irrefutable) *)\nTheorem excluded_middle_irrefutable : forall P : Prop,\n ~~(P \\/ ~P).\nProof.\n intros P H.\n apply de_morgan_not_or in H. apply helper in H. apply H.\nQed.\n\n(** **** Exercise: 3 stars, advanced (not_exists_dist) *)\n(* It is a theorem of classical logic that the following two assertions are equivalent:\n ~ (∃ x, ~ P x)\n forall x, P x\nThe dist_not_exists theorem above proves one side of this equivalence. Interestingly, the\nother direction cannot be proved in constructive logic. Your job is to show that it is implied\nby the excluded middle. *)\nTheorem not_exists_dist:\n excluded_middle ->\n forall (X : Type) (P : X -> Prop),\n ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n intros EM X P. unfold not. intros.\n destruct (EM (P x)) as [H1 | H2]. (* Can destruct the whole proposition. *)\n - apply H1.\n - apply ex_falso_quodlibet. apply H. exists x. apply H2.\nQed.\n\nDefinition peirce := forall P Q: Prop,\n ((P -> Q) -> P) -> P.\nDefinition double_negation_elimination := forall P:Prop,\n ~~P -> P.\nDefinition de_morgan_not_and_not := forall P Q:Prop,\n ~(~P /\\ ~ Q) -> P \\/ Q.\nDefinition implies_to_or := forall P Q:Prop,\n (P -> Q) -> (~ P \\/ Q).\n\nTheorem em_imples_peirce :\n excluded_middle -> peirce.\nProof.\n unfold excluded_middle, peirce, not.\n intros. destruct (H P).\n - apply H1.\n - apply H0. intros. apply H1 in H2. apply ex_falso_quodlibet. apply H2.\nQed.\n\nTheorem peirce_imples_dne:\n peirce -> double_negation_elimination.\nProof.\n unfold peirce, double_negation_elimination, not.\n intros. apply (H P False). (* Remember to apply with arguments! *)\n intros. apply H0 in H1. apply ex_falso_quodlibet. apply H1.\nQed.\n\nTheorem dne_implies_dm :\n double_negation_elimination -> de_morgan_not_and_not.\nProof.\n unfold double_negation_elimination, de_morgan_not_and_not, not.\n intros. apply H. intros. apply H1.\n left. apply H. intros. apply H0. split. apply H2. intros. apply H1. right. apply H3.\nQed.\n\nTheorem dm_implies_implies_to_or :\n de_morgan_not_and_not -> implies_to_or.\nProof.\n unfold de_morgan_not_and_not, implies_to_or, not.\n intros.\n apply H. intros. destruct H1.\n apply H1. intros. apply H2. apply H0. apply H3.\nQed.\n\nTheorem implies_to_or_implies_em :\n implies_to_or -> excluded_middle.\nProof.\n unfold implies_to_or, excluded_middle, not.\n intros.\n apply or_commut. apply H. intros. apply H0.\nQed.", "meta": {"author": "hiroki-chen", "repo": "Software-Foundations", "sha": "c60a50c490603fce3c2ecaa88976349004f7fc6f", "save_path": "github-repos/coq/hiroki-chen-Software-Foundations", "path": "github-repos/coq/hiroki-chen-Software-Foundations/Software-Foundations-c60a50c490603fce3c2ecaa88976349004f7fc6f/Vol1/exercise6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.9353465152482724, "lm_q1q2_score": 0.856879938940925}} {"text": "Require Import Arith.\n\n(* Quelques tactiques utiles, qu'on verra au fur et a mesure :\n - assert (un énoncé) H12\n - replace (un terme) with (un autre)\n - inversion H. \n - ((auto with arith : seulement quand la tactique est EXPLICITEMENT autorisée)) *)\n\n\n(** Partie I : Petits prédicats inductifs *)\n\n(* Réflechissez un peu au sens de nat -> Prop *)\n\n(*A.nat -> Prop est un predicat sur les entiers*)\n\n(* En plus des types de données inductifs, Coq permet de définir des\npropriétés inductives. Par exemple, la propriété que un nat est pair\npeut être définie de la facon suivante : *)\n\nInductive even : nat -> Prop := \n | even_zero : even 0 \n | even_succ : forall n, even n -> even (S (S n)).\n\n\n(* even n \n -------- -------------- \n even 0 even (S (S n)) *)\n\n\n(* Définissez vous-même le prédicat \"odd\" pour designer les\nimpairs. Essayez de trouver une définition avec UN SEUL\nconstructeur. *)\n\nInductive odd : nat -> Prop :=\n | odd_succ : forall n, even n -> odd (S n).\n\n(* [inversion H] est une tactique compliquée qui élimine les cas\nimpossibles dans les types inductifs. Servez-vous en pour prouver : *)\n\nLemma not_even: ~ odd 0.\n intros H.\n inversion H.\nQed.\n\nLemma odd_even : forall n, odd n -> even (S n).\n intros.\n inversion H.\n apply even_succ.\n apply H0.\nQed.\n\nLemma eventwo_times : forall n, even (n * 2).\n intros.\n induction n.\n *\n simpl.\n apply even_zero.\n *\n simpl.\n apply even_succ.\n apply IHn.\nQed.\n\nLemma odd_or_even : forall n, even n \\/ odd n.\n intros.\n induction n.\n *\n left.\n apply even_zero.\n *\n destruct IHn.\n right.\n apply odd_succ.\n apply H.\n left.\n apply odd_even.\n apply H.\nQed.\n\nLemma evenS_odd : forall n, even (S n) -> odd n.\n intros.\n inversion H.\n apply odd_succ.\n apply H1.\nQed.\n\nLemma oddS_even : forall n, odd (S n) -> even n.\n intros.\n inversion H.\n apply H1.\nQed.\n\n(* Conseil: utilisez inversion. *)\nLemma odd_and_even : forall n, ~ (even n /\\ odd n).\n induction n.\n *\n unfold not.\n intros.\n destruct H.\n apply not_even.\n apply H0.\n *\n unfold not.\n intros H0.\n destruct IHn.\n destruct H0.\n split.\n apply oddS_even.\n apply H0.\n apply evenS_odd.\n apply H.\nQed.\n\n\n\n\n(** Prédicats inductifs : relations *)\n\n(* Le type [A -> A -> Prop] des formules paramétrées par deux éléments\nde A sert à représenter les relations sur A. *)\nDefinition relation A := A -> A -> Prop.\n\n(* Par exemple la relation [div] est une [relation nat] *)\n\n(* Mais on peut aussi définir des relations de relations comme par\nexample l'inclusion entre les relations. *)\nDefinition incl A : relation (relation A) := fun R1 R2 => \n forall x y, R1 x y -> R2 x y.\n\n(* Definissez la relation maximale, la relation minimale (i.e. la\nrelation vide) ainsi que la relation identité. *)\nDefinition rel_full A : relation A :=\n fun x y => True.\nDefinition rel_empty A : relation A :=\n fun x y => False. \nDefinition rel_id A : relation A :=\n fun x y => x=y.\n\n(* Étant donnée une relation, définissez la relation réciproque. *)\nDefinition converse A (R : relation A) :=\n fun x y => R y x.\n\n(* On peut aussi définir des propriétés sur les relations comme par\nexemple la transitivité : *)\nDefinition transitive A (R : relation A) : Prop := \n forall x y z, R x y -> R y z -> R x z.\n\n(* Définissez la réflexivité et la symétrie: *)\nDefinition reflexive A (R : relation A) : Prop :=\n forall x, R x x.\nDefinition symmetric A (R : relation A) : Prop :=\n forall x y, R x y -> R y x.\n\n(* Pour vous chauffer, prouvez le lemme suivant. Indice: Utilisez la\ntactique [unfold D] pour déplier la définition D. La tactique [compute\nin H] permet de normaliser le type de H *)\nLemma incl_conv : forall A R, incl A R (converse A R) -> symmetric A R.\n intros.\n compute in H.\n compute.\n apply H.\nQed.\n\n(* Dans cette section nous allons fabriquer la cloture reflexive\ntransitive d'une relation. *)\n\nSection Star. \n\n(* On suppose qu'on dispose d'un type A et d'une relation sur A. *)\nVariable A : Type. \nVariable R : A -> A -> Prop. \n\n(* On définit le prédicat inductif suivant : *)\nInductive star : A -> A -> Prop :=\n | star_refl : forall a, star a a\n | star_R : forall a b c, R a b -> star b c -> star a c.\n\n(* Prouvez que R est incluse dans sa cloture. *)\nLemma R_star : incl A R star.\n compute.\n intros.\n apply star_R with y.\n apply H.\n apply star_refl.\nQed.\n\n(* Prouvez que la cloture est transitive. Indice : Dans [apply h with\nt], le mot-clef 'with' permet de donner à apply les arguments qu'il\nn'arrive pas à inférer. *)\nLemma star_trans : transitive _ star.\n compute.\n intros.\n induction H.\n *\n apply H0.\n *\n apply IHstar in H0.\n apply star_R with b.\n apply H.\n apply H0.\nQed.\n\n(* En passant, vous pouvez démontrer ça aussi. *)\nLemma star_ass : forall a b c, star a b -> R b c -> star a c.\nProof.\n intros.\n apply R_star in H0.\n apply star_trans with b.\n apply H.\n apply H0.\nQed.\n \nLemma star_sym : symmetric _ R -> symmetric _ star.\nProof.\n compute.\n intros.\n induction H0.\n apply star_refl.\n apply H in H0.\n apply star_ass with b.\n apply IHstar.\n apply H0.\nQed.\n\nCheck star_trans. \nEnd Star.\nCheck star_trans.\n\n\n\n\n\n\n(** Partie II : Sémantique à grands pas *)\n\n(* Considérons la grammaire d'expressions suivante, avec les mots\ninhabituels \"Randombit\" et \"AssertZero\", qui sont expliqués plus\nbas. *)\n\nInductive expr : Set :=\n | N : nat -> expr\n (*| Randombit : expr*)\n | Zero : expr\n | Un : expr\n | Plus : expr -> expr -> expr\n | Mult : expr -> expr -> expr\n | Minus : expr -> expr -> expr\n | AssertZero : expr -> expr -> expr.\n\n(* Donnez une sémantique à grand pas avec le sens suivant :\n - N n\n représente l'entier n\n \n -------\n N n → n\n \n - Plus, Mult et Minus\n comme en cours\n \n e₁ → n₁ e₂ → n₂ \n -------------------\n Plus e₁ e₂ → n₁ + n₂\n \n \n - Randombit\n peut engendrer 0\n peut engendrer 1\n \n ------------ ------------\n Randombit → 0 Randombit → 1\n \n - AssertZero e1 e2\n s'assure que e1 peut réduire vers 0 et se comporte comme e2 dans\n ce cas.\n \n e₁ → 0 e₂ → n₂\n ---------------------\n AssertZero e₁ e₂ → n₂\n*)\n\nInductive bs : expr -> nat -> Prop := \n | bs_nat : forall n, bs (N n) n\n (*| bs_Randombit0 : bs Randombit 0\n | bs_Randombit1 : bs Randombit 1*)\n | bs_Zero : bs Zero 0\n | bs_Un : bs Un 1\n | bs_Plus : forall e1 e2 n m, bs e1 n -> bs e2 m -> bs (Plus e1 e2) (n+m)\n | bs_Mult : forall e1 e2 n m, bs e1 n -> bs e2 m -> bs (Mult e1 e2) (n*m)\n | bs_Minus : forall e1 e2 n m, bs e1 n -> bs e2 m -> bs (Minus e1 e2) (n-m)\n | bs_AssertZero : forall e1 e2 n, bs e1 0 -> bs e2 n -> bs (AssertZero e1 e2) n\n. \n(* Question :\n \nEssayez de définir une telle sémantique pour faire en sorte que\n\"AssertZero e1 e2\" se comporte comme \"e2\" si \"e1\" ne peut PAS se\nréduire vers 0. Coq accepte-t'il la définition ? Pourquoi ? *)\n(*\nLemma expression_example :\n bs (AssertZero (Minus (Minus (N 2) Randombit) Randombit) (Mult (N 5) (N 3))) 15.\n (* replace expr1 with expr2 => substitue expr1 par expr2 et un but apparait pour prouver l'égalité *)\n apply bs_AssertZero.\n *\n replace 0 with (1-1).\n apply bs_Minus.\n simpl.\n replace 1 with (2-1).\n apply bs_Minus.\n simpl.\n apply bs_nat.\n apply bs_Randombit1.\n simpl.\n reflexivity.\n apply bs_Randombit1.\n simpl.\n reflexivity.\n *\n replace 15 with(5*3).\n apply bs_Mult.\n apply bs_nat.\n apply bs_nat.\n simpl.\n reflexivity.\nQed.\n*)\n\n(* On va vouloir définir une fonction d'évaluation des expressions; pour ça, on se débarasse de RandomBit et \n on le remplace par Zero et Un, qui valent toujours zero et un! Commentez les expressions et redéfinissez-les ainsi. *)\n\n\n\n\n(* Définissez maintenant une fonction récursive eval qui calcule la valeur d'une expression \n arithmétique. Pour le cas ou un AssertZero échoue, considérez que la valeur retournée par l'assert est 0. *)\n\nFixpoint eval (e : expr) : nat :=\n match e with\n |N(n) => n\n |Zero => 0\n |Un => 1\n |Plus e1 e2 => (eval e1) + (eval e2)\n |Mult e1 e2 => (eval e1) * (eval e2)\n |Minus e1 e2 => (eval e1) - (eval e2)\n |AssertZero e1 e2 =>\n match eval e1 with\n |0 => eval e2\n |_ => 0\n end\nend.\n\n(* On va maintenant prouver qu'on a défini une fonction qui est correcte vis-à-vis de \n\tla sémantique à grand pas des expressions *)\n\nLemma eval_correct : forall (e : expr) (n : nat), bs e n -> eval e = n.\n intros.\n inversion H.\n *\n simpl.\n reflexivity.\n *\n simpl.\n reflexivity.\n *\n simpl.\n reflexivity.\n *\n simpl.\n induction e.\nQed.\n\n(* Peut-on prouver le lemme opposé? (c'est-à-dire que si eval e = n, alors on a bs e n). Pourquoi? *)\n\n\n\n\n\n\n\n\n", "meta": {"author": "adud", "repo": "prog-l3", "sha": "cca449d82f22c714e3703984aed39307ee0c3657", "save_path": "github-repos/coq/adud-prog-l3", "path": "github-repos/coq/adud-prog-l3/prog-l3-cca449d82f22c714e3703984aed39307ee0c3657/tp2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.9099070151996071, "lm_q1q2_score": 0.8568177225395798}} {"text": "Module Playground1.\n\nInductive bool : Type :=\n| true : bool\n| false : bool.\n\nCheck true.\nCheck bool.\n\n\nInductive nat : Type :=\n| O : nat\n| S : nat -> nat.\n\nEnd Playground1.\n\nDefinition minustwo (n : nat) : nat :=\n match n with\n | O => O\n | S O => O\n | S (S n') => n'\n end.\n\nFixpoint evenb (n : nat) : bool :=\n match n with\n | O => true\n | S O => false\n | S (S n') => evenb n'\n end.\n\nDefinition oddb (n : nat) : bool := negb (evenb n).\n\nDefinition admit {T: Type} : T. Admitted.\n(* Haskell: undefined *)\n\nModule Playground2.\n\nFixpoint plus (n : nat) (m : nat) {struct n} : nat :=\n match n with\n | O => m\n | S n' => S (plus n' m)\n end.\n\nFixpoint mult (n m : nat) : nat :=\n match n with \n | O => O\n | S n' => plus m (mult n' m)\n end.\n\nFixpoint minus (n m : nat) : nat :=\n match n, m with\n | O , _ => O\n | _ , O => n (* make this non-overlapping *)\n | S n', S m' => minus n' m'\n end.\n\nEnd Playground2.\n\nTheorem plus_O_n : forall n:nat, 0 + n = n.\nProof.\n intro n.\n simpl.\n reflexivity.\nQed.\n\n(* End of seminar 1. *)\n\n(* ************************************************************ *)\n\n(* Looking up info *)\n\n(* Require Import Arith. *)\nSearch nat.\nSearchAbout nat.\n(* SearchPattern (_ -> nat). (* Doesn't work in older coq versions *) *)\nSearchRewrite (0 + _).\n\n\n(* More tactics. *)\n\nTheorem plus_id_example : forall n m,\n n = m -> n + n = m + m.\nProof.\n intros k l.\n intros H.\n rewrite <- H. (* show directions *)\n reflexivity.\nQed.\n\nTheorem mult_O_plus : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros.\n rewrite -> plus_O_n.\n reflexivity.\nQed.\n\n\nFixpoint beq_nat (n m : nat) : bool :=\n match n, m with\n | O, O => true\n | S n', S m' => beq_nat n' m'\n | _, _ => false\n end.\n\nPrint beq_nat.\n\nTheorem plus_1_neq_0_b : forall n : nat,\n beq_nat (n+1) 0 = false.\nProof.\n intros.\n (* destruct n; reflexivity. *)\n destruct n.\n reflexivity.\n\n reflexivity.\nQed.\n\nAxiom convenient : forall n, n+1 = S n.\n\nTheorem plus_1_neq_0 : forall n : nat, n + 1 <> 0.\nProof.\n intros.\n (* rewrite convenient. *)\n (* discriminate. *)\n destruct n.\n discriminate.\n\n simpl.\n discriminate.\nQed.\n\nTheorem eq_beq_nat : forall n m : nat,\n n = m <-> beq_nat n m = true.\nProof.\n intros.\n split.\n intro.\n rewrite H.\n(* Finish from here. Hard. Good HW! :) *)\nAdmitted.\n\n\nTheorem plus_0_r : forall n, n + 0 = n.\nProof.\n intros.\n induction n.\n reflexivity.\n\n simpl.\n rewrite IHn.\n reflexivity.\nQed.\n\nTheorem minus_diag : forall n : nat, n - n = 0.\nProof.\n intros.\n induction n.\n reflexivity.\n\n simpl.\n assumption.\nQed.\n\nTheorem plus_comm : forall n m, n + m = m + n.\nProof.\n intros n m.\n induction n.\n simpl.\n rewrite plus_0_r.\n reflexivity.\n\n simpl.\n rewrite IHn.\n assert (forall k l, k + S l = S (k + l)).\n clear IHn n m.\n intros.\n induction k.\n reflexivity.\n\n simpl.\n rewrite IHk.\n reflexivity.\n\n rewrite H.\n reflexivity.\nQed.\n(* HW: do without assert, but with induction within induction. *)\n\n(* Induction more closely *)\n\nFixpoint double n : nat :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\nTheorem double_injective : forall n m,\n double n = double m ->\n n = m.\nProof.\n intros.\n generalize dependent m.\n induction n.\n intros.\n destruct m.\n reflexivity.\n\n simpl in H.\n discriminate H.\n\n\n intros.\n destruct m.\n discriminate H.\n\n f_equal.\n apply IHn.\n simpl in H.\n inversion H.\n trivial.\nQed.\n(* intros n. *)\n(* induction n. *)\n(* intros. *)\n(* simpl in H. *)\n(* destruct m. *)\n(* reflexivity. *)\n\n(* simpl in H. *)\n(* discriminate H. *)\n\n(* (* induction side *) *)\n(* intros. *)\n(* destruct m. *)\n(* discriminate H. *)\n\n(* (* apply a hypothesis to the goal *) *)\n(* f_equal. (* remove the same constructor *) *)\n(* apply IHn. *)\n(* simpl in H. *)\n(* (* TODO(klao): look up how to introduce S-es to the goal. *) *)\n(* (* union of 'discriminate' and 'f_equal in hypothesis' *) *)\n(* inversion H. *)\n(* reflexivity. *)\n(* Qed. *)\n(* TODO(klao): look into: printing readable proofs. *)\n\n(* End of Seminar 2. *)\n\n(* ********************************************************************** *)\n(* Seminar 3 starts here. *)\n\n(* revert, generalize dependent, and induction in |- *)\n\n\n\nTheorem plus_rearrange : forall n m p q,\n (n + m) + (p + q) = (m + n) + (q + p).\nProof.\n intros.\n rewrite plus_comm.\n rewrite plus_comm.\n Check plus_comm.\n\n rewrite (plus_comm n m).\n (* rewrite (plus_comm p q). *)\n (* reflexivity. *)\n replace (p + q) with (q + p).\n reflexivity.\n apply plus_comm.\nQed.\n\n(* ************* *)\n(* 'Apply' and other tactic examples *)\n\nTheorem silly_ex : \n (forall n, evenb n = true -> oddb (S n) = true) ->\n evenb 3 = true ->\n oddb 4 = true.\nProof.\n (* intros. *)\n (* apply H. *)\n (* exact H0. *)\n\n intro H.\n (* apply H. *)\n exact (H 3).\nQed.\n\nTheorem silly3 : forall (n : nat),\n true = beq_nat n 5 ->\n beq_nat (S (S n)) 7 = true.\nProof.\n intros n H.\n\n symmetry.\n (* simpl. *) (* Actually, this [simpl] is unnecessary, since \n [apply] will do a [simpl] step first. *) \n apply H.\nQed.\n\n(* Reasoning in assumptions, aka forward reasoning. *)\nTheorem silly3' : forall (n : nat),\n (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->\n true = beq_nat n 5 ->\n true = beq_nat (S (S n)) 7.\nProof.\n intros n eq H.\n remember H as H1.\n clear HeqH1.\n symmetry in H. apply eq in H. symmetry in H. \n apply H.\nQed.\n\nTheorem plus_n_n_injective : forall n m,\n n + n = m + m ->\n n = m.\nProof.\n intros n. induction n as [| n'].\n (* Hint: use the plus_n_Sm lemma *)\n intros. destruct m as [| m']. reflexivity.\n simpl in H. discriminate H.\n\n intros. destruct m as [| m']. discriminate H.\n simpl in H. rewrite <- !plus_n_Sm in H. (* rewrite modifiers *)\n inversion H. apply IHn' in H1. rewrite H1. reflexivity.\nQed.\n\n\n(* Remember and destruct expression. *)\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n match reverse goal with\n | H : _ |- _ => try move x after H\n end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n let H := fresh in\n assert (x = v) as H by reflexivity;\n clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n first [\n set (x := name); move_to_top x\n | assert_eq x name; move_to_top x\n | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n\n\nTheorem bool_fn_applied_thrice : \n forall (f : bool -> bool) (b : bool), \n f (f (f b)) = f b.\nProof.\n intros f b.\n destruct b.\n Case \"b = true\".\n remember (f true) as ftrue.\n destruct ftrue.\n SCase \"f true = true\".\n rewrite <- Heqftrue.\n symmetry.\n apply Heqftrue.\n SCase \"f true = false\".\n remember (f false) as ffalse.\n destruct ffalse.\n SSCase \"f false = true\".\n symmetry.\n apply Heqftrue.\n SSCase \"f false = false\".\n symmetry.\n apply Heqffalse.\n remember (f false) as ffalse.\n destruct ffalse.\n SCase \"f false = true\".\n remember (f true) as ftrue.\n destruct ftrue.\n SSCase \"f true = true\".\n symmetry.\n apply Heqftrue.\n SSCase \"f true = false\".\n symmetry.\n apply Heqffalse.\n SCase \"f false = false\".\n rewrite <- Heqffalse.\n symmetry.\n apply Heqffalse.\nQed.\n\n(* HW *)\nTheorem bool_funcs : forall (f : bool -> bool),\n (forall b, f (f b) = f b) \\/ (forall b, f b = negb b).\nAdmitted.\n\nTheorem bool_fn_applied_thrice' : \n forall (f : bool -> bool) (b : bool), \n f (f (f b)) = f b.\nProof.\n intro f.\n destruct (bool_funcs f).\n intro.\n rewrite H.\n rewrite H.\n reflexivity.\n\n intro.\n rewrite !H.\n (* SearchAbout negb. *)\n rewrite Bool.negb_involutive.\n reflexivity.\nQed.\n\n(* Seminar 3 ended here. *)\n(* ********************************************************** *)\n(* Seminar 4 starts here. *)\n\n\nModule ExampleList1.\n\nInductive list (T : Type) : Type :=\n | nil : list T\n | cons : T -> list T -> list T.\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\nCheck (cons _ 2 (cons _ 1 (nil _))).\n\nCheck cons.\nCheck nil.\n\nEnd ExampleList1.\n\nModule ExampleList2.\n\nSet Implicit Arguments.\n\nInductive list (T : Type) : Type :=\n | nil\n | cons : T -> list T -> list T.\nPrint list.\n\nCheck (cons 2 (cons 1 (nil _))).\n\nImplicit Arguments nil [[T]].\n(* Deprecated, use: Arguments nil [T]. *)\n\nCheck (cons 2 (cons 1 nil)).\n\nCheck @nil nat.\n\nUnset Implicit Arguments.\n\n(* Fixpoint length {X:Type} (l:list X) : nat := *)\n(* match l with *)\n(* | nil => 0 *)\n(* | cons h t => S (length t) *)\n(* end. *)\n\nFixpoint length (X:Type) (l:list X) : nat :=\n match l with\n | nil => 0\n | cons h t => S (length X t)\n end.\nCheck length.\nImplicit Arguments length [[X]].\n\nEval compute in length (cons 2 (cons 1 nil)).\n\nCheck @length.\n\nNotation \"x :: y\" := (cons x y) \n (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y []) ..).\n\n(* Define app! *)\nFixpoint app {X : Type} (l1 l2 : list X) : list X :=\n match l1 with\n | [] => l2\n | h :: t => h :: app t l2\n end.\n\nNotation \"x ++ y\" := (app x y) \n (at level 60, right associativity).\n\n\nEval compute in [1,2,3] ++ 4::5::[].\n\nFixpoint repeat {X : Type} (x : X) (count : nat) : list X := \n match count with\n | O => nil\n | S c' => x :: repeat x c'\n end.\n\nEval compute in repeat true 3.\n\nTheorem repeat_length : forall n X (x : X), length (repeat x n) = n.\nProof.\n intros.\n pattern n.\n apply nat_ind.\n simpl. \n reflexivity.\n\n intros.\n simpl.\n rewrite <- H at 2.\n reflexivity.\nQed.\n\n(* Induction priciple for induction definition. *)\n\nCheck nat_ind.\nCheck list_ind.\n\nTheorem app_assoc : forall X (l1 l2 l3 : list X), l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\nProof.\n intros.\n induction l1.\n simpl.\n reflexivity.\n\n simpl.\n rewrite IHl1.\n reflexivity.\nQed.\n\n(* HW: trivial *)\nTheorem app_length : forall X (l1 l2 : list X), length (l1 ++ l2) = length l1 + length l2.\nAdmitted.\n\n(* HW: involved. What should the induction go on? *)\nTheorem app_length2 : forall X (l1 l2 : list X) n1 n2,\n length l1 = n1 -> length l2 = n2 -> length (l1 ++ l2) = n1 + n2.\nAdmitted.\n\n\nInductive vector (T : Type) : nat -> Type :=\n | nilv : vector T 0\n | consv n : T -> vector T n -> vector T (S n).\n\nImplicit Arguments nilv [[T]].\nImplicit Arguments consv [[T] [n]].\n\nCheck consv 1 (consv 2 nilv).\nCheck consv true (consv false nilv).\n\nDefinition lengthv {T : Type} {n : nat} (v : vector T n) : nat := n.\n\nFixpoint repeatv {X : Type} (x : X) (n : nat) : vector X n :=\n match n with\n | 0 => nilv\n | S n' => consv x (repeatv x n')\n end.\n\nTheorem lengthv_repeatv : forall n X (x : X), lengthv (repeatv x n) = n.\nProof.\n intros.\n reflexivity.\nQed.\n(* Show that simpl is not enough here, but compute is, or unfold. *)\n\nCheck @repeat.\n (* : forall X : Type, X -> nat -> list X *)\nCheck @repeatv.\n (* : forall X : Type, X -> forall n : nat, vector X n *)\n\n(* Relation of 'forall' and '->' *)\n\nParameter p q : Prop.\n\nPrint p.\n\nDefinition p_to_q := forall h : p, q.\n\nPrint p_to_q.\n\n\nCheck forall n : nat, bool.\n\nCheck forall n : nat, p.\n\n\nEnd ExampleList2.\n\nParameter A B : Prop.\n\nTheorem a_to_b_to_a : A -> B -> A.\nProof.\n intros.\n assumption.\n Show Proof.\nQed.\n\nDefinition a_to_b_to_a' : A -> B -> A := fun x => fun _ => x.\n\nCheck a_to_b_to_a.\nCheck a_to_b_to_a'.\n\nTheorem two_times_n_plus_3 : nat -> nat.\nProof.\n intros n.\n induction n.\n exact 3.\n\n exact (S (S IHn)).\n Show Proof.\nDefined.\n\nEval compute in two_times_n_plus_3 5.\n\nDefinition true_all : forall P : Prop, P -> True := fun _ => fun _ => I.\n\nTheorem true_all' : forall P : Prop, P -> True.\nProof.\n intros.\n trivial.\n Show Proof.\nQed.\n\nDefinition true_all'' (P : Prop) (H : P) := I.\n\nCheck true_all''.\n\nPrint False.\n\n(* Definition false_all : forall (P : Prop), False -> P := *)\n\nDefinition false_all (P : Prop) (H : False) : P :=\n match H with\n end.\n\nCheck false_all.\n\n(* Homework: hard! *)\nDefinition O_not_1 : not (eq O (S 0)).\n\nPrint not.\nPrint eq.\n \n", "meta": {"author": "klao", "repo": "coq-learning", "sha": "e408913099774f2390bd5541c1d438d3c835d803", "save_path": "github-repos/coq/klao-coq-learning", "path": "github-repos/coq/klao-coq-learning/coq-learning-e408913099774f2390bd5541c1d438d3c835d803/work_sheets/Seminar4firstrun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697695, "lm_q2_score": 0.908617890746506, "lm_q1q2_score": 0.8563784660961039}} {"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\nModule NatList.\n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as here: *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is one way to construct\n a pair of numbers: by applying the constructor [pair] to two\n arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n\n(** Here are two simple functions for extracting the first and\n second components of a pair. The definitions also illustrate how\n to do pattern matching on two-argument constructors. *)\n\nDefinition fst (p : natprod) : nat :=\n match p with\n | pair x y => x\n end.\n\nDefinition snd (p : natprod) : nat :=\n match p with\n | pair x y => y\n end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this works because the pair notation is actually\n provided as part of the standard library): *)\n\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n match p with\n | (x,y) => x\n end.\n\nDefinition snd' (p : natprod) : nat :=\n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n match p with\n | (x,y) => (y,x)\n end.\n\n(** Let's try to prove a few simple facts about pairs.\n\n If we state things in a particular (and slightly peculiar) way, we\n can complete proofs with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** Notice that, unlike its behavior with [nat]s, [destruct]\n doesn't generate an extra subgoal here. That's because [natprod]s\n can only be constructed in one way. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p. destruct p as [n m].\n simpl. reflexivity.\nQed. \n\n \n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros p. destruct p as [n m].\n simpl. reflexivity.\nQed.\n \n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n type of _lists_ of numbers like this: \"A list is either the empty\n list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n declarations, but in case you are interested, here is roughly\n what's going on. The [right associativity] annotation tells Coq\n how to parenthesize expressions involving several uses of [::] so\n that, for example, the next three declarations mean exactly the\n same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\n Notation \"x + y\" := (plus x y)\n (at level 50, left associativity).\n the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (By the way, it's worth noting in passing that expressions like \"[1\n + 2 :: [3]]\" can be a little confusing when you read them in a .v\n file. The inner brackets, around 3, indicate a list, but the outer\n brackets, which are invisible in the HTML rendering, are there to\n instruct the \"coqdoc\" tool that the bracketed part should be\n displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(** *** Repeat *)\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n\n(** *** Length *)\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(** *** Append *)\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(** *** Head (with default) and Tail *)\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\").\n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(** *** Exercises *)\n(** **** Exercise: 2 stars, recommended (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | nil => nil\n | x::xs => match x with\n | 0 => nonzeros xs\n | _ => x :: (nonzeros xs)\n end\n end.\n\n\nExample test_nonzeros:\n nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\n\nFixpoint oddmembers (l:natlist) : natlist := match l with\n | nil => nil\n | x::xs => match oddb x with\n | true => x::(oddmembers xs)\n | _ => oddmembers xs\n end\n end. \n \n\nExample test_oddmembers:\n oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat := length (oddmembers l).\n \nExample test_countoddmembers1:\n countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers2:\n countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers3:\n countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist := match l1,l2 with\n | nil , nil => nil\n | x::xs, nil => l1\n | nil , x::xs => l2 \n | x::xs, y::ys => x::y::(alternate xs ys)\n end. \n\n\nExample test_alternate1:\n alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. reflexivity. Qed.\n\nExample test_alternate2:\n alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\n\n\nExample test_alternate3:\n alternate [1;2;3] [4] = [1;4;2;3].\nProof. reflexivity. Qed.\n\n\nExample test_alternate4:\n alternate [] [20;30] = [20;30].\nProof. reflexivity. Qed.\n\n\n(* ###################################################### *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n can appear multiple times rather than just once. One possible\n implementation is to represent a bag of numbers as a list. *)\n\nDefinition bag := natlist.\n\n\n(** **** Exercise: 3 stars, recommended (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat := match s with\n | nil => 0\n | x::xs => if beq_nat x v\n then S (count v xs)\n else count v xs\n end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\n\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := app.\n\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := v :: s.\n\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\n\nDefinition member (v:nat) (s:bag) : bool :=\n match count v s with\n | O => false\n | _ => true\n end. \n\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\n (* When remove_one is applied to a bag without the number to remove,\n it should return the same bag unchanged. *)\nFixpoint remove_one (v:nat) (s:bag) : bag := match s with\n | nil => s\n | x::xs => match beq_nat x v with\n | true => xs\n | _ => x :: (remove_one v xs)\n end\n end. \n\n\nExample test_remove_one1:\n count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one2:\n count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\n\nExample test_remove_one3:\n count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\n\nExample test_remove_one4:\n count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity. Qed.\n\n\nFixpoint remove_all (v:nat) (s:bag) : bag := match s with\n | nil => s\n | x::xs => match beq_nat x v with\n | true => remove_all v xs\n | _ => x :: (remove_all v xs)\n end\n end. \n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. reflexivity. Qed.\n\n\n\n(* check if s1 subset of s2 *)\nFixpoint subset (s1:bag) (s2:bag) : bool := match s1 with\n | nil => true\n | x::xs => match (member x s2) with\n | true => subset xs (remove_one x s2)\n | _ => false\n end\n end. \n \nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity. Qed.\n\n\n(** **** Exercise: 3 stars, recommended (bag_theorem) *)\n(** Write down an interesting theorem [bag_theorem] about bags\n involving the functions [count] and [add], and prove it. For\n this, replace the [admit] command below with the statement of your\n theorem. Note that, since this problem is somewhat open-ended,\n it's possible that you may come up with a theorem which is true,\n but whose proof requires techniques you haven't learned yet. Feel\n free to ask for help if you get stuck! *)\n\n(*\n (count x ls) + 1 == count x (add x ls)\n*)\nTheorem bag_theorem : forall x : nat, forall l : bag,\n S (count x l) = count x (add x l).\nProof.\n intros x l. induction l as [|n l' IHl'].\n + simpl. induction x as [|x' IHx'].\n - simpl. reflexivity.\n - simpl. rewrite <- IHx'. reflexivity.\n + simpl. induction x as [|x' IHx'].\n - simpl. reflexivity.\n - simpl. induction n as [|n' IHn'].\n * simpl. rewrite <- beq_nat_refl. reflexivity.\n * simpl. rewrite <- beq_nat_refl. reflexivity.\nQed.\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match\n \"scrutinee\" in the definition of [app], allowing the match itself\n to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons n l' *)\n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ###################################################### *)\n(** *** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n It is important to work through the details of each one, using Coq\n and thinking about what each step achieves. Otherwise it is more\n or less guaranteed that the exercises will make no sense when you\n get to them. 'Nuff said. *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n little less familiar than standard natural number induction, but\n the idea is equally simple. Each [Inductive] declaration defines\n a set of data values that can be built up using the declared\n constructors: a boolean can be either [true] or [false]; a number\n can be either [O] or [S] applied to another number; a list can be\n either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two arguments together establish\n the truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons n l1' *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n [as...] clause provided to the [induction] tactic gives a name to\n the induction hypothesis corresponding to the smaller list [l1']\n in the [cons] case. Once again, this Coq proof is not especially\n illuminating as a static written document -- it is easy to see\n what's going on if you are reading the proof in an interactive Coq\n session and you can see the current goal and context at each\n point, but this state is not visible in the written-down parts of\n the Coq proof. So a natural-language proof -- one written for\n human readers -- will need to include more explicit signposts; in\n particular, it will help the reader stay oriented if we remind\n them exactly what the induction hypothesis is in the second\n case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n (the induction hypothesis). We must show\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n By the definition of [++], this follows from\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n which is immediate from the induction hypothesis. []\n*)\n\n(** *** Reversing a list *)\n(** For a slightly more involved example of inductive proof over\n lists, suppose we use [app] to define a list-reversing function\n [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => rev t ++ [h]\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** *** Proofs about reverse *)\n\n(** Now let's prove some theorems about our newly defined [rev].\n For something a bit more challenging than what we've seen, let's\n prove that reversing a list does not change its length. Our first\n attempt gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = [] *)\n reflexivity.\n - (* l = n :: l' *)\n (* This is the tricky case. Let's begin as usual\n by simplifying. *)\n simpl.\n (* Now we seem to be stuck: the goal is an equality\n involving [++], but we don't have any useful equations\n in either the immediate context or in the global\n environment! We can make a little progress by using\n the IH to rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n would have enabled us to make progress and prove it as a separate\n lemma.\n*)\n\nTheorem app_length : forall l1 l2 : natlist,\n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Note that, to make the lemma as general as possible, we\n quantify over _all_ [natlist]s, not just those that result from an\n application of [rev]. This should seem natural, because the truth\n of the goal clearly doesn't depend on the list having been\n reversed. Moreover, it is easier to prove the more general\n property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons *)\n simpl. rewrite -> app_length, plus_comm.\n rewrite -> IHl'. simpl. reflexivity.\nQed. \n \n\n(** For comparison, here are informal proofs of these two theorems:\n\n _Theorem_: For all lists [l1] and [l2],\n [length (l1 ++ l2) = length l1 + length l2].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n length ([] ++ l2) = length [] + length l2,\n which follows directly from the definitions of\n [length] and [++].\n\n - Next, suppose [l1 = n::l1'], with\n length (l1' ++ l2) = length l1' + length l2.\n We must show\n length ((n::l1') ++ l2) = length (n::l1') + length l2).\n This follows directly from the definitions of [length] and [++]\n together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (rev []) = length [],\n which follows directly from the definitions of [length]\n and [rev].\n\n - Next, suppose [l = n::l'], with\n length (rev l') = length l'.\n We must show\n length (rev (n :: l')) = length (n :: l').\n By the definition of [rev], this follows from\n length ((rev l') ++ [n]) = S (length l')\n which, by the previous lemma, is the same as\n length (rev l') + length [n] = S (length l').\n This follows directly from the induction hypothesis and the\n definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n After the first few, we might find it easier to follow proofs that\n give fewer details (which can easily work out in our own minds or\n on scratch paper if necessary) and just highlight the non-obvious\n steps. In this more compressed style, the above proof might look\n like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n for any [l] (this follows by a straightforward induction on [l]).\n The main property again follows by induction on [l], using the\n observation together with the induction hypothesis in the case\n where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for our\n present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, e.g., using [rewrite]. But in order to refer to a\n theorem, we need to know its name! Indeed, it is often hard even\n to remember what theorems have been proven, much less what they\n are called.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following to\n see a list of theorems that we have proved about [rev]: *)\n\n(* SearchAbout rev. *)\n\nSearchAbout rev.\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the book; it can save you a lot of time!\n\n If you are using ProofGeneral, you can run [SearchAbout] with [C-c\n C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n l ++ [] = l.\nProof.\n intros l. induction l as [|n l' IHl'].\n + simpl. reflexivity.\n + simpl. rewrite -> IHl'. reflexivity.\nQed.\n\n(* may be redundant as it follows from the def directly \nTheorem cons_app_equiv : forall l : natlist, forall x : nat,\n x::l = [x] ++ l.\nProof. \n intros l x. induction l.\n + simpl. reflexivity.\n + simpl. reflexivity.\nQed. \n*)\n\n(*\n question: how do you use variable declaration in proofs?\n*)\nTheorem rev_distrb : forall l1 : natlist, forall l2 : natlist,\n rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n intros l1 l2.\n induction l1 as [|n l1' IHl1'].\n + simpl. rewrite -> app_nil_r. reflexivity.\n + simpl. rewrite -> IHl1'. rewrite -> app_assoc. reflexivity.\nQed. \n\n \n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros l. induction l as [|x l' IHl'].\n + simpl. reflexivity.\n + simpl. rewrite -> rev_distrb. simpl. rewrite -> IHl'. reflexivity.\nQed.\n \n \n\n(** There is a short solution to the next one. If you find yourself\n getting tangled up, step back and try to look for a simpler\n way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros l1 l2 l3 l4.\n rewrite -> app_assoc. rewrite -> app_assoc.\n reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros l1 l2.\n induction l1 as [|x l1' IHl1'].\n + simpl. reflexivity.\n + simpl. rewrite -> IHl1'. destruct x.\n - reflexivity.\n - simpl. reflexivity.\nQed.\n\n \n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n match l1, l2 with\n | nil, nil => true\n | cons _ _, nil => false\n | nil, cons _ _ => false\n | cons x xs, cons y ys => match beq_nat x y with\n | true => beq_natlist xs ys\n | _ => false\n end \n end. \n \n \n\nExample test_beq_natlist1 :\n (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\n \nExample test_beq_natlist2 :\n beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\nExample test_beq_natlist3 :\n beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\n intros l. induction l as [|n l' IHl'].\n + simpl. reflexivity.\n + simpl. induction n as [|n' IHn'].\n - simpl. rewrite <- IHl'. reflexivity.\n - simpl. rewrite <- IHn'. reflexivity.\nQed. \n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n definitions about bags earlier in the file. *)\n\n(* 1 <= count 1 (1::s) *)\nTheorem count_member_nonzero : forall (s : bag),\n leb 1 (count 1 (1 :: s)) = true.\nProof.\n intros s. induction s as [|n s' IHs'].\n + simpl. reflexivity.\n + simpl. reflexivity.\nQed. \n\n(** The following lemma about [leb] might help you in the next proof. *)\n\n(* n < S n*)\nTheorem ble_n_Sn : forall n,\n leb n (S n) = true.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* 0 *)\n simpl. reflexivity.\n - (* S n' *)\n simpl. rewrite IHn'. reflexivity. Qed.\n\n(* count 0 (remove_one 0 s) <= count 0 s *)\nTheorem remove_decreases_count: forall (s : bag),\n leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n intros s. induction s as [|n s' IHs'].\n + simpl. reflexivity.\n + simpl. induction n as [|n' IHn'].\n - simpl. rewrite -> ble_n_Sn. reflexivity.\n - simpl. rewrite <- IHs'. reflexivity.\nQed.\n\n\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *)\n(** Write down an interesting theorem [bag_count_sum] about bags\n involving the functions [count] and [sum], and prove it.*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective -- that is,\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n(There is a hard way and an easy way to do this.)\n*)\n\nFact rev_list_of_one : forall n : nat,\n rev [n] = [n].\nProof. intros n. simpl. reflexivity. Qed.\n\nFact cons_app_equiv : forall n : nat, forall l : natlist,\n [n] ++ l = n :: l. \nProof. intros n l. simpl. reflexivity. Qed.\n\n\nTheorem rev_injective : forall (l1 l2 : natlist),\n rev l1 = rev l2 -> l1 = l2.\nProof.\n intros l1 l2 H.\n rewrite <- rev_involutive.\n rewrite <- H.\n rewrite -> rev_involutive.\n reflexivity.\nQed.\n\n(*\n in class quiz\n\nTheorem foo2 : forall n m : nat, forall l : natlist,\n repeat n m = l -> length l = m.\nProof.\n intros n m l H.\n induction m as [|m' IHm'].\n + rewrite <- H. simpl. reflexivity.\n + destruct l.\n - inversion H.\n - inversion H.\n*)\n \n\n(* ###################################################### *)\n(** * Options *)\n\n\n(** Suppose we want to write a function that returns the [n]th\n element of some list. If we give it type [nat -> natlist -> nat],\n then we'll have to choose some number to return when the list is\n too short...\n *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with\n | true => a\n | false => nth_bad l' (pred n)\n end\n end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n can't tell whether that value actually appears on the input\n without further processing. A better alternative is to change the\n return type of [nth_bad] to include an error value as a possible\n outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption.\n\n(** We can then change the above definition of [nth_bad] to\n return [None] when the list is too short and [Some a] when the\n list has enough members and [a] appears at position [n]. We call\n this new function [nth_error] to indicate that it may result in an\n error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => match beq_nat n O with\n | true => Some a\n | false => nth_error l' (pred n)\n end\n end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n small feature of Coq's programming language: conditional\n expressions... *)\n\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => if beq_nat n O then Some a\n else nth_error' l' (pred n)\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_error) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_error (l : natlist) : natoption :=\n match l with\n | nil => None\n | cons x _ => Some x\n end. \n\n\nExample test_hd_error1 : hd_error [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n\n\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_error l).\nProof.\n intros l default. induction l as [|n l' IHl'].\n + simpl. reflexivity.\n + simpl. reflexivity.\nQed.\n \n\nEnd NatList.\n\n(* ###################################################### *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n Coq, here is a simple _partial map_ data type, analogous to the\n map or dictionary data structures found in most programming\n languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n | Id : nat -> id.\n\n(** Internally, an [id] is just a number. Introducing a separate type\n by wrapping each nat with the tag [Id] makes definitions more\n readable and gives us the flexibility to change representations\n later if we wish.\n\n We'll also need an equality test for [id]s: *)\n\nDefinition extract_id (i : id) : nat := match i with\n | Id n => n\n end.\n\nTheorem extract_id_n : forall n : nat,\n extract_id (Id n) = n.\nProof. intros n. simpl. reflexivity. Qed.\n\n\nDefinition beq_id x1 x2 :=\n match x1, x2 with\n | Id n1, Id n2 => beq_nat n1 n2\n end.\n\n(** **** Exercise: 1 star (beq_id_refl) *)\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n intros x. destruct x. simpl. induction n as [|n' IHn'].\n + simpl. reflexivity.\n + simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem beq_id_equiv : forall n : nat,\n beq_id (Id n) (Id n) = beq_nat n n. \nProof. intros n. simpl. reflexivity. Qed.\n \n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nImport NatList.\n \nInductive partial_map : Type :=\n | empty : partial_map\n | record : id -> nat -> partial_map -> partial_map.\n\n(** This declaration can be read: \"There are two ways to construct a\n [partial_map]: either using the constructor [empty] to represent an\n empty partial map, or by applying the constructor [record] to\n a key, a value, and an existing [partial_map] to construct a\n [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n partial map (or adds a new entry if the given key is not already\n present). *)\n\nDefinition update (d : partial_map)\n (key : id) (value : nat)\n : partial_map :=\n record key value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n key. It returns [None] if the key was not found and [Some val] if\n the key was associated with [val]. If the same key is mapped to\n multiple values, [find] will return the first one it\n encounters. *)\n\nFixpoint find (key : id) (d : partial_map) : natoption :=\n match d with\n | empty => None\n | record k v d' => if beq_id key k\n then Some v\n else find key d'\n end.\n\n\n(** **** Exercise: 1 star (update_eq) *)\nTheorem update_eq :\n forall (d : partial_map) (k : id) (v: nat),\n find k (update d k v) = Some v.\nProof.\n intros d k v. induction d.\n + simpl. destruct k. induction n as [|n' IHn'].\n - simpl. reflexivity.\n - simpl. rewrite <- beq_id_equiv. rewrite -> IHn'. reflexivity.\n + simpl. destruct k as [x]. induction n as [|n' IHn'].\n - simpl. rewrite <- beq_nat_refl. reflexivity.\n - simpl. rewrite <- beq_nat_refl. reflexivity.\nQed.\n\n\n\n(** **** Exercise: 1 star (update_neq) *)\nTheorem update_neq :\n forall (d : partial_map) (m n : id) (o: nat),\n beq_id m n = false -> find m (update d n o) = find m d.\nProof.\n intros d m n o H.\n induction d.\n + simpl. rewrite -> H. reflexivity.\n + simpl. rewrite -> H. reflexivity.\nQed. \n\n\nEnd PartialMap.\n\n(** **** Exercise: 2 stars (baz_num_elts) *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n | Baz1 : baz -> baz\n | Baz2 : baz -> bool -> baz.\n\n\n(** How _many_ elements does the type [baz] have?\n\n(* FILL IN HERE *)\n\n [baz] is not inhabited so it has no elements. In order to construct\n some [Baz1], we need some [x : baz], but we do not have this type.\n Similarly to construct [Baz2], we need some term of type [baz],\n which we do not have. \n\n*)\n\n\n\n(** $Date: 2016-01-13 11:14:59 -0500 (Wed, 13 Jan 2016) $ *)\n", "meta": {"author": "lingxiao", "repo": "CIS500", "sha": "5b6e3a9cfe1ecaeaa9112b350022f3ca84924d4a", "save_path": "github-repos/coq/lingxiao-CIS500", "path": "github-repos/coq/lingxiao-CIS500/CIS500-5b6e3a9cfe1ecaeaa9112b350022f3ca84924d4a/hw2/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.9372107843878721, "lm_q1q2_score": 0.8563074977942783}} {"text": "Inductive nat : Set :=\n | zero : nat\n | succ : nat -> nat.\n\nFixpoint add (a b: nat): nat :=\n match a with\n | zero => b\n | succ n => succ (add n b)\n end.\n\nTheorem add_zero: forall a : nat, add a zero = a.\nProof.\n intros a.\n induction a as [ | a Ha].\n + simpl; reflexivity.\n + simpl; rewrite Ha; reflexivity.\nQed. \n\nTheorem add_succ: forall a b : nat, succ (add a b) = add a (succ b).\nProof.\n intros a b.\n elim a.\n - simpl; trivial.\n - intros n Ha. simpl. rewrite Ha. trivial.\nQed.\n\nTheorem add_sym: forall a b: nat, add a b = add b a.\nProof.\n intros a b.\n induction a.\n + simpl. pose (add_zero b) as H. rewrite H. trivial. \n + simpl. rewrite IHa. exact (add_succ b a).\nQed.\n\nTheorem add_assoc: forall a b c: nat, add a (add b c) = add (add a b) c.\nProof.\n intros a b.\n elim a.\n - intros c. simpl. trivial.\n - intros n H1 c. simpl. rewrite (H1 c). trivial.\nQed.\n\n\n", "meta": {"author": "QuangTung97", "repo": "coq", "sha": "eceb86794d73475caa662d200c532a026b1335e0", "save_path": "github-repos/coq/QuangTung97-coq", "path": "github-repos/coq/QuangTung97-coq/coq-eceb86794d73475caa662d200c532a026b1335e0/Simple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305339244013, "lm_q2_score": 0.8887587817066392, "lm_q1q2_score": 0.8560795958332865}} {"text": "(* Solution for exercieses in Tsinghua Coq Summber School.\n Exercise for leture 2: Datatypes, pattern-matching, and recursion by Yves Bertot. *)\nSection Exercise_2_Work.\n\nRequire Import List.\nRequire Import ZArith.\n\n(* Define a datatype of binary trees where non-atomic nodes have only two\n components which are binary trees, and only atomic nodes carry an integer\n value. Include a case for empty trees. *)\n\nInductive PolymorphicBalancedTree (A : Type) : Type :=\n | Empty\n | Atomic (value : A)\n | Branch (l : PolymorphicBalancedTree A) (r : PolymorphicBalancedTree A).\n\nImplicit Arguments Empty [A].\nImplicit Arguments Atomic [A].\nImplicit Arguments Branch [A].\n\n(* Option type as a polymorphic datatype. *)\nInductive option (A : Type) : Type :=\n | Some : A -> option A\n | None : option A.\n\nInductive ZBalancedTree : Type :=\n | ZEmpty\n | ZAtomic (value : Z)\n | ZBranch (l : ZBalancedTree) (r : ZBalancedTree).\n\n(* Define a function that takes a list as input and constructs a balanced\n binary tree carrying the same values. The trick is to interchange the\n the two components of each node after inserting an integer into the first\n node. *)\n\nInductive NatBalancedTree : Type :=\n | NatEmpty\n | NatAtomic (value : nat)\n | NatBranch (l : NatBalancedTree) (r : NatBalancedTree).\n\nFixpoint nat_ge_bool_local (n m : nat): bool :=\n match n, m with\n | _, O => true\n | O, S _ => false\n | S a, S b => nat_ge_bool_local a b\n end.\n\nFixpoint nat_le_bool_local (n m : nat) : bool :=\n match n, m with\n | O, _ => true\n | S _, O => false\n | S a, S b => nat_le_bool_local a b\n end.\n\nFixpoint maximum_val (t : NatBalancedTree) : nat :=\n match t with\n | NatEmpty => O\n | NatAtomic v => v\n | NatBranch l r =>\n if (nat_ge_bool_local (maximum_val l) (maximum_val r))\n then maximum_val l\n else maximum_val r\n end.\n\nFixpoint insert_element (x : nat) (t : NatBalancedTree) : NatBalancedTree :=\n match t with\n | NatEmpty => NatAtomic x\n | NatAtomic val => NatBranch (NatAtomic x) (NatAtomic val)\n | NatBranch l r =>\n if (nat_le_bool_local x (maximum_val l))\n then NatBranch (insert_element x l) r\n else NatBranch l (insert_element x r)\n end.\n\nFixpoint construct_tree (xs : list nat) : NatBalancedTree :=\n match xs with\n | nil => NatEmpty\n | cons x rest => insert_element x (construct_tree rest)\n end.\n\n(* Define a function with three arguments: a natural number and two\n lists, which builds a new list by always taking the least element\n of the heads of the two lists. The length of the resulting list should\n be the natural number given as first input (if the two lists are long enough).\n\n This is a merge function as in the \"merge sort\" algorithm, except that the\n natural number argument should be the sum of the lengths of the two input\n lists.\n*)\n\nFixpoint merge_nat_list_n (n : nat) (us : list nat) (vs : list nat) : list nat :=\n match n with\n | O => nil\n | S p =>\n match us, vs with\n | cons a uss, cons b vss =>\n if (nat_le_bool_local a b)\n then a :: merge_nat_list_n p uss vs\n else b :: merge_nat_list_n p us vss\n | cons _ _, nil => us\n | nil, cons _ _ => vs\n | nil, nil => nil\n end\n end.\n\n(* Define a function that merges two lists bu first computing the sum of their\n lengths and then calling the previous function. *)\n\nDefinition merge_nat_list (us vs : list nat) : list nat :=\n merge_nat_list_n (length us + length vs) us vs.\n\n(* Eval compute in merge_nat_list (1::3::5::7::9::nil) (2::4::6::8::10::nil). *)\n\n(* Define a recursive function on binary trees which returns a sorted list:\n - on empty trees it returns the empty list\n - on leaf treeas carrying one value, it returns a singleton list\n - on binary nodes, it returns the merge of the two sorted lists obtained\n from the sub-components. *)\n\nFixpoint destruct_tree (t : NatBalancedTree) : list nat :=\n match t with\n | NatEmpty => nil\n | NatAtomic v => v::nil\n | NatBranch l r => merge_nat_list (destruct_tree l) (destruct_tree r)\n end.\n\n(* Eval compute in destruct_tree (construct_tree (1::3::5::7::9::2::4::6::8::10::nil)). *)\n\n(* Define a function that sorts a list by first constructing a balanced binary\n tree and then by calling the function above. *)\n\nFixpoint sort_via_tree (xs : list nat) : list nat :=\n destruct_tree (construct_tree xs).\n\n(* Eval compute in sort_via_tree (1::3::5::7::9::2::4::6::8::10::nil). *)\n\nEnd Exercise_2_Work.\n", "meta": {"author": "sighingnow", "repo": "amazing-coq", "sha": "70acce0bac267f76f696b0f0a35865622b6a0ee8", "save_path": "github-repos/coq/sighingnow-amazing-coq", "path": "github-repos/coq/sighingnow-amazing-coq/amazing-coq-70acce0bac267f76f696b0f0a35865622b6a0ee8/tsinghua-coq-summer-school/solutions/exercises_2_work.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390752, "lm_q2_score": 0.9099070151996071, "lm_q1q2_score": 0.8560311972100488}} {"text": "(** * Lists: Working with Structured Data *)\n\nFrom LF Require Export Induction.\nModule NatList.\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as here: *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n(** Here are simple functions for extracting the first and\n second components of a pair. The definitions also illustrate how\n to do pattern matching on two-argument constructors. *)\n\nDefinition fst (p : natprod) : nat :=\n match p with\n | pair x y => x\n end.\n\nDefinition snd (p : natprod) : nat :=\n match p with\n | pair x y => y\n end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new pair notation can be used both in expressions and in\n pattern matches (indeed, we've actually seen this already in the\n [Basics] chapter, in the definition of the [minus] function --\n this works because the pair notation is also provided as part of\n the standard library): *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n match p with\n | (x,y) => x\n end.\n\nDefinition snd' (p : natprod) : nat :=\n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n match p with\n | (x,y) => (y,x)\n end.\n\n(** Let's try to prove a few simple facts about pairs.\n\n If we state things in a slightly peculiar way, we can complete\n proofs with just reflexivity (and its built-in simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** Notice that, unlike its behavior with [nat]s, [destruct]\n generates just one subgoal here. That's because [natprod]s can\n only be constructed in one way. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p.\n destruct p as [n m].\n simpl.\n reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros p.\n destruct p as [n m].\n simpl.\n reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n type of _lists_ of numbers like this: \"A list is either the empty\n list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n declarations, but in case you are interested, here is roughly\n what's going on. The [right associativity] annotation tells Coq\n how to parenthesize expressions involving several uses of [::] so\n that, for example, the next three declarations mean exactly the\n same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\n\n Notation \"x + y\" := (plus x y)\n (at level 50, left associativity).\n\n the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n you read them in a [.v] file. The inner brackets, around 3, indicate\n a list, but the outer brackets, which are invisible in the HTML\n rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n part should be displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head (with default) and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\").\n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, recommended (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | nil => []\n | 0 :: t => nonzeros t\n | h :: t => h :: (nonzeros t)\n end.\n\n\nExample test_nonzeros:\n nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. simpl. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | nil => []\n | h :: t =>\n if oddb h then h :: (oddmembers t)\n else oddmembers t\n end.\n\nExample test_oddmembers:\n oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. simpl. reflexivity. Qed.\n\nDefinition countoddmembers (l:natlist) : nat :=\n length (oddmembers l).\n\nExample test_countoddmembers1:\n countoddmembers [1;0;3;1;4;5] = 4.\nProof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers2:\n countoddmembers [0;2;4] = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers3:\n countoddmembers nil = 0.\nProof. simpl. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l1 with\n | [] => l2\n | h1 :: t1 => match l2 with\n | [] => l1\n | h2 :: t2 => h1 :: h2 :: (alternate t1 t2)\n end\n end.\n\nExample test_alternate1:\n alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate2:\n alternate [1] [4;5;6] = [1;4;5;6].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate3:\n alternate [1;2;3] [4] = [1;4;2;3].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate4:\n alternate [] [20;30] = [20;30].\nProof. simpl. reflexivity. Qed.\n\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n can appear multiple times rather than just once. One possible\n implementation is to represent a bag of numbers as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, recommended (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat :=\n match s with\n | [] => O\n | h :: t =>\n if beq_nat v h then S (count v t)\n else count v t\n end.\n \n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. simpl. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. simpl. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n the elements of [a] and of [b]. (Mathematicians usually define\n [union] on multisets a little bit differently -- using max instead\n of sum -- which is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\n\nDefinition add : nat -> bag -> bag := cons.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n if beq_nat O (count v s) then false\n else true.\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_member2: member 2 [1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more [bag] functions for you to practice with. *)\n\n(** When [remove_one] is applied to a bag without the number to remove,\n it should return the same bag unchanged. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n match s with\n | [] => []\n | h :: t => \n if beq_nat v h then t\n else h :: remove_one v t\n end.\n\nExample test_remove_one1:\n count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_one2:\n count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_one3:\n count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_one4:\n count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. simpl. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with\n | [] => []\n | h :: t =>\n if beq_nat v h then (remove_all v t)\n else h :: (remove_all v t)\n end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. simpl. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n match s1 with\n | [] => true\n | h :: t =>\n if beq_nat O (count h s2) then false\n else subset t (remove_one h s2)\n end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. simpl. reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_bag_theorem : option (prod nat string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (bag_theorem) *)\n(** Write down an interesting theorem [bag_theorem] about bags\n involving the functions [count] and [add], and prove it. Note\n that, since this problem is somewhat open-ended, it's possible\n that you may come up with a theorem which is true, but whose proof\n requires techniques you haven't learned yet. Feel free to ask for\n help if you get stuck! *)\n\nTheorem bag_theorem : forall (p : bag), forall (n : nat),\n S (length p) = length (add n p).\nProof.\n intros p n.\n reflexivity.\nQed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ...because the [[]] is substituted into the\n \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n the match) in the definition of [app], allowing the match itself\n to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons n l' *)\n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n It is important to work through the details of each one, using Coq\n and thinking about what each step achieves. Otherwise it is more\n or less guaranteed that the exercises will make no sense when you\n get to them. 'Nuff said. *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n little less familiar than standard natural number induction, but\n the idea is equally simple. Each [Inductive] declaration defines\n a set of data values that can be built up using the declared\n constructors: a boolean can be either [true] or [false]; a number\n can be either [O] or [S] applied to another number; a list can be\n either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two arguments together establish\n the truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons n l1' *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n [as...] clause provided to the [induction] tactic gives a name to\n the induction hypothesis corresponding to the smaller list [l1']\n in the [cons] case. Once again, this Coq proof is not especially\n illuminating as a static written document -- it is easy to see\n what's going on if you are reading the proof in an interactive Coq\n session and you can see the current goal and context at each\n point, but this state is not visible in the written-down parts of\n the Coq proof. So a natural-language proof -- one written for\n human readers -- will need to include more explicit signposts; in\n particular, it will help the reader stay oriented if we remind\n them exactly what the induction hypothesis is in the second\n case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n (the induction hypothesis). We must show\n\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n By the definition of [++], this follows from\n\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n which is immediate from the induction hypothesis. [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n lists, suppose we use [app] to define a list-reversing function\n [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => rev t ++ [h]\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Properties of [rev] *)\n\n(** Now let's prove some theorems about our newly defined [rev].\n For something a bit more challenging than what we've seen, let's\n prove that reversing a list does not change its length. Our first\n attempt gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = [] *)\n reflexivity.\n - (* l = n :: l' *)\n (* This is the tricky case. Let's begin as usual\n by simplifying. *)\n simpl.\n (* Now we seem to be stuck: the goal is an equality\n involving [++], but we don't have any useful equations\n in either the immediate context or in the global\n environment! We can make a little progress by using\n the IH to rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n would have enabled us to make progress and state it as a separate\n lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Note that, to make the lemma as general as possible, we\n quantify over _all_ [natlist]s, not just those that result from an\n application of [rev]. This should seem natural, because the truth\n of the goal clearly doesn't depend on the list having been\n reversed. Moreover, it is easier to prove the more general\n property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons *)\n simpl. rewrite -> app_length, plus_comm.\n simpl. rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n _Theorem_: For all lists [l1] and [l2],\n [length (l1 ++ l2) = length l1 + length l2].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n length ([] ++ l2) = length [] + length l2,\n\n which follows directly from the definitions of\n [length] and [++].\n\n - Next, suppose [l1 = n::l1'], with\n\n length (l1' ++ l2) = length l1' + length l2.\n\n We must show\n\n length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n This follows directly from the definitions of [length] and [++]\n together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n\n length (rev []) = length [],\n\n which follows directly from the definitions of [length]\n and [rev].\n\n - Next, suppose [l = n::l'], with\n\n length (rev l') = length l'.\n\n We must show\n\n length (rev (n :: l')) = length (n :: l').\n\n By the definition of [rev], this follows from\n\n length ((rev l') ++ [n]) = S (length l')\n\n which, by the previous lemma, is the same as\n\n length (rev l') + length [n] = S (length l').\n\n This follows directly from the induction hypothesis and the\n definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n After the first few, we might find it easier to follow proofs that\n give fewer details (which can easily work out in our own minds or\n on scratch paper if necessary) and just highlight the non-obvious\n steps. In this more compressed style, the above proof might look\n like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n for any [l] (this follows by a straightforward induction on [l]).\n The main property again follows by induction on [l], using the\n observation together with the induction hypothesis in the case\n where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for our\n present purposes. *)\n\n\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, e.g., using [rewrite]. But in order to refer to a\n theorem, we need to know its name! Indeed, it is often hard even\n to remember what theorems have been proven, much less what they\n are called.\n\n Coq's [Search] command is quite helpful with this. Typing\n [Search foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following line\n to see a list of theorems that we have proved about [rev]: *)\n\nSearch rev.\n\n(** Keep [Search] in mind as you do the following exercises and\n throughout the rest of the book; it can save you a lot of time!\n\n If you are using ProofGeneral, you can run [Search] with [C-c\n C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n l ++ [] = l.\nProof.\n intros l.\n induction l as [|n l' IHl].\n - (* l = nil *) reflexivity.\n - (* l = cons n l' *) simpl. rewrite -> IHl. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n intros l1 l2.\n induction l1 as [|n l1' IHl].\n - (* l1 = nil *) simpl.\n destruct l2 as [|m l2'].\n + (* l2 = nil *) reflexivity.\n + (* l2 = m :: l2' *)\n simpl.\n rewrite -> app_assoc.\n rewrite -> app_nil_r.\n reflexivity.\n - (* l1 = n :: l1' *)\n simpl. rewrite -> IHl. rewrite -> app_assoc.\n reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros l.\n induction l as [|n l' IHl].\n - (* l = nil *) reflexivity.\n - (* l = n :: l' *) simpl.\n rewrite -> rev_app_distr, IHl.\n reflexivity.\nQed.\n\n(** There is a short solution to the next one. If you find yourself\n getting tangled up, step back and try to look for a simpler\n way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros l1 l2 l3 l4.\n rewrite -> app_assoc, app_assoc.\n reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros l1 l2.\n induction l1 as [|n l1' IHl1].\n - (* l1 = nil *) reflexivity.\n - (* l1 = n :: l1' *)\n destruct n as [|n'].\n + (* n = O *) simpl. rewrite <- IHl1. reflexivity.\n + (* n = S n' *) simpl. rewrite <- IHl1. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n match l1, l2 with\n | [], [] => true\n | _, [] => false\n | [], _ => false\n | h1 :: t1, h2 :: t2 =>\n if beq_nat h1 h2 then beq_natlist t1 t2\n else false\n end.\n\nExample test_beq_natlist1 :\n (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\n\nExample test_beq_natlist2 :\n beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\nExample test_beq_natlist3 :\n beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof. \n intros l.\n induction l as [|n l' IHl].\n - (* l = nil *) reflexivity.\n - (* l = n :: l' *) simpl.\n induction n as [|n' IHn].\n + (* n = O *) simpl. rewrite <- IHl. reflexivity.\n + (* n = S n' *) simpl. rewrite <- IHn. reflexivity.\nQed.\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** Here are a couple of little theorems to prove about your\n definitions about bags above. *)\n\n(** **** Exercise: 1 star (count_member_nonzero) *)\nTheorem count_member_nonzero : forall (s : bag),\n leb 1 (count 1 (1 :: s)) = true.\nProof.\n reflexivity.\nQed.\n(** [] *)\n\n(** The following lemma about [leb] might help you in the next exercise. *)\n\nTheorem ble_n_Sn : forall n,\n leb n (S n) = true.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* 0 *)\n simpl. reflexivity.\n - (* S n' *)\n simpl. rewrite IHn'. reflexivity. Qed.\n\n(** **** Exercise: 3 stars, advanced (remove_does_not_increase_count) *)\n\nTheorem remove_does_not_increase_count: forall (s : bag),\n leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n intros s.\n induction s as [|n s' IHs].\n - (* s = nil *) reflexivity.\n - (* s = n :: s' *)\n simpl.\n destruct n as [|n'].\n + (* n = 0 *) rewrite -> ble_n_Sn. reflexivity.\n + (* n = S n' *) simpl. rewrite -> IHs. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *)\n(** Write down an interesting theorem [bag_count_sum] about bags\n involving the functions [count] and [sum], and prove it using\n Coq. (You may find that the difficulty of the proof depends on\n how you defined [count]!) *)\n(*\nTheorem bag_count_sum : forall (s1 s2 : bag), forall (n : nat),\n count n s1 + count n s2 = count n (sum s1 s2).\nProof.\n intros s1 s2 n.\n induction s1 as [|m s1' IHs1].\n - (* s1 = nil *) reflexivity.\n - (* s1 = m :: s1' *) simpl. rewrite <- IHs1.\nAbort.\n*)\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective -- that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\n (There is a hard way and an easy way to do this.) *)\n\nTheorem rev_injective : forall (l1 l2 : natlist),\n rev l1 = rev l2 -> l1 = l2.\nProof.\n intros l1 l2 H.\n rewrite <- rev_involutive.\n rewrite <- H.\n rewrite -> rev_involutive.\n reflexivity.\nQed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_rev_injective : option (prod nat string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n element of some list. If we give it type [nat -> natlist -> nat],\n then we'll have to choose some number to return when the list is\n too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with\n | true => a\n | false => nth_bad l' (pred n)\n end\n end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n can't tell whether that value actually appears on the input\n without further processing. A better alternative is to change the\n return type of [nth_bad] to include an error value as a possible\n outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption.\n\n(** We can then change the above definition of [nth_bad] to\n return [None] when the list is too short and [Some a] when the\n list has enough members and [a] appears at position [n]. We call\n this new function [nth_error] to indicate that it may result in an\n error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => match beq_nat n O with\n | true => Some a\n | false => nth_error l' (pred n)\n end\n end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n examples are elided. Click on a box if you want to see one.)\n\n This example is also an opportunity to introduce one more small\n feature of Coq's programming language: conditional\n expressions... *)\n\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => if beq_nat n O then Some a\n else nth_error' l' (pred n)\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually supports conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_error) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_error (l : natlist) : natoption :=\n match l with\n | [] => None\n | h :: _ => Some h\n end.\n\n\nExample test_hd_error1 : hd_error [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_error l).\nProof.\n intros l default.\n induction l as [| n l' IHl].\n - (* l = nil *) reflexivity.\n - (* l = n :: l' *) reflexivity.\nQed.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n Coq, here is a simple _partial map_ data type, analogous to the\n map or dictionary data structures found in most programming\n languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n | Id : nat -> id.\n\n(** Internally, an [id] is just a number. Introducing a separate type\n by wrapping each nat with the tag [Id] makes definitions more\n readable and gives us the flexibility to change representations\n later if we wish. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition beq_id (x1 x2 : id) :=\n match x1, x2 with\n | Id n1, Id n2 => beq_nat n1 n2\n end.\n\n(** **** Exercise: 1 star (beq_id_refl) *)\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n intros x.\n destruct x as [x'].\n simpl.\n rewrite <- beq_nat_refl.\n reflexivity.\nQed.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n \nInductive partial_map : Type :=\n | empty : partial_map\n | record : id -> nat -> partial_map -> partial_map.\n\n(** This declaration can be read: \"There are two ways to construct a\n [partial_map]: either using the constructor [empty] to represent an\n empty partial map, or by applying the constructor [record] to\n a key, a value, and an existing [partial_map] to construct a\n [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n partial map by shadowing it with a new one (or simply adds a new\n entry if the given key is not already present). *)\n\nDefinition update (d : partial_map)\n (x : id) (value : nat)\n : partial_map :=\n record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n key. It returns [None] if the key was not found and [Some val] if\n the key was associated with [val]. If the same key is mapped to\n multiple values, [find] will return the first one it\n encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n match d with\n | empty => None\n | record y v d' => if beq_id x y\n then Some v\n else find x d'\n end.\n\n\n(** **** Exercise: 1 star (update_eq) *)\nTheorem update_eq :\n forall (d : partial_map) (x : id) (v: nat),\n find x (update d x v) = Some v.\nProof.\n intros d x v.\n simpl.\n rewrite <- beq_id_refl.\n reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star (update_neq) *)\nTheorem update_neq :\n forall (d : partial_map) (x y : id) (o: nat),\n beq_id x y = false -> find x (update d y o) = find x d.\nProof.\n intros d x y o H.\n simpl.\n rewrite -> H.\n reflexivity.\nQed.\n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 stars (baz_num_elts) *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n | Baz1 : baz -> baz\n | Baz2 : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have?\n (Explain your answer in words, preferrably English.) *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_baz_num_elts : option (prod nat string) := None.\n(** [] *)\n\n\n", "meta": {"author": "neshkeev", "repo": "Logical-Foundations", "sha": "f529036b8e483f1beb737386c02fc5d18e6deae2", "save_path": "github-repos/coq/neshkeev-Logical-Foundations", "path": "github-repos/coq/neshkeev-Logical-Foundations/Logical-Foundations-f529036b8e483f1beb737386c02fc5d18e6deae2/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.9230391648332472, "lm_q1q2_score": 0.8559926400577486}} {"text": "Require Export D.\n\n\n\n(** **** Exercise: 3 stars (all_forallb) *)\n(** Inductively define a property [all] of lists, parameterized by a\n type [X] and a property [P : X -> Prop], such that [all X P l]\n asserts that [P] is true for every element of the list [l]. *)\n\nInductive all {X : Type} (P : X -> Prop) : list X -> Prop :=\n|all_nil : all P []\n|all_cons : forall hd tl, P hd -> all P tl -> all P (hd::tl)\n.\n\n(** Recall the function [forallb], from the exercise\n [forall_exists_challenge] in chapter [Poly]: *)\n\nPrint forallb.\n\n(** Using the property [all], write down a specification for [forallb],\n and prove that it satisfies the specification. Try to make your \n specification as precise as possible.\n\n Are there any important properties of the function [forallb] which\n are not captured by your specification? *)\n\nExample test_all_1: all (fun x => x = 1) [1; 1].\nProof. apply all_cons. reflexivity. apply all_cons. reflexivity. apply all_nil. Qed.\n\nTheorem forallb_correct: forall X (P: X -> bool) l,\n forallb P l = true <-> all (fun x => P x = true) l.\nProof.\n intros. split.\n Case \"->\". induction l. \n SCase \"[]\". intros. apply all_nil.\n SCase \"x::l\". intros. apply all_cons. inversion H.\n destruct (P x) eqn:Hb. simpl. simpl in H1. symmetry. assumption.\n simpl. reflexivity.\n apply IHl. inversion H. destruct (forallb P l) eqn :Hb.\n symmetry. assumption. destruct (P x). simpl. reflexivity. simpl. reflexivity.\n Case \"<-\". induction l.\n SCase \"[]\". intros. simpl. reflexivity.\n SCase \"x::l\". intros. inversion H. simpl. rewrite H2. simpl.\n apply IHl. assumption.\nQed.\n\n", "meta": {"author": "YeongjinOh", "repo": "Programming-language", "sha": "a235e30cec9cab33fa52a7f708ae15d84b869615", "save_path": "github-repos/coq/YeongjinOh-Programming-language", "path": "github-repos/coq/YeongjinOh-Programming-language/Programming-language-a235e30cec9cab33fa52a7f708ae15d84b869615/06/P27.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915912, "lm_q2_score": 0.9173026522382527, "lm_q1q2_score": 0.8553418984714861}} {"text": "Load MyLists.\n\nTheorem app_assoc : forall l1 l2 l3 : natlist, (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n intros l1 l2 l3.\n induction l1.\n - (* base *) simpl. reflexivity.\n - (* i.h. *) simpl. rewrite <- IHl1. reflexivity.\nQed.\n\nFixpoint rev (l:natlist) : natlist :=\n match l with\n | nil => nil\n | cons h t => rev t ++ [h]\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof.\n reflexivity.\nQed.\n\nExample test_rev2: rev nil = nil.\nProof.\n reflexivity.\nQed.\n\nLemma my_fancy_lemma : forall l1 l2 : natlist, length (l1 ++ l2) = length l1 + length l2.\nProof.\n intros l1 l2.\n induction l1.\n - (* base *) simpl. reflexivity.\n - (* i.h. *) simpl. rewrite IHl1. reflexivity.\nQed.\n\nRequire Import PeanoNat.\n\nSearch (S _ = _ + 1).\nSearch (_ + 1 = S _).\nCheck Nat.add_1_r.\n\nLemma testlemma : forall n : nat, n + 1 = S n.\nProof.\n intros n.\n induction n.\n - (* base *) simpl. reflexivity.\n - (* i.h. *) simpl. rewrite IHn. reflexivity.\nQed.\n\nAxiom plus_comm : forall m n : nat, m + n = n + m.\n\nTheorem rev_length_mytry : forall l : natlist, length (rev l) = length l.\nProof.\n intros l.\n induction l.\n - (* base *) simpl. reflexivity.\n(* - (* i.h. *) simpl. rewrite -> my_fancy_lemma, plus_comm. simpl. rewrite IHl. reflexivity. *)\n - (* i.h. *) simpl. rewrite -> my_fancy_lemma. simpl. rewrite -> IHl. exact (Nat.add_1_r (length l)).\nQed.", "meta": {"author": "FengZiGG", "repo": "coqlf", "sha": "73aea6d263b0e05d8e25c5ce1f6609faf8e3956c", "save_path": "github-repos/coq/FengZiGG-coqlf", "path": "github-repos/coq/FengZiGG-coqlf/coqlf-73aea6d263b0e05d8e25c5ce1f6609faf8e3956c/3_Lists/7_list_induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954106, "lm_q2_score": 0.912436167620237, "lm_q1q2_score": 0.8551450195596313}} {"text": "Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice fintype.\nRequire Import tuple finfun div path bigop prime.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* The following lemma is already proved as in the examples file, but you may\n want to prove it in a different way, by induction on n.\n\n This lemma also exists in the library (part of binomial.v) *)\n\nLemma sumP' : forall n, \\sum_(i < n) i = (n * n.-1) ./2.\nProof.\nQed.\n\n(* You can prove this one in two fashions.\n 1/ by induction on n.\n 2/ by spliting and distributivity, then re-using sumP'. But division by\n two is a pain in the neck. *)\nLemma sum_odd1 : forall n, \\sum_(i < n) (2 * i + 1) = n ^ 2.\n\nLemma ex1 : forall n f, \\sum_(i < n) (f i + 1) = n + \\sum_(i < n) f i.\n\nLemma fact_big : forall n, n`! = \\prod_(1 <= i < n.+1) i.\n\n(* use the previous lemma for this proof. This is an opportunity to use big_prop. *)\nLemma prime_lt_Ndiv_fact :\n\nLemma sum_exp : forall x n, 0 < x -> x ^ n.+1 - 1 = (x - 1) * \\sum_(i < n.+1) x ^ i.\n\nSection abstract.\n\nVariable A : Type.\nVariables ad mu : A -> A -> A.\nVariable op : A -> A.\nVariables a0 a1 : A.\n\nHypothesis adC : commutative ad.\nHypothesis muC : commutative mu.\nHypothesis adA : associative ad.\nHypothesis muA : associative ad.\nHypothesis ad0a : left_id a0 ad.\nHypothesis ada0 : right_id a0 ad.\nHypothesis mu0a : left_zero a0 mu.\nHypothesis mua0 : right_zero a0 mu.\nHypothesis mu1a : left_id a1 mu.\nHypothesis mua1 : right_id a1 mu.\nHypothesis mu_adl : left_distributive mu ad.\nHypothesis mu_adr : right_distributive mu ad.\nHypothesis adN : forall a, ad a (op a) = a0.\n\nVariable exp : A -> nat -> A.\nHypothesis exp0 : forall x, exp x 0 = a1.\nHypothesis expS : forall x n, exp x n.+1 = mu x (exp x n).\nHypothesis muVop1 : forall x, op x = mu (op a1) x.\n\nLocal Notation \"x ^ n\" := (exp x n).\nLocal Notation \"a + b\" := (ad a b).\nLocal Notation \"a * b\" := (mu a b).\nLocal Notation \"a - b\" := (ad a (op b)).\n\n(* Add the relevant canonical structures to allow using natural operations on\n this addition, and multiplication. *)\n\n(* If you added enough canonical structures, this should be provable using\n big_split big_distrr, big_ord_recl, big_ord_recr, and many of the \n hypotheses given above. *)\n\nLemma sum_exp' : forall x n, x ^ n.+1 - a1 = (x - a1) * \\big[ad/a0]_(i < n.+1) x ^ i.\n\nEnd abstract.", "meta": {"author": "daoo", "repo": "formalization-of-mathematics", "sha": "7f87baab942cc053e446396c69817e98483d6db5", "save_path": "github-repos/coq/daoo-formalization-of-mathematics", "path": "github-repos/coq/daoo-formalization-of-mathematics/formalization-of-mathematics-7f87baab942cc053e446396c69817e98483d6db5/exercises/map/exercises-08.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.9252299488452012, "lm_q1q2_score": 0.8550436849585759}} {"text": "(** * Lists: Working with Structured Data *)\n\nFrom lf Require Export Induction.\nModule NatList.\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as here: *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n(** Here are two simple functions for extracting the first and\n second components of a pair. The definitions also illustrate how\n to do pattern matching on two-argument constructors. *)\n\nDefinition fst (p : natprod) : nat :=\n match p with\n | pair x y => x\n end.\n\nDefinition snd (p : natprod) : nat :=\n match p with\n | pair x y => y\n end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new pair notation can be used both in expressions and in\n pattern matches (indeed, we've actually seen this already in the\n [Basics] chapter, in the definition of the [minus] function --\n this works because the pair notation is also provided as part of\n the standard library): *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n match p with\n | (x,y) => x\n end.\n\nDefinition snd' (p : natprod) : nat :=\n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n match p with\n | (x,y) => (y,x)\n end.\n\n(** Let's try to prove a few simple facts about pairs.\n\n If we state things in a particular (and slightly peculiar) way, we\n can complete proofs with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nMProof.\n reflexivity. Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nMProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nMProof.\n intros p. destruct p &> [i:\\n m]. simpl. reflexivity. Qed.\n\n(** Notice that, unlike its behavior with [nat]s, [destruct]\n generates just one subgoal here. That's because [natprod]s can\n only be constructed in one way. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nMProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nMProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n type of _lists_ of numbers like this: \"A list is either the empty\n list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n declarations, but in case you are interested, here is roughly\n what's going on. The [right associativity] annotation tells Coq\n how to parenthesize expressions involving several uses of [::] so\n that, for example, the next three declarations mean exactly the\n same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\n\n Notation \"x + y\" := (plus x y)\n (at level 50, left associativity).\n\n the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n you read them in a .v file. The inner brackets, around 3, indicate\n a list, but the outer brackets, which are invisible in the HTML\n rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n part should be displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nMProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nMProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nMProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head (with default) and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\").\n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nMProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nMProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nMProof. reflexivity. Qed.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, recommended (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_nonzeros:\n nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n (* FILL IN HERE *) Admitted.\n\nFixpoint oddmembers (l:natlist) : natlist\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_oddmembers:\n oddmembers [0;1;0;2;3;0;0] = [1;3].\n (* FILL IN HERE *) Admitted.\n\nDefinition countoddmembers (l:natlist) : nat\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_countoddmembers1:\n countoddmembers [1;0;3;1;4;5] = 4.\n (* FILL IN HERE *) Admitted.\n\nExample test_countoddmembers2:\n countoddmembers [0;2;4] = 0.\n (* FILL IN HERE *) Admitted.\n\nExample test_countoddmembers3:\n countoddmembers nil = 0.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_alternate1:\n alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n (* FILL IN HERE *) Admitted.\n\nExample test_alternate2:\n alternate [1] [4;5;6] = [1;4;5;6].\n (* FILL IN HERE *) Admitted.\n\nExample test_alternate3:\n alternate [1;2;3] [4] = [1;4;2;3].\n (* FILL IN HERE *) Admitted.\n\nExample test_alternate4:\n alternate [] [20;30] = [20;30].\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n can appear multiple times rather than just once. One possible\n implementation is to represent a bag of numbers as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, recommended (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\n (* FILL IN HERE *) Admitted.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\n (* FILL IN HERE *) Admitted.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n the elements of [a] and of [b]. (Mathematicians usually define\n [union] on multisets a little bit differently -- using max instead\n of sum -- which is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\n (* FILL IN HERE *) Admitted.\n\nDefinition add (v:nat) (s:bag) : bag\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\n (* FILL IN HERE *) Admitted.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\n\nDefinition member (v:nat) (s:bag) : bool\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_member1: member 1 [1;4;1] = true.\n (* FILL IN HERE *) Admitted.\n\nExample test_member2: member 2 [1;4;1] = false.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\n(** When remove_one is applied to a bag without the number to remove,\n it should return the same bag unchanged. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_remove_one1:\n count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\n\nExample test_remove_one2:\n count 5 (remove_one 5 [2;1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\n\nExample test_remove_one3:\n count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n (* FILL IN HERE *) Admitted.\n\nExample test_remove_one4:\n count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n (* FILL IN HERE *) Admitted.\n\nFixpoint remove_all (v:nat) (s:bag) : bag\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n (* FILL IN HERE *) Admitted.\n\nFixpoint subset (s1:bag) (s2:bag) : bool\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\n (* FILL IN HERE *) Admitted.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (bag_theorem) *)\n(** Write down an interesting theorem [bag_theorem] about bags\n involving the functions [count] and [add], and prove it. Note\n that, since this problem is somewhat open-ended, it's possible\n that you may come up with a theorem which is true, but whose proof\n requires techniques you haven't learned yet. Feel free to ask for\n help if you get stuck! *)\n\n(*\nTheorem bag_theorem : ...\nProof.\n ...\nQed.\n*)\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nMProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the\n \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n the match) in the definition of [app], allowing the match itself\n to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nMProof.\n intros l. destruct l &> [i: ~~ | \\n l'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons n l' *)\n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n It is important to work through the details of each one, using Coq\n and thinking about what each step achieves. Otherwise it is more\n or less guaranteed that the exercises will make no sense when you\n get to them. 'Nuff said. *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n little less familiar than standard natural number induction, but\n the idea is equally simple. Each [Inductive] declaration defines\n a set of data values that can be built up using the declared\n constructors: a boolean can be either [true] or [false]; a number\n can be either [O] or [S] applied to another number; a list can be\n either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two arguments together establish\n the truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nMProof.\n intros l1 l2 l3. elim l1 &> [i:~~| \\n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons n l1' *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n [as...] clause provided to the [induction] tactic gives a name to\n the induction hypothesis corresponding to the smaller list [l1']\n in the [cons] case. Once again, this Coq proof is not especially\n illuminating as a static written document -- it is easy to see\n what's going on if you are reading the proof in an interactive Coq\n session and you can see the current goal and context at each\n point, but this state is not visible in the written-down parts of\n the Coq proof. So a natural-language proof -- one written for\n human readers -- will need to include more explicit signposts; in\n particular, it will help the reader stay oriented if we remind\n them exactly what the induction hypothesis is in the second\n case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n (the induction hypothesis). We must show\n\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n By the definition of [++], this follows from\n\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n which is immediate from the induction hypothesis. [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n lists, suppose we use [app] to define a list-reversing function\n [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => rev t ++ [h]\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nMProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nMProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Properties of [rev] *)\n\n(** Now let's prove some theorems about our newly defined [rev].\n For something a bit more challenging than what we've seen, let's\n prove that reversing a list does not change its length. Our first\n attempt gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nMProof.\n intros l. elim l &> [i: ~~ | \\n l' IHl'].\n - (* l = [] *)\n reflexivity.\n - (* l = n :: l' *)\n (* This is the tricky case. Let's begin as usual\n by simplifying. *)\n simpl.\n (* Now we seem to be stuck: the goal is an equality\n involving [++], but we don't have any useful equations\n in either the immediate context or in the global\n environment! We can make a little progress by using\n the IH to rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n would have enabled us to make progress and prove it as a separate\n lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n length (l1 ++ l2) = (length l1) + (length l2).\nMProof.\n (* WORKED IN CLASS *)\n intros l1 l2. elim l1 &> [i:~~| \\n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Note that, to make the lemma as general as possible, we\n quantify over _all_ [natlist]s, not just those that result from an\n application of [rev]. This should seem natural, because the truth\n of the goal clearly doesn't depend on the list having been\n reversed. Moreover, it is easier to prove the more general\n property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nMProof.\n intros l. elim l &> [i: ~~| \\n l' IHl'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons *)\n simpl. rewrite -> app_length, plus_comm.\n simpl. rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n _Theorem_: For all lists [l1] and [l2],\n [length (l1 ++ l2) = length l1 + length l2].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n length ([] ++ l2) = length [] + length l2,\n\n which follows directly from the definitions of\n [length] and [++].\n\n - Next, suppose [l1 = n::l1'], with\n\n length (l1' ++ l2) = length l1' + length l2.\n\n We must show\n\n length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n This follows directly from the definitions of [length] and [++]\n together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n\n length (rev []) = length [],\n\n which follows directly from the definitions of [length]\n and [rev].\n\n - Next, suppose [l = n::l'], with\n\n length (rev l') = length l'.\n\n We must show\n\n length (rev (n :: l')) = length (n :: l').\n\n By the definition of [rev], this follows from\n\n length ((rev l') ++ [n]) = S (length l')\n\n which, by the previous lemma, is the same as\n\n length (rev l') + length [n] = S (length l').\n\n This follows directly from the induction hypothesis and the\n definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n After the first few, we might find it easier to follow proofs that\n give fewer details (which can easily work out in our own minds or\n on scratch paper if necessary) and just highlight the non-obvious\n steps. In this more compressed style, the above proof might look\n like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n for any [l] (this follows by a straightforward induction on [l]).\n The main property again follows by induction on [l], using the\n observation together with the induction hypothesis in the case\n where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for our\n present purposes. *)\n\n\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, e.g., using [rewrite]. But in order to refer to a\n theorem, we need to know its name! Indeed, it is often hard even\n to remember what theorems have been proven, much less what they\n are called.\n\n Coq's [Search] command is quite helpful with this. Typing\n [Search foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following line\n to see a list of theorems that we have proved about [rev]: *)\n\n(* Search rev. *)\n\n(** Keep [Search] in mind as you do the following exercises and\n throughout the rest of the book; it can save you a lot of time!\n\n If you are using ProofGeneral, you can run [Search] with [C-c\n C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n l ++ [] = l.\nMProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n rev (l1 ++ l2) = rev l2 ++ rev l1.\nMProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nMProof.\n (* FILL IN HERE *) Admitted.\n\n(** There is a short solution to the next one. If you find yourself\n getting tangled up, step back and try to look for a simpler\n way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nMProof.\n (* FILL IN HERE *) Admitted.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nMProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_beq_natlist1 :\n (beq_natlist nil nil = true).\n (* FILL IN HERE *) Admitted.\n\nExample test_beq_natlist2 :\n beq_natlist [1;2;3] [1;2;3] = true.\n(* FILL IN HERE *) Admitted.\n\nExample test_beq_natlist3 :\n beq_natlist [1;2;3] [1;2;4] = false.\n (* FILL IN HERE *) Admitted.\n\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nMProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n definitions about bags above. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n leb 1 (count 1 (1 :: s)) = true.\nMProof.\n (* FILL IN HERE *) Admitted.\n\n(** The following lemma about [leb] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n leb n (S n) = true.\nMProof.\n intros n. elim n &> [i:~~| \\n' IHn'].\n - (* 0 *)\n simpl. reflexivity.\n - (* S n' *)\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nMProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *)\n(** Write down an interesting theorem [bag_count_sum] about bags\n involving the functions [count] and [sum], and prove it. (You may\n find that the difficulty of the proof depends on how you defined\n [count]!) *)\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective -- that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\n(There is a hard way and an easy way to do this.) *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n element of some list. If we give it type [nat -> natlist -> nat],\n then we'll have to choose some number to return when the list is\n too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with\n | true => a\n | false => nth_bad l' (pred n)\n end\n end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n can't tell whether that value actually appears on the input\n without further processing. A better alternative is to change the\n return type of [nth_bad] to include an error value as a possible\n outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption.\n\n(** We can then change the above definition of [nth_bad] to\n return [None] when the list is too short and [Some a] when the\n list has enough members and [a] appears at position [n]. We call\n this new function [nth_error] to indicate that it may result in an\n error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => match beq_nat n O with\n | true => Some a\n | false => nth_error l' (pred n)\n end\n end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nMProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nMProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nMProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n examples are elided. Click on a box if you want to see one.)\n\n This example is also an opportunity to introduce one more small\n feature of Coq's programming language: conditional\n expressions... *)\n\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => if beq_nat n O then Some a\n else nth_error' l' (pred n)\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually supports conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars (hd_error) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_error (l : natlist) : natoption\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_hd_error1 : hd_error [] = None.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_error l).\nMProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n Coq, here is a simple _partial map_ data type, analogous to the\n map or dictionary data structures found in most programming\n languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n | Id : nat -> id.\n\n(** Internally, an [id] is just a number. Introducing a separate type\n by wrapping each nat with the tag [Id] makes definitions more\n readable and gives us the flexibility to change representations\n later if we wish. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition beq_id (x1 x2 : id) :=\n match x1, x2 with\n | Id n1, Id n2 => beq_nat n1 n2\n end.\n\n(** **** Exercise: 1 star (beq_id_refl) *)\nTheorem beq_id_refl : forall x, true = beq_id x x.\nMProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n\nInductive partial_map : Type :=\n | empty : partial_map\n | record : id -> nat -> partial_map -> partial_map.\n\n(** This declaration can be read: \"There are two ways to construct a\n [partial_map]: either using the constructor [empty] to represent an\n empty partial map, or by applying the constructor [record] to\n a key, a value, and an existing [partial_map] to construct a\n [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n partial map (or adds a new entry if the given key is not already\n present). *)\n\nDefinition update (d : partial_map)\n (x : id) (value : nat)\n : partial_map :=\n record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n key. It returns [None] if the key was not found and [Some val] if\n the key was associated with [val]. If the same key is mapped to\n multiple values, [find] will return the first one it\n encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n match d with\n | empty => None\n | record y v d' => if beq_id x y\n then Some v\n else find x d'\n end.\n\n\n(** **** Exercise: 1 star (update_eq) *)\nTheorem update_eq :\n forall (d : partial_map) (x : id) (v: nat),\n find x (update d x v) = Some v.\nMProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (update_neq) *)\nTheorem update_neq :\n forall (d : partial_map) (x y : id) (o: nat),\n beq_id x y = false -> find x (update d y o) = find x d.\nMProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 stars (baz_num_elts) *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n | Baz1 : baz -> baz\n | Baz2 : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have? (Answer in English\n or the natural language of your choice.)\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** $Date: 2017-09-06 10:45:52 -0400 (Wed, 06 Sep 2017) $ *)\n", "meta": {"author": "Mtac2", "repo": "Mtac2", "sha": "d16c2e682d5ab18ed77b13b4fd60a42a65c4f958", "save_path": "github-repos/coq/Mtac2-Mtac2", "path": "github-repos/coq/Mtac2-Mtac2/Mtac2-d16c2e682d5ab18ed77b13b4fd60a42a65c4f958/tests/sf-5/lf/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.9207896753475597, "lm_q1q2_score": 0.8548692398772032}} {"text": "(* Programming and Proving with Numbers in Coq \n Whirlwind Tour, Part I\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *)\n\n(** Coq's most basic numeric type is [nat], or the type of natural numbers. \n As we saw last week, naturals are defined in unary notation in Coq, \n via the following inductive definition. This unary encoding makes \n defining and reasoning about [nat]-valued functions easy, but is \n horrendously ineficient! *)\n\nModule MyNat.\n Inductive nat : Type :=\n | O : nat (** zero *)\n | S : nat -> nat. (** successor *)\n\n (** Some notation, for nats 0 through 5: *)\n\n Local Notation \"'0'\" := (O).\n Local Notation \"'1'\" := (S 0).\n Local Notation \"'2'\" := (S 1).\n Local Notation \"'3'\" := (S 2). \n Local Notation \"'4'\" := (S 3).\n Local Notation \"'5'\" := (S 4). \n \n (** Now here's addition on the unary natural numbers. *)\n\n Fixpoint plus (n m : nat) : nat :=\n match n with\n | 0 => m\n | S n' => S (plus n' m)\n end.\n\n Eval compute in plus 3 2.\nEnd MyNat.\n\n(** Tactics for Proving [nat] Properties *)\n\nRequire Import Arith. (** Loads a bunch of libraries related to [nat] *)\n\n(** Exercise 1: Review *)\n\nLemma plus_assoc1 :\n forall n m r : nat,\n n + m + r = n + (m + r).\nProof.\n induction n.\n { simpl. auto. }\n intros. simpl. rewrite IHn. auto.\nQed.\n\nRequire Import Omega. (* The 'Omega' test \n -- a decision procedure for Presburger arithmetic *)\n\n(** Exercise 2: Use 'omega' to prove the following theorem: *)\n\nLemma plus_assoc2 :\n forall n m r : nat,\n n + m + r = n + (m + r).\nProof.\n intros.\n omega.\nQed.\n\n(** Exercise 3: When 'omega' fails... *)\n\nLemma mult_assoc1 :\n forall n m r : nat,\n n * m * r = n * (m * r).\nProof.\n intros.\n (* omega fails, why? *)\nAdmitted.\n\n(** Exercise 4: Update the above lemma statement by replacing \n [n] and [m] with constants. Does 'omega' work now? *)\n\nLemma mult_plus_distrib :\n forall n m r : nat,\n n * (m + r) = n * m + n * r.\nProof.\n induction n; auto.\n simpl. intros. rewrite IHn. omega.\nQed. \n\n(** Exercise 5: Prove the following theorem without using \n 'omega' directly (you may use [mult_plus_distrib] above. *)\n \nLemma mult_assoc2 :\n forall n m r : nat,\n n * m * r = n * (m * r).\nProof.\n induction n; auto.\n simpl. intros. rewrite <-IHn.\n rewrite mult_comm.\n rewrite mult_plus_distrib.\n rewrite mult_comm.\n rewrite (mult_comm r (n * m)).\n auto.\nQed.\n\n(** The unary encoding of [nat] is really inefficient. \n Here's a better binary encoding of the positive integers. *)\n\nModule MyPosZ.\n Inductive positive : Type :=\n | xI : positive -> positive (* Multiply by two and add 1 *)\n | xO : positive -> positive (* Multiply by two and add 0 *)\n | xH : positive. (* The positive '1' *)\n\n (** Exercise 6: Define successor on positives. *)\n \n Fixpoint succ (p : positive) : positive :=\n match p with\n | xI p' => xO (succ p')\n | xO p' => xI p'\n | xH => xO xH\n end.\n \n (** Some notation, for positives 1 through 5: *)\n\n Local Notation \"'1'\" := (xH).\n Local Notation \"'2'\" := (xO 1).\n Local Notation \"'3'\" := (xI 1). \n Local Notation \"'4'\" := (xO 2).\n Local Notation \"'5'\" := (xI 2). \n\n Eval compute in succ 2.\n Eval compute in succ 4.\n Eval compute in succ 1.\n\n (** The successor function defined above works correctly \n on a few test cases. But that doesn't imply that successor\n works correctly in *all* cases. To be certain, we'll \n have to prove it!\n\n Define the following interpretation function from \n positives to nats:\n \n [[ . ]] : positive -> nat\n [[ xI p' ]] = 2 * [[ p' ]] + 1\n [[ xO p' ]] = 2 * [[ p' ]]\n [[ xH ]] = 1\n\n Our correctness property is then the following theorem: \n\n Theorem: forall p, [[ succ p ]] = [[ p ]] + 1.\n\n Case xI: \n By IH, [[succ p']] = [[p']] + 1.\n N.T.S. [[p'~1]] + 1 = [[(succ p')~0]]\n = 2 * [[p']] + 2 = 2 * [[succ p']]\n = 2 * ([[p']] + 1) By IH\n = 2 * [[ p' ]] + 2 []\n\n Case xO: \n N.T.S. [[p'~0]] + 1 = [[p'~1]].\n = 2 * [[p']] + 1 = 2 * [[p']] + 1 []\n\n Case xH:\n N.T.S. [[xH]] + 1 = [[xO xH]]\n = 1 + 1 = 2 * [[xH]]\n = 2 * 1 = 2 []\n *)\n\n Fixpoint interp (p : positive) : nat :=\n match p with\n | xH => 1\n | xO p' => 2 * interp p'\n | xI p' => 2 * interp p' + 1\n end.\n\n Lemma pos_succ_correct :\n forall p : positive,\n interp p + 1 = interp (succ p).\n Proof.\n induction p.\n { unfold succ. fold succ.\n unfold interp. fold interp.\n rewrite <-!IHp. omega.\n }\n { simpl. rewrite <-!plus_n_O. auto. }\n auto.\n Qed. \n \n (** HOMEWORK Exercise 6b: Define predecessor on positives. \n HINT: Define [pred 1 = 1]. You may find an auxiliary \n function useful. Look in the standard library if you get \n stuck. *)\n \n (** Now we can define [Z] (the positive and negative integers) \n in terms of [positive] as follows: *)\n\n Inductive Z : Type :=\n | Z0 : Z (** Zero *)\n | Zpos : positive -> Z (* Positive Zs *)\n | Zneg : positive -> Z. (* Negative Zs *)\nEnd MyPosZ.\n\n(** This representation of positives and Z is in fact the same \n representation Coq's standard library uses. *)\n\nRequire Import ZArith.\n\n(* Coq's parser overloads standard notation like '*' to operate \n on multiple different arithmetic types. We explicitly open \n 'Z_scope' here, to ensure that '*' gets parsed as multiplication \n on the integers. *)\nOpen Scope Z_scope. \n\n(** Exercise 7: Prove the following fact on Z. Here's \n it's pretty inconvenient to reason directly from the underlying \n inductive definitions -- much better to make use of available \n lemmas! Recall \"SearchAbout\"... *)\n\nLemma Zfact1 :\n forall p q r s : Z, s * (p * (q + r)) = (s * p * q) + (s * p * r).\nProof.\n intros p q r s.\n rewrite Z.mul_assoc.\n rewrite Z.mul_add_distr_l; auto.\nQed. \n\nLemma Zfact2 :\n forall p q r s : Z, s * (p * (q + r)) = (s * p * q) + (s * p * r).\nProof.\n intros p q r s.\n ring. (*Yay!*)\n (* See [https://coq.inria.fr/refman/Reference-Manual028.html] for details *)\nQed.\n\n(** Exercise 8: *Without using ring*, try to prove the following fact \n about the integers. *)\n\nLemma Zfact3 :\n forall s t u z : Z, t * (s * u) + z = z + t * u * s.\nProof.\n intros s t u z.\n rewrite Z.add_comm.\n rewrite (Z.mul_comm s u).\n rewrite Z.mul_assoc.\n auto.\nQed.\n\n(** Let's compose some of the pieces we've defined above to build \n a new datatype for rationals, Q: *)\n\nModule MyQ.\n Record Q : Type :=\n QMake { QNum : Z;\n QDen : positive }.\n\n (** The 'Record' declaration above basically does the following: \n\n 1. Define an \n\n Inductive Q : Type := \n QMake : Z -> positive -> Q\n\n 2. Define 'projections', of the form:\n\n Definition QNum (q : Q) : Z := \n match q with \n | QMake n d => n\n end. \n\n Definition QDen (q : Q) : positive := \n match q with \n | QMake n d => d\n end. \n *)\n\n (** Here's addition on rationals. Note that we don't \n maintain irreducibility. *)\n \n Definition Qplus (x y : Q) :=\n QMake (QNum x * Zpos (QDen y) + QNum y * Zpos (QDen x))\n (Pos.mul (QDen x) (QDen y)).\n\n Definition three_fourths : Q := QMake 3 4.\n\n Eval compute in Qplus three_fourths three_fourths.\n\n (** Exercise 9: Define a variant of the 'Q' type above\n such that the fraction Qnum / Qden is always in \n reduced form (Qnum and Qden have no common divisors). To \n do so, you'll need to add a third term to the record \n containing a proof of the appropriate arithmetic fact. *)\n\n Record Q' : Type :=\n QMake' { QNum' : Z;\n QDen' : positive;\n invariant : (* FILL IN HERE *) False }.\n\n (* Define equality on \"reduced Q\" as follows: *)\n\n Definition Qeq (x y : Q') :=\n QNum' x * Zpos (QDen' y) = QNum' y * Zpos (QDen' x).\n\n (* If you've correctly defined 'reducedQ', you should be able \n to prove the following lemma: *)\n\n Lemma Qeq_eq :\n forall x y : Q', Qeq x y -> x = y.\n Proof.\n (** CHALLENGE Exercise: Prove this! *)\n Admitted. \nEnd MyQ. \n\n(** We don't need to define our own rationals, of course. Coq's \n standard library builds them in: *)\n\nRequire Import QArith.\n\nLemma Qfact1 :\n forall x y z : Q,\n z * (x + y) == z * x + z * y. (* To the left, == is 'Qeq'. *)\nProof.\n intros x y z.\n (* \"SearchAbout Qplus Qmult\" yields lemma \"Qmult_plus_distr_r\". *)\n apply Qmult_plus_distr_r.\nQed. \n\n(** Enough for now. In Part II, we'll look Real, plus ways to inject \n statements over one number type (e.g., nats) into another (e.g., Z). *)\n\n\n\n\n\n\n\n", "meta": {"author": "gstew5", "repo": "coq-tutorial-summer2016", "sha": "a68f81725388326f953a94c9143176075a90fe9e", "save_path": "github-repos/coq/gstew5-coq-tutorial-summer2016", "path": "github-repos/coq/gstew5-coq-tutorial-summer2016/coq-tutorial-summer2016-a68f81725388326f953a94c9143176075a90fe9e/numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415278, "lm_q2_score": 0.913676521650809, "lm_q1q2_score": 0.8546041456502314}} {"text": "(** MacBook-Air:08chapt billw$ /Applications/CoqIDE_8.4pl5.app/Contents/Resources/bin/coqc -verbose play02.v \nModule Playground2.\nFixpoint plus (n : nat) (m : nat) : nat :=\n match n with\n | O => m\n | S n' => S (plus n' m)\n end.\nEval compute in (plus (S (S (S O))) (S (S O))).\n = 5\n : nat\nFixpoint mult (n m : nat) : nat :=\n match n with\n | O => O\n | S n' => plus m (mult n' m)\n end.\nExample test_mult1: (mult 3 3) = 9.\nProof.\nreflexivity.\nQed.\nFixpoint minus (n m:nat) : nat :=\n match n, m with\n | O , _ => O\n | S _ , O => n\n | S n', S m' => minus n' m'\n end.\nEnd Playground2.\nMacBook-Air:08chapt billw$\n*)\nModule Playground2.\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n match n with\n | O => m\n | S n' => S (plus n' m)\n end.\n\nEval compute in (plus (S (S (S O))) (S (S O))).\n\nFixpoint mult (n m : nat) : nat :=\n match n with\n | O => O\n | S n' => plus m (mult n' m)\n end.\n\nExample test_mult1: (mult 3 3) = 9.\nProof. reflexivity. Qed.\n\nFixpoint minus (n m:nat) : nat :=\n match n, m with\n | O , _ => O\n | S _ , O => n\n | S n', S m' => minus n' m'\n end.\n\nEnd Playground2.\n", "meta": {"author": "billwestfall", "repo": "coq_ide", "sha": "a2985a04f37f9c1c6f23799d543fdb862792d54b", "save_path": "github-repos/coq/billwestfall-coq_ide", "path": "github-repos/coq/billwestfall-coq_ide/coq_ide-a2985a04f37f9c1c6f23799d543fdb862792d54b/008chapt/play02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.956634196290671, "lm_q2_score": 0.8933094032139577, "lm_q1q2_score": 0.8545703229824834}} {"text": "Module nat2.\n\nCheck nat.\nFixpoint plus (a: nat) (b: nat) : nat :=\n match a with\n | O => b\n | S a' => S (plus a' b)\n end.\nFixpoint mult (a: nat) (b: nat): nat :=\n match a with \n | O => O\n | S a' => plus b (mult a' b)\n end.\nFixpoint minus (a: nat) (b: nat) :=\n match a, b with\n | O, _ => O\n | _ , O => O\n | S a', S b' => minus a' b'\n end.\nFixpoint factorial (n: nat) : nat :=\n match n with\n | O => S O\n | S n' => mult n (factorial n')\n end.\n Example test_factorial1: (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = 120.\nProof. simpl. reflexivity. Qed.\nEnd nat2.\n \n", "meta": {"author": "jeorp", "repo": "SoftwareFoundations_reading", "sha": "1d85b5360f1225af103a9a78424aa8df02d234cd", "save_path": "github-repos/coq/jeorp-SoftwareFoundations_reading", "path": "github-repos/coq/jeorp-SoftwareFoundations_reading/SoftwareFoundations_reading-1d85b5360f1225af103a9a78424aa8df02d234cd/nat2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9830850837598123, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.854130650768932}} {"text": "Require Import Arith.\nRequire Import ZArith.\nRequire Import Bool.\n\n(** Exercise 2.1 **)\n\nOpen Scope nat_scope.\n\n(* The type is going to be nat -> nat\n because of rule App applied with A = nat,\n B = nat -> nat *)\nCheck (plus 3).\n\n(* The type is going to be Z -> Z for the same \n reason, replacing nat by Z *)\nCheck (Zmult(-5)).\n\n(* The type is going to be Z -> nat because the\n function is defined to convert integers to\n natural numbers *)\nCheck Zabs_nat.\n\n(* The type is going to be nat, because plus has\n type nat -> nat -> nat and it's applied to\n two value *)\nCheck (5 + Zabs_nat(5 - 19)).\n\n(** Exercise 2.2 **)\n\n(* The type is going to be Z -> Z -> Z -> Z,\n because it's \"a function that takes three\n integers and returns one\" *)\n\nCheck fun a b c:Z => (b*b-4*a*c)%Z.\n\n(** Exercise 2.3 **)\n\n(** It's possible and its type is going to be\n (nat -> nat) -> (nat -> nat) -> nat -> nat\n because it takes two function from naturals}\n to naturals and returns a single one. The\n last parenthesis is not necessary because of\n right associativity *)\n\nCheck fun (f g:nat->nat)(n:nat) => g (f n).\n\n(** Exercise 2.4 **)\n\n(* Two applications of Lam give us the type \n - Lam: whole expression, nat -> ???\n - Lam: whole expression, nat -> nat -> ???\n - Let-in\n App: n - p, nat\n - Let-in\n App: diff*diff, nat\n App: square + n, nat\n App: square * (square + n), nat\n inner let, nat\n outer let, nat\n*)\n \nCheck fun n p: nat =>\n (let diff := n-p in\n let square := diff*diff in\n square * (square + n)).\n\n(** Exercise 2.5 **)\n\nDefinition sum5 a b c d e:Z :=\n (a + b + c + d + e)%Z.\n\n(** Exercise 2.6 **)\n\nSection defNewSum5.\n Variables a b c d e:Z.\n Definition newSum5 := (a + b + c + d + e)%Z.\nEnd defNewSum5.\n\nPrint newSum5.\n\n(** Exercise 2.7 **)\n\nDefinition poly27 :=\n fun x:Z => Zplus (Zplus (Zmult 2%Z\n (Zmult x x))\n (Zmult 3%Z x))\n 3%Z.\n\nEval compute in (poly27 2).\nEval compute in (poly27 3).\nEval compute in (poly27 4).", "meta": {"author": "mchouza", "repo": "learning-coq", "sha": "b5a3409d34dcce571c002b6e6b8e80acce069e82", "save_path": "github-repos/coq/mchouza-learning-coq", "path": "github-repos/coq/mchouza-learning-coq/learning-coq-b5a3409d34dcce571c002b6e6b8e80acce069e82/coq-ch2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.9184802529509909, "lm_q1q2_score": 0.8536726518113554}} {"text": "Require Import ssreflect.\n\nInductive color :=\n | blue\n | red.\n\nDefinition inv (c : color) :=\n match c with\n | red => blue\n | blue => red\n end.\n\nEval compute in (inv (inv red)).\n\n(* various versions *)\nLemma inv_conv : forall x, inv (inv x) = x.\nmove => x.\ncase: x.\n- simpl.\n reflexivity.\n- reflexivity.\nRestart.\n move => x.\n case x; reflexivity. \nRestart.\nmove => [ | ]; reflexivity.\nQed.\n\nCheck true.\n(* ===> true : bool *)\n\n Inductive opt_nat :=\n None\n| Some : nat -> opt_nat.\n\nDefinition opt_add :=\n fun (n : opt_nat) (m : opt_nat) =>\n match n, m with\n | Some a, Some b => Some (a+b)\n | _ , _ => None\n end.\n\n(* This two a equal\nDefinition add_opt n m :=\n match n, m with\n | Some a, Some b => Some (a+b)\n | None, Some _ => None\n | Some _, None => None\n | None, None => None\n end.\n*)\n\nEval compute in (opt_add (Some 2)(Some 3)).\n\nEval compute in (opt_add (Some 2) None).\n\nDefinition pred n :=\n match n with\n O => O\n | S m => m\n end.\n\nEval compute in (pred (pred 6)).\n\nEval compute in (pred 0).\n\nEval compute in (pred 5).\n\nEval compute in (S 3).\n\nEval compute in (S (pred 3)).\n\n(* The following function prove that if the pred of x plus 1 is iteself then it's 0 *)\nLemma pred_corr :\n forall x, S (pred x) = x \\/ x = 0.\nmove => x.\ncase: x.\n- simpl.\n right; reflexivity.\n- move => x.\n simpl.\n left; reflexivity.\nRestart.\nmove => [ | y].\n- right; reflexivity.\n- left; reflexivity.\nQed.\n\nFixpoint plus n m :=\n match n with\n | O => m\n | S p => S (plus p m)\n end.\n\nEval compute in (plus 2 2).\nEval compute in (plus (S O) (S O)).\nLemma dpd : (plus 2 2) = 4.\nreflexivity.\nQed.\n\n\nLemma l1 : forall x, plus 0 x = x.\nmove => x.\nreflexivity.\nQed.\n\nLemma l2 : forall x, plus x 0 = x.\n move => x.\n simpl.\n induction x.\n - simpl.\n reflexivity.\n - simpl.\n rewrite IHx.\n reflexivity. \nQed.\n\nFixpoint double (n : nat) :=\n match n with\n | O => O\n | S m => S (S (double m))\nend.\n\nEval compute in (double 3).\n\n\n(* Proof by intduction *)\nTheorem add_0_r_secondtry : forall n:nat,\n n + 0 = n.\nProof.\n intros n. destruct n as [| n'] eqn:E.\n - (* n = 0 *)\n reflexivity. (* so far so good... *)\n - (* n = S n' *)\n simpl. (* ...but here we are stuck again *)\nAbort.\n\n(* Since for n is an unknown number then therefore we need proof by induction *)\nTheorem add_0_r : forall n:nat, n + 0 = n.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *) reflexivity.\n - (* n = S n' *) simpl. rewrite -> IHn'. reflexivity. \nQed.", "meta": {"author": "yubocai-poly", "repo": "Nim-Game", "sha": "cfda89d3ed187b07a43442ac1bb7ababc264c050", "save_path": "github-repos/coq/yubocai-poly-Nim-Game", "path": "github-repos/coq/yubocai-poly-Nim-Game/Nim-Game-cfda89d3ed187b07a43442ac1bb7ababc264c050/Tutorial_3/datatypes_lect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.9314625126757597, "lm_q1q2_score": 0.8533217646938345}} {"text": "Inductive Nat : Set :=\n| Z : Nat\n| S : Nat -> Nat.\n\nFixpoint add ( n m : Nat ) : Nat :=\nmatch n with\n| Z => m\n| S n' => S ( add n' m )\nend.\n\nTheorem add_z_r : forall n : Nat, add n Z = n.\nProof.\n induction n.\n simpl.\n auto.\n simpl.\n rewrite IHn.\n auto.\nQed.\n\nTheorem add_s_r : forall n m: Nat, add n (S m) = S (add n m).\nProof.\n induction n.\n simpl.\n auto.\n simpl.\n intros.\n simpl.\n rewrite IHn.\n auto.\nQed.\n\nInductive Assoc (A : Type) (f : A -> A -> A) :=\n| Assoc_proof : ( forall a b c : A, f ( f a b ) c = f a ( f b c )) -> Assoc A f\n.\n\nInductive ID_Elem (A : Type) (f : A -> A -> A) (id : A) :=\n| ID_Elem_proof : (forall a : A, f id a = a) -> ID_Elem A f id\n.\n\nInductive Commute (A : Type) (f : A -> A -> A) :=\n| Commute_proof : (forall a b : A , f a b = f b a) -> Commute A f\n.\n\nInductive SemiGroup (A : Type) (f : A -> A -> A) :=\n| SemiGroup_proof : Assoc A f -> Commute A f -> SemiGroup A f\n.\n\nInductive Monoid (A : Type) (f : A -> A -> A) (id : A) :=\n| Monoid_proof : SemiGroup A f -> ID_Elem A f id -> Monoid A f id\n.\n\nTheorem add_commut : forall n m : Nat, add n m = add m n.\nProof.\n induction n.\n simpl.\n intro m.\n replace (add m Z) with m.\n simpl.\n auto.\n rewrite add_z_r.\n auto.\n simpl.\n intros.\n rewrite add_s_r.\n auto.\n rewrite IHn.\n auto.\nQed.\n\nTheorem add_assoc : forall a b c : Nat , add ( add a b ) c = add a ( add b c).\nProof.\n induction a.\n simpl.\n auto.\n simpl.\n intros.\n rewrite IHa.\n auto.\nQed.\n\nTheorem add_id : forall n : Nat, add Z n = n.\nProof.\n intros.\n simpl.\n auto.\nQed.\n\nDefinition add_monoid := Monoid_proof Nat add Z\n( SemiGroup_proof Nat add (Assoc_proof Nat add add_assoc) (Commute_proof Nat add add_commut ) )\n( ID_Elem_proof Nat add Z add_id ) \n.\n\nInductive List (A : Type) :=\n| Empty : List A \n| Cons : A -> List A -> List A\n.\n\nFixpoint fold (A : Type) (f : A -> A -> A) (empty : A) (p : Monoid A f empty) (ls : List A) := \nmatch ls with\n| Empty _ => empty\n| Cons _ val rest => f val (fold A f empty p rest)\nend .\n\n", "meta": {"author": "LaltonDundy", "repo": "MonoidCoq", "sha": "a7f9b99542f413a013c70630354da359cf9e7fad", "save_path": "github-repos/coq/LaltonDundy-MonoidCoq", "path": "github-repos/coq/LaltonDundy-MonoidCoq/MonoidCoq-a7f9b99542f413a013c70630354da359cf9e7fad/MonoidVerified.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762057376384, "lm_q2_score": 0.8887587846530938, "lm_q1q2_score": 0.8529969596699879}} {"text": "(*递归描述的数据结构*)\nFrom LF Require Export Induction.\nModule NatList.\nInductive natprod: Type := \n| pair (n1 n2: nat).\nCheck (pair 3 5).\nCheck pair 3.\nDefinition fst(p : natprod) : nat :=\n match p with\n | pair x y => x\n end.\nDefinition snd(p : natprod) : nat :=\n match p with\n | pair x y => y\n end.\nCompute (fst(pair 3 5)).\nNotation \"( x , y )\" := (pair x y).\nDefinition fst' (p : natprod) : nat :=\n match p with\n | (x,y) => x\n end.\nDefinition snd' (p : natprod) : nat :=\n match p with\n | (x,y) => y\n end.\nDefinition swap_pair (p : natprod) : natprod :=\n match p with\n | (x,y) => (y,x)\n end.\nFixpoint minus (n m : nat) : nat :=\n match n, m with\n | O , _ => O\n | S _ , O => n\n | S n', S m' => minus n' m'\n end.\n(* Can't match on a pair with multiple patterns: \nDefinition bad_fst (p : natprod) : nat :=\n match p with\n | x, y => x\n end.\n(* Can't match on multiple values with pair patterns: *)\nDefinition bad_minus (n m : nat) : nat :=\n match n, m with\n | (O , _ ) => O\n | (S _ , O ) => n\n | (S n', S m') => bad_minus n' m'\n end.\n 不允许pair匹配多值\"*\"下面证明为啥pair不允许被匹配多值*)\nTheorem surjective_pairing' : forall (n m: nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\nTheorem surjective_pairing_stuck: forall (p:natprod),\n p = (fst p, snd p).\nProof.\n simpl.\nAbort.\nCheck natprod.\nTheorem surjetive_pairing: forall p:natprod,\n p = (fst p,snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n(* Exercise: 1 star, standard (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p. destruct p as [n m].\n simpl. reflexivity.\nQed.\n(* Exercise: 1 star, standard, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros p. destruct p as [n m].\n simpl. reflexivity.\nQed.\n(*cons == construct*)\nInductive natlist : Type:=\n | nil\n | cons (n:nat)(l:natlist).\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\nPrint mylist.\nNotation \"x :: l\" := (cons x l)\n (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\nNotation \"x + y\" := (plus x y)\n (at level 50, left associativity).\nFixpoint repeat (n count : nat) : natlist :=\n match count with\n | 0 => nil\n | S count' => n :: (repeat n count')\n end.\nFixpoint length (l: natlist): nat :=\n match l with\n | nil => O\n | h :: t => S (length t)\n end.\nFixpoint app (l1 l2:natlist):natlist :=\n match l1 with\n | nil => l2\n | h :: t => h:: (app t l2)\n end.\nNotation \"x ++ y\" := (app x y)\n (right associativity, at level 60).\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => t\n end.\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n(*\nExercise: 2 stars, standard, recommended (list_funs)\nComplete the definitions of nonzeros, oddmembers, and countoddmembers below. Have a look at the tests to understand what these functions should do.\n*)\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | nil => nil\n | 0 :: t => nonzeros t\n | h :: t => h :: (nonzeros t)\n end.\nExample test_nonzeros:\n nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n reflexivity. Qed.\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => match evenb(h) with\n | true => oddmembers t\n | false => h :: oddmembers t\n end\n end. \nExample test_oddmembers:\n oddmembers [0;1;0;2;3;0;0] = [1;3].\n simpl. reflexivity. Qed.\nDefinition countoddmembers (l:natlist) : nat :=\n length (oddmembers l).\nExample test_countoddmembers1:\n countoddmembers [1;0;3;1;4;5] = 4.\n Proof. reflexivity. Qed.\nExample test_countoddmembers2:\n countoddmembers [0;2;4] = 0.\n Proof. reflexivity. Qed.\nExample test_countoddmembers3:\n countoddmembers nil = 0.\n Proof. reflexivity. Qed.\n(*\nExercise: 3 stars, advanced (alternate)\nComplete the definition of alternate,\n which interleaves two lists into one,\nalternating between elements taken from the first list and elements from the second. See the tests below for more specific examples.\n*)\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h1 :: t1 => \n match l2 with\n | nil => h1::t1\n | h2 :: t2 => h1::h2::( alternate t1 t2 )\n end\n end.\nExample test_alternate1:\n alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. simpl. reflexivity. Qed.\nExample test_alternate2:\n alternate [1] [4;5;6] = [1;4;5;6].\nProof. simpl. reflexivity. Qed.\nExample test_alternate3:\n alternate [1;2;3] [4] = [1;4;2;3].\nProof. simpl. reflexivity. Qed.\nExample test_alternate4:\n alternate [] [20;30] = [20;30].\nProof. simpl. reflexivity. Qed.\n\n(* Bags via Lists*)\n(* Exercise: 3 stars, standard, recommended (bag_functions) *)\nDefinition bag := natlist.\nFixpoint count (v:nat)(s:bag) :nat :=\n match s with\n | nil => 0\n | h::t => \n match h=?v with\n | true => S (count v t)\n | false => count v t\n end \n end.\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. simpl. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. simpl. reflexivity. Qed.\n(*很像匿名函数*)\nDefinition sum : bag -> bag -> bag := app.\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\nDefinition add (v:nat) (s:bag) : bag := v :: s.\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nDefinition member (v:nat) (s:bag) : bool :=\n match count v s with\n | 0 => false\n | _ => true\n end.\nExample test_member1: member 1 [1;4;1] = true.\nProof. simpl. reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n(* Exercise: 3 stars, standard, optional (bag_more_functions) *)\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n match s with\n | nil => nil\n | h :: t => \n match v=?h with\n | true => t\n | false => h :: (remove_one v t)\n end\n end.\nExample test_remove_one1:\n count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_one2:\n count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_one3:\n count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\nExample test_remove_one4:\n count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. simpl. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with \n | nil => nil\n | h :: t => \n match v=?h with\n | true => remove_all v t\n | false => h :: (remove_all v t)\n end\n end.\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. simpl. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n match s1 with\n | nil => true\n | h :: t => \n match (count h s1)<=?(count h s2) with\n | true => subset t s2\n | false => false\n end\n end.\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. simpl. reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n(*Reasoning about Lists*)\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(*tl means tail*)\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons n l' *)\n reflexivity. Qed.\n(* pred 指的是前驱 \nCompute Nat.pred (S(S 0)).*)\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons n l1' *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\nFixpoint rev (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => rev t ++ [h]\n end.\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n(* let's prove that reversing a list does not change its length. Our first attempt gets stuck in the successor case...*)\n\nTheorem app_length : forall l1 l2 : natlist,\n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - reflexivity. \n - simpl. rewrite -> app_length, plus_comm.\n simpl. rewrite -> IHl'.\n reflexivity.\nQed.\n\n(* Exercise: 3 stars, standard (list_exercises) *)\nTheorem app_nil_r : forall l : natlist,\n l ++ [] = l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - reflexivity.\n - simpl. rewrite -> IHl'. reflexivity.\nQed.\nTheorem rev_app_distr: forall l1 l2 : natlist,\n rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n simpl. induction l2 as [| n l2' IHl2']. reflexivity.\n rewrite -> app_nil_r. reflexivity.\n simpl. rewrite -> IHl1'. rewrite -> app_assoc. reflexivity.\nQed.\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros l. induction l as [| n l IHl']. reflexivity.\n simpl. rewrite -> rev_app_distr.\n simpl. rewrite -> IHl'.\n reflexivity.\nQed.\n\n(* Exercise: 2 stars, standard (eqblist) *)\n(* Fill in the definition of eqblist, which compares lists of numbers for equality. Prove that eqblist l l yields true for every list l. *)\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n match l1 with\n | nil => \n match l2 with\n | nil => true\n | h :: t => false\n end\n | h1 :: t1 => \n match l2 with\n | nil => false\n | h2 :: t2 => \n match h1 =? h2 with\n | true => eqblist t1 t2\n | false => false\n end\n end\n end.\nExample test_eqblist1 :\n (eqblist nil nil = true).\nProof. simpl. reflexivity. Qed.\nExample test_eqblist2 :\n eqblist [1;2;3] [1;2;3] = true.\nProof. simpl. reflexivity. Qed.\nExample test_eqblist3 :\n eqblist [1;2;3] [1;2;4] = false.\nProof. simpl. reflexivity. Qed.\n\nTheorem eqblist_refl : forall l:natlist,\n true = eqblist l l.\nProof.\n intros l. induction l as [| n l' IHl']. reflexivity.\n simpl. rewrite <- eql_theo, IHl'. reflexivity. \nQed.\n\n(* Exercise: 1 star, standard (count_member_nonzero) *)\nTheorem count_member_nonzero : forall (s : bag),\n 1 <=? (count 1 (1 :: s)) = true.\nProof.\n intros s. induction s as [| n l IHl]. reflexivity.\n reflexivity.\nQed.\n\nTheorem leb_n_Sn : forall n,\n n <=? (S n) = true.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* 0 *)\n simpl. reflexivity.\n - (* S n' *)\n simpl. rewrite IHn'. reflexivity. Qed.\n\n(* Exercise: 3 stars, advanced (remove_does_not_increase_count) *)\nTheorem remove_does_not_increase_count: forall (s : bag),\n (count 0 (remove_one 0 s)) <=? (count 0 s) = true.\nProof.\n intros s. induction s as [| n l IHl]. reflexivity.\n destruct n. simpl. rewrite -> leb_n_Sn. reflexivity.\n simpl. rewrite -> IHl. reflexivity.\nQed.\n\n(*\nExercise: 4 stars, advanced (rev_injective)\nProve that the rev function is injective — that is,\n ∀(l1 l2 : natlist), rev l1 = rev l2 → l1 = l2.\n(There is a hard way and an easy way to do this.)\n*)\nTheorem bag_theo_one_fst: forall l1 l2 : natlist,\n rev l1 = rev l2 -> l1 = l2.\nProof.\n intros l1 l2. destruct l1 as [].\n intros H. destruct l2 as []. reflexivity. \n rewrite <- rev_involutive. rewrite <- H. \n rewrite -> rev_involutive. reflexivity.\nAbort.\nTheorem bag_theo_one_sec: forall l1 l2 : natlist,\n rev l1 = rev l2 -> l1 = l2.\nProof.\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n intros H. destruct l2 as []. reflexivity. \n rewrite <- rev_involutive. rewrite <- H. \n rewrite -> rev_involutive. reflexivity.\n induction l2 as [| l2 IHl2']. intros H.\n rewrite <- rev_involutive. rewrite <- H. \n rewrite -> rev_involutive. reflexivity. \n intros H.\nAbort.\nTheorem bag_theo_one: forall l1 l2 : natlist,\n rev l1 = rev l2 -> l1 = l2.\nProof.\n intros l1 l2. intros H.\n induction l1 as [| n l1' IHl1'].\n destruct l2 as []. reflexivity. \n rewrite <- rev_involutive. rewrite <- H. \n rewrite -> rev_involutive. reflexivity.\n induction l2 as [| l2 IHl2']. \n rewrite <- rev_involutive. rewrite <- H. \n rewrite -> rev_involutive. reflexivity.\n rewrite <- rev_involutive. rewrite <- H. \n rewrite -> rev_involutive. reflexivity.\nQed.\n\n(*rewrite xx -->把xx 带入*)\n(*Options *)\n(*Suppose we want to write a function that returns the nth element of some list. If we give it type nat → natlist → nat, then we'll have to choose some number to return when the list is too short...*)\nInductive natoption : Type :=\n | Some (n:nat)\n | None.\n\nFixpoint nth_error (l:natlist)(n:nat):natoption:=\n match l with\n | nil => None\n | h :: t => \n match n =? 0 with\n | true => Some h\n | false => nth_error t (pred n)\n end\n end.\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. simpl. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. simpl. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. simpl. reflexivity. Qed.\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => if n =? O then Some a\n else nth_error' l' (pred n)\n end.\nDefinition option_elim (d:nat)(o:natoption): nat:=\n match o with\n | Some n => n\n | None => d\n end.\n(*\nExercise: 2 stars, standard (hd_error)\nUsing the same idea, fix the hd function from earlier so we don't have to pass a default element for the nil case.\n*)\nDefinition hd_error (l : natlist) : natoption :=\n match l with\n | nil => None\n | h :: t => Some h\n end.\nExample test_hd_error1 : hd_error [] = None.\nProof. simpl. reflexivity. Qed.\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. simpl. reflexivity. Qed.\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. simpl. reflexivity. Qed.\n(*\nExercise: 1 star, standard, optional (option_elim_hd)\nThis exercise relates your new hd_error to the old hd.\n*)\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_error l).\nProof.\n intros l default. induction l as [| n l' IHl']. reflexivity.\n reflexivity.\nQed.\nEnd NatList.\n\n(*Partial Maps*)\nInductive id : Type :=\n | Id (n:nat).\nDefinition eqb_id (x1 x2:id):=\n match x1,x2 with\n | Id n1,Id n2 => n1 =? n2\n end.\n(*Exercise: 1 star, standard (eqb_id_refl)*)\nTheorem eqb_id_refl : forall x, true = eqb_id x x.\nProof.\n intros x. destruct x.\n simpl. rewrite <- eql_theo. reflexivity.\nQed.\nModule PartialMap.\nExport NatList.\nInductive partial_map:Type :=\n |empty\n |record (i:id)(v:nat)(m:partial_map).\nDefinition update (d:partial_map)(x:id)(value:nat):partial_map\n:= record x value d.\nFixpoint find (x:id)(d:partial_map):natoption :=\n match d with\n | empty => None\n | record y v d' => \n if eqb_id x y\n then Some v\n else find x d'\n end.\n(* Exercise: 1 star, standard (update_eq) *)\nTheorem update_eq :\n forall (d : partial_map) (x : id) (v: nat),\n find x (update d x v) = Some v.\nProof.\n intros d x v. destruct d. destruct x. destruct v.\n simpl. rewrite <- eql_theo. reflexivity.\n simpl. rewrite <- eql_theo. reflexivity.\n simpl. rewrite <- eqb_id_refl. reflexivity.\nQed.\n(* Exercise: 1 star, standard (update_neq) *)\nTheorem update_neq :\n forall (d : partial_map) (x y : id) (o: nat),\n eqb_id x y = false -> find x (update d y o) = find x d.\nProof.\n intros d x y o. \n destruct x. destruct y. destruct o. simpl.\n intros H. rewrite -> H. reflexivity.\n simpl. intros H. rewrite -> H. reflexivity. \nQed.\nEnd PartialMap.\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "santiweide", "repo": "software_foundation", "sha": "a45c9cf27801f206ee7baab391e750bcf09badfa", "save_path": "github-repos/coq/santiweide-software_foundation", "path": "github-repos/coq/santiweide-software_foundation/software_foundation-a45c9cf27801f206ee7baab391e750bcf09badfa/logic_foundations/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849805, "lm_q2_score": 0.9273632931373373, "lm_q1q2_score": 0.8528427323494577}} {"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export Logic.\n\n\n\n(* ####################################################### *)\n(** * From Boolean Functions to Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n number for evenness, yielding [true] if so. We can use this\n function to define the _proposition_ that some number [n] is\n even: *)\n\nDefinition even (n:nat) : Prop := \n evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n returns [true] when applied to [n].\" \n\n Note that here we have given a name\n to a proposition using a [Definition], just as we have\n given names to expressions of other sorts. This isn't a fundamentally\n new kind of proposition; it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n directly. Instead of going via the [evenb] function (\"a number is\n even if a certain computation yields [true]\"), we can say what the\n concept of evenness means by giving two different ways of\n presenting _evidence_ that a number is even. *)\n\n(** * Inductively Defined Propositions *)\n\nInductive ev : nat -> Prop :=\n | ev_0 : ev O\n | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(** This definition says that there are two ways to give\n evidence that a number [m] is even. First, [0] is even, and\n [ev_0] is evidence for this. Second, if [m = S (S n)] for some\n [n] and we can give evidence [e] that [n] is even, then [m] is\n also even, and [ev_SS n e] is the evidence. *)\n\n\n(** **** Exercise: 1 star (double_even) *)\n\nTheorem double_even : forall n,\n ev (double n).\nProof.\n intros.\n induction n as [|n'].\n Case \"n = 0\".\n simpl. apply ev_0.\n Case \"n = S n'\".\n simpl. apply ev_SS. apply IHn'.\nQed.\n(** [] *)\n\n\n(** *** Discussion: Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n phrased in two different ways -- indirectly, via a boolean testing\n function [evenb], or directly, by inductively describing what\n constitutes evidence for evenness. These two ways of defining\n evenness are about equally easy to state and work with. Which we\n choose is basically a question of taste.\n\n However, for many other properties of interest, the direct\n inductive definition is preferable, since writing a testing\n function may be awkward or even impossible. \n\n One such property is [beautiful]. This is a perfectly sensible\n definition of a set of numbers, but we cannot translate its\n definition directly into a Coq Fixpoint (or into a recursive\n function in any other common programming language). We might be\n able to find a clever way of testing this property using a\n [Fixpoint] (indeed, it is not too hard to find one in this case),\n but in general this could require arbitrarily deep thinking. In\n fact, if the property we are interested in is uncomputable, then\n we cannot define it as a [Fixpoint] no matter how hard we try,\n because Coq requires that all [Fixpoint]s correspond to\n terminating computations.\n\n On the other hand, writing an inductive definition of what it\n means to give evidence for the property [beautiful] is\n straightforward. *)\n\n\n\n(** **** Exercise: 1 star (ev__even) *)\n(** Here is a proof that the inductive definition of evenness implies\n the computational one. *)\n\nTheorem ev__even : forall n,\n ev n -> even n.\nProof.\n intros n E. induction E as [| n' E'].\n Case \"E = ev_0\". \n unfold even. reflexivity.\n Case \"E = ev_SS n' E'\". \n unfold even. apply IHE'. \nQed.\n\n(** Could this proof also be carried out by induction on [n] instead\n of [E]? If not, why not? *)\n\n(* Performing induction on [n] requires us to prove\n evenb (S n') = true\n assuming that\n ev n' -> evenb n' = true\n and\n ev (S n')\n\n If the goal is [True], then [S n'] is even and [n'] is odd, so we\n cannot apply the hypothesis. If [n'] is even, then [S n'] is odd,\n and we are stuck again.\n\n If we perform induction on the hypothesis instead, we get\n even n'\n in the context and\n even (S (S n'))\n in the goal. Both numbers are either odd or even, so we can use\n the hypothesis. *)\n(** [] *)\n\n(** The induction principle for inductively defined propositions does\n not follow quite the same form as that of inductively defined\n sets. For now, you can take the intuitive view that induction on\n evidence [ev n] is similar to induction on [n], but restricts our\n attention to only those numbers for which evidence [ev n] could be\n generated. We'll look at the induction principle of [ev] in more\n depth below, to explain what's really going on. *)\n\n(** **** Exercise: 1 star (l_fails) *)\n(** The following proof attempt will not succeed.\n Theorem l : forall n,\n ev n.\n Proof.\n intros n. induction n.\n Case \"O\". simpl. apply ev_0.\n Case \"S\".\n ...\n Intuitively, we expect the proof to fail because not every\n number is even. However, what exactly causes the proof to fail?\n\nWe cannot apply [ev_SS]. Even if we apply it in the hypothesis, we\nwon't be able to apply the result [ev (S (S n))] in the goal [ev (S\nn)]. *)\n(** [] *)\n\n(** **** Exercise: 2 stars (ev_sum) *)\n(** Here's another exercise requiring induction. *)\n\nTheorem ev_sum : forall n m,\n ev n -> ev m -> ev (n+m).\nProof. \n intros n m evN evM.\n induction evN.\n apply evM.\n simpl. apply ev_SS. apply IHevN.\nQed.\n(** [] *)\n\n\n(* ##################################################### *)\n(** ** Example *)\n\n(** As a running example, let's\n define a simple property of natural numbers -- we'll call it\n \"[beautiful].\" *)\n\n(** Informally, a number is [beautiful] if it is [0], [3], [5], or the\n sum of two [beautiful] numbers. \n\n More pedantically, we can define [beautiful] numbers by giving four\n rules:\n\n - Rule [b_0]: The number [0] is [beautiful].\n - Rule [b_3]: The number [3] is [beautiful]. \n - Rule [b_5]: The number [5] is [beautiful]. \n - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is\n their sum. *)\n(** ** Inference Rules *)\n(** We will see many definitions like this one during the rest\n of the course, and for purposes of informal discussions, it is\n helpful to have a lightweight notation that makes them easy to\n read and write. _Inference rules_ are one such notation: *)\n(**\n ----------- (b_0)\n beautiful 0\n \n ------------ (b_3)\n beautiful 3\n\n ------------ (b_5)\n beautiful 5 \n\n beautiful n beautiful m\n --------------------------- (b_sum)\n beautiful (n+m) \n*)\n\n(** *** *)\n(** Each of the textual rules above is reformatted here as an\n inference rule; the intended reading is that, if the _premises_\n above the line all hold, then the _conclusion_ below the line\n follows. For example, the rule [b_sum] says that, if [n] and [m]\n are both [beautiful] numbers, then it follows that [n+m] is\n [beautiful] too. If a rule has no premises above the line, then\n its conclusion holds unconditionally.\n\n These rules _define_ the property [beautiful]. That is, if we\n want to convince someone that some particular number is [beautiful],\n our argument must be based on these rules. For a simple example,\n suppose we claim that the number [5] is [beautiful]. To support\n this claim, we just need to point out that rule [b_5] says so.\n Or, if we want to claim that [8] is [beautiful], we can support our\n claim by first observing that [3] and [5] are both [beautiful] (by\n rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n is therefore [beautiful] by rule [b_sum]. This argument can be\n expressed graphically with the following _proof tree_: *)\n(**\n ----------- (b_3) ----------- (b_5)\n beautiful 3 beautiful 5\n ------------------------------- (b_sum)\n beautiful 8 \n*)\n(** *** *)\n(** \n Of course, there are other ways of using these rules to argue that\n [8] is [beautiful], for instance:\n ----------- (b_5) ----------- (b_3)\n beautiful 5 beautiful 3\n ------------------------------- (b_sum)\n beautiful 8 \n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty) *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n(*\nInfinite due to b_0.\n*)\n(** [] *)\n\n(** *** *)\n(** In Coq, we can express the definition of [beautiful] as\n follows: *)\n\nInductive beautiful : nat -> Prop :=\n b_0 : beautiful 0\n| b_3 : beautiful 3\n| b_5 : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n\n(** The first line declares that [beautiful] is a proposition -- or,\n more formally, a family of propositions \"indexed by\" natural\n numbers. (That is, for each number [n], the claim that \"[n] is\n [beautiful]\" is a proposition.) Such a family of propositions is\n often called a _property_ of numbers. Each of the remaining lines\n embodies one of the rules for [beautiful] numbers.\n*)\n(** *** *)\n(** \n The rules introduced this way have the same status as proven \n theorems; that is, they are true axiomatically. \n So we can use Coq's [apply] tactic with the rule names to prove \n that particular numbers are [beautiful]. *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n (* This simply follows from the rule [b_3]. *)\n apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n (* First we use the rule [b_sum], telling Coq how to\n instantiate [n] and [m]. *)\n apply b_sum with (n:=3) (m:=5).\n (* To solve the subgoals generated by [b_sum], we must provide\n evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n have rules for both. *)\n apply b_3.\n apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n intros n B.\n apply b_sum with (n:=8) (m:=n).\n apply eight_is_beautiful.\n apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2) *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n intros n B.\n simpl. apply b_sum.\n apply B.\n apply b_sum.\n apply B.\n apply b_0.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (b_timesm) *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n intros n m B.\n induction m.\n simpl.\n apply b_0.\n simpl.\n apply b_sum.\n apply B.\n apply IHm.\nQed.\n(** [] *)\n\n\n(* ####################################################### *)\n(** ** Induction Over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n declaration tells Coq not only that the constructors [b_0], [b_3],\n [b_5] and [b_sum] are ways to build evidence, but also that these\n four constructors are the _only_ ways to build evidence that\n numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n [beautiful n], then we know that [E] must have one of four shapes:\n\n - [E] is [b_0] (and [n] is [O]),\n - [E] is [b_3] (and [n] is [3]), \n - [E] is [b_5] (and [n] is [5]), or \n - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n evidence that [n1] is beautiful and [E2] is evidence that [n2]\n is beautiful). *)\n\n(** *** *) \n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n n] to see how it was constructed, using the tactics we already\n know. In particular, we can use the [induction] tactic that we\n have already seen for reasoning about inductively defined _data_\n to reason about inductively defined _evidence_.\n\n To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree) *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n notation.\n\n ---------- g_0\n gorgeous 0\n\n gorgeous n\n -------------- g_plus3\n gorgeous (3+n)\n\n gorgeous n\n -------------- g_plus5\n gorgeous (5+n)\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13) *)\nTheorem gorgeous_plus13: forall n, \n gorgeous n -> gorgeous (13+n).\nProof.\n intros.\n induction H.\n apply g_plus3.\n apply g_plus5.\n apply g_plus5.\n apply g_0.\n apply g_plus3.\n apply IHgorgeous.\n apply g_plus5.\n apply IHgorgeous.\nQed.\n(** [] *)\n\n(** *** *)\n(** It seems intuitively obvious that, although [gorgeous] and\n [beautiful] are presented using slightly different rules, they are\n actually the same property in the sense that they are true of the\n same numbers. Indeed, we can prove this. *)\n\nTheorem gorgeous__beautiful : forall n, \n gorgeous n -> beautiful n.\nProof.\n intros n H.\n induction H as [|n'|n'].\n Case \"g_0\".\n apply b_0.\n Case \"g_plus3\". \n apply b_sum. apply b_3.\n apply IHgorgeous.\n Case \"g_plus5\".\n apply b_sum. apply b_5. apply IHgorgeous. \nQed.\n\n(** Notice that the argument proceeds by induction on the _evidence_ [H]! *) \n\n(** Let's see what happens if we try to prove this by induction on [n]\n instead of induction on the evidence [H]. *)\n\nTheorem gorgeous__beautiful_FAILED : forall n, \n gorgeous n -> beautiful n.\nProof.\n intros. induction n as [| n'].\n Case \"n = 0\". apply b_0.\n Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n useful induction hypothesis. Knowing how the property we are\n interested in behaves on the predecessor of [n] doesn't help us\n prove that it holds for [n]. Instead, we would like to be able to\n have induction hypotheses that mention other numbers, such as [n -\n 3] and [n - 5]. This is given precisely by the shape of the\n constructors for [gorgeous]. *)\n\n\n\n\n(** **** Exercise: 2 stars (gorgeous_sum) *)\nTheorem gorgeous_sum : forall n m,\n gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n intros.\n induction H.\n simpl. apply H0.\n simpl. apply g_plus3. apply IHgorgeous.\n simpl. apply g_plus5. apply IHgorgeous.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n intros.\n induction H.\n apply g_0.\n apply g_plus3. apply g_0.\n apply g_plus5. apply g_0.\n apply gorgeous_sum. apply IHbeautiful1. apply IHbeautiful2.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (g_times2) *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y)= z + x + y.\nProof.\n intros.\n rewrite plus_swap.\n rewrite plus_assoc.\n reflexivity.\nQed.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n intros n H. simpl. \n induction H.\n apply g_0.\n rewrite helper_g_times2.\n apply gorgeous_sum.\n apply gorgeous_sum.\n apply g_plus3. apply H.\n apply g_plus3. apply H.\n apply g_0.\n rewrite helper_g_times2.\n apply gorgeous_sum.\n apply gorgeous_sum.\n apply g_plus5. apply H.\n apply g_plus5. apply H.\n apply g_0.\nQed.\n(** [] *)\n\n\n\n\n(* ####################################################### *)\n(** ** [Inversion] on Evidence *)\n\n(** Another situation where we want to analyze evidence for evenness\n is when proving that, if [n] is even, then [pred (pred n)] is\n too. In this case, we don't need to do an inductive proof. The\n right tactic turns out to be [inversion]. *)\n\nTheorem ev_minus2: forall n,\n ev n -> ev (pred (pred n)). \nProof.\n intros n E.\n inversion E as [| n' E'].\n Case \"E = ev_0\". simpl. apply ev_0. \n Case \"E = ev_SS n' E'\". simpl. apply E'. Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n) *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* We cannot apply [E]:\n n' : nat\n E : ev (S n')\n ============================\n ev (pred n')\n*)\n(** [] *)\n\n(** *** *)\n(** Another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n ev (S (S n)) -> ev n.\nProof.\n intros n E. \n inversion E as [| n' E']. \n apply E'. Qed.\n\n(** ** [inversion] revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n Until now, we've only used [inversion] on equality\n propositions, to utilize injectivity of constructors or to\n discriminate between different constructors. But we see here\n that [inversion] can also be applied to analyzing evidence\n for inductively defined propositions.\n\n (You might also expect that [destruct] would be a more suitable\n tactic to use here. Indeed, it is possible to use [destruct], but \n it often throws away useful information, and the [eqn:] qualifier\n doesn't help much in this case.) \n\n Here's how [inversion] works in general. Suppose the name\n [I] refers to an assumption [P] in the current context, where\n [P] has been defined by an [Inductive] declaration. Then,\n for each of the constructors of [P], [inversion I] generates\n a subgoal in which [I] has been replaced by the exact,\n specific conditions under which this constructor could have\n been used to prove [P]. Some of these subgoals will be\n self-contradictory; [inversion] throws these away. The ones\n that are left represent the cases that must be proved to\n establish the original goal.\n\n In this particular case, the [inversion] analyzed the construction\n [ev (S (S n))], determined that this could only have been\n constructed using [ev_SS], and generated a new subgoal with the\n arguments of that constructor as new hypotheses. (It also\n produced an auxiliary equality, which happens to be useless here.)\n We'll begin exploring this more general behavior of inversion in\n what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice) *)\nTheorem SSSSev__even : forall n,\n ev (S (S (S (S n)))) -> ev n.\nProof.\n intros n E.\n inversion E as [|n' E'].\n apply SSev__even in E'.\n apply E'.\nQed.\n\n(** The [inversion] tactic can also be used to derive goals by showing\n the absurdity of a hypothesis. *)\n\nTheorem even5_nonsense : \n ev 5 -> 2 + 2 = 9.\nProof.\n intros.\n apply SSSSev__even in H.\n inversion H.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev) *)\n(** Finding the appropriate thing to do induction on is a\n bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n ev (n+m) -> ev n -> ev m.\nProof.\n intros n m ev_nm ev_n.\n induction ev_n.\n Case \"0\".\n simpl in ev_nm.\n apply ev_nm.\n Case \"S (S n)\".\n simpl in ev_nm.\n apply SSev__even in ev_nm.\n apply IHev_n.\n apply ev_nm.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus) *)\n(** Here's an exercise that just requires applying existing lemmas. No\n induction or even case analysis is needed, but some of the rewriting\n may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n intros n m p ev_nm.\n apply ev_ev__ev.\n replace (n + p + (m + p)) with ((p + p) + (n + m)).\n apply ev_sum.\n replace (p + p) with (double p).\n apply double_even.\n Focus 2.\n apply ev_nm.\n apply double_plus.\n rewrite plus_swap.\n rewrite plus_assoc.\n replace (m + p) with (p + m).\n rewrite plus_assoc.\n rewrite plus_assoc.\n reflexivity.\n apply plus_comm.\nQed.\n(** [] *)\n\n\n\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 4 stars (palindromes) *)\n(** A palindrome is a sequence that reads the same backwards as\n forwards.\n\n - Define an inductive proposition [pal] on [list X] that\n captures what it means to be a palindrome. (Hint: You'll need\n three cases. Your definition should be based on the structure\n of the list; just having a single constructor\n c : forall l, l = rev l -> pal l\n may seem obvious, but will not work very well.)\n \n - Prove that \n forall l, pal (l ++ rev l).\n - Prove that \n forall l, pal l -> l = rev l.\n*)\n\n\nInductive pal {X : Type} : (list X) -> Prop :=\n | p_nil : pal nil\n | p_one : forall x : X, pal [x]\n | p_rec : forall (x : X) (xs : list X), pal xs -> pal (x :: xs ++ [x]).\n\nExample pal_1_2_3_4_4_3_2_1 : pal [1;2;3;4;4;3;2;1].\nProof.\n apply (p_rec 1 [2; 3; 4; 4; 3; 2]).\n apply (p_rec 2 [3; 4; 4; 3]).\n apply (p_rec 3 [4; 4]).\n apply (p_rec 4 []).\n apply p_nil.\nQed.\n\nExample pal_1_2_3_4_3_2_1 : pal [1;2;3;4;3;2;1].\nProof.\n apply (p_rec 1 [2; 3; 4; 3; 2]).\n apply (p_rec 2 [3; 4; 3]).\n apply (p_rec 3 [4]).\n apply p_one.\nQed.\n\nLemma not_app_nil : forall (X : Type) (xs ys : list X) (y : X),\n not (xs ++ y :: ys = []).\nProof.\n unfold not.\n intros.\n destruct xs as [|z zs].\n inversion H.\n inversion H.\nQed.\n\nExample not_pal_1_2 : not (pal [1;2]).\nProof.\n unfold \"~\".\n intros.\n inversion H.\n destruct xs as [|y ys].\n inversion H2. inversion H2. apply not_app_nil in H5. apply H5.\nQed.\n\nExample not_pal_1_2_3_4_5 : not (pal [1;2;3;4;5]).\nProof.\n unfold \"~\".\n intros.\n inversion H.\n destruct xs as [|y ys].\n Case \"nil\".\n inversion H2.\n Case \"cons\".\n inversion H2.\n destruct ys as [|z zs].\n SCase \"nil\".\n inversion H5.\n SCase \"cons\".\n inversion H5.\n destruct zs as [|m ms].\n SSCase \"nil\".\n inversion H7.\n SSCase \"cons\".\n inversion H7.\n destruct ms as [|n ns].\n SSSCase \"nil\".\n inversion H9.\n SSSCase \"cons\".\n inversion H9.\n apply not_app_nil in H11. apply H11.\nQed.\n\nExample not_pal_1_2_3_4_1 : not (pal [1;2;3;4;1]).\nProof.\n unfold \"~\".\n intros.\n inversion H.\n destruct xs as [|y ys].\n Case \"nil\".\n inversion H2.\n Case \"cons\".\n inversion H2.\n destruct ys as [|z zs].\n SCase \"nil\".\n inversion H5.\n SCase \"cons\".\n inversion H5.\n destruct zs as [|m ms].\n SSCase \"nil\".\n inversion H7.\n SSCase \"cons\".\n inversion H7.\n destruct ms as [|n ns].\n rewrite H8 in H1.\n rewrite H6 in H1.\n rewrite H4 in H1.\n inversion H1.\n destruct xs as [|p ps].\n SSSCase \"nil\".\n inversion H11.\n SSSCase \"cons\".\n inversion H11.\n destruct ps as [|s ss].\n SSSSCase \"nil\".\n inversion H14.\n SSSSCase \"cons\".\n inversion H14.\n apply not_app_nil in H16.\n apply H16.\n inversion H9.\n apply not_app_nil in H11.\n apply H11.\nQed.\n\nLemma snoc_app : forall (X : Type) (xs : list X) (x : X),\n snoc xs x = xs ++ [x].\nProof.\n intros.\n induction xs as [|y ys].\n Case \"nil\".\n reflexivity.\n Case \"cons\".\n simpl. rewrite IHys. reflexivity.\nQed.\n\nTheorem pal_app_rev : forall (X : Type) (xs : list X),\n pal (xs ++ rev xs).\nProof.\n intros.\n induction xs.\n Case \"nil\".\n simpl. apply p_nil.\n Case \"succ\".\n simpl. apply (p_rec x) in IHxs.\n rewrite <- snoc_with_append.\n rewrite snoc_app.\n apply IHxs.\nQed.\n\nLemma rev_app : forall (X : Type) (xs : list X) (x : X),\n rev xs = xs ->\n rev (xs ++ [x]) = rev [x] ++ rev xs.\nProof.\n intros.\n simpl.\n rewrite <- rev_snoc.\n rewrite snoc_app.\n reflexivity.\nQed.\n\nTheorem pal_rev : forall (X : Type) (xs : list X),\n pal xs -> xs = rev xs.\nProof.\n intros.\n induction H.\n Case \"nil\".\n reflexivity.\n Case \"one\".\n reflexivity.\n Case \"rec\".\n simpl. rewrite snoc_app.\n rewrite rev_app.\n simpl. rewrite <- IHpal.\n reflexivity.\n symmetry. apply IHpal.\nQed.\n(** [] *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse) *)\n(** Using your definition of [pal] from the previous exercise, prove\n that\n forall l, l = rev l -> pal l.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (subsequence) *)\n(** A list is a _subsequence_ of another list if all of the elements\n in the first list occur in the same order in the second list,\n possibly with some extra elements in between. For example,\n [1,2,3]\n is a subsequence of each of the lists\n [1,2,3]\n [1,1,1,2,2,3]\n [1,2,7,3]\n [5,6,1,9,9,2,7,3,8]\n but it is _not_ a subsequence of any of the lists\n [1,2]\n [1,3]\n [5,6,2,1,7,3,8]\n\n - Define an inductive proposition [subseq] on [list nat] that\n captures what it means to be a subsequence. (Hint: You'll need\n three cases.)\n\n - Prove that subsequence is reflexive, that is, any list is a\n subsequence of itself. \n\n - Prove that for any lists [l1], [l2], and [l3], if [l1] is a\n subsequence of [l2], then [l1] is also a subsequence of [l2 ++\n l3].\n\n - (Optional, harder) Prove that subsequence is transitive -- that\n is, if [l1] is a subsequence of [l2] and [l2] is a subsequence\n of [l3], then [l1] is a subsequence of [l3]. Hint: choose your\n induction carefully!\n*)\n\nInductive subseq {X : Type} : (list X) -> (list X) -> Prop :=\n | s_nil : forall (xs : list X),\n subseq nil xs\n | s_diff : forall (y : X) (xs ys : list X),\n subseq xs ys -> subseq xs (y::ys)\n | s_same : forall (x : X) (xs ys : list X),\n subseq xs ys -> subseq (x::xs) (x::ys).\n\nExample subseq_1_2_3__1_2_3 : subseq [1;2;3] [1;2;3].\nProof.\n apply s_same.\n apply s_same.\n apply s_same.\n apply s_nil.\nQed.\n\nExample subseq_1_2_3__1_1_1_2_2_3 : subseq [1;2;3] [1;1;1;2;2;3].\nProof.\n apply s_same.\n apply s_diff.\n apply s_diff.\n apply s_same.\n apply s_diff.\n apply s_same.\n apply s_nil.\nQed.\n\nExample subseq_1_2_3__1_2_7_3 : subseq [1;2;3] [1;2;7;3].\nProof.\n apply s_same.\n apply s_same.\n apply s_diff.\n apply s_same.\n apply s_nil.\nQed.\n\nExample subseq_1_2_3__5_6_1_9_9_2_7_3_8 : subseq [1;2;3] [5;6;1;9;9;2;7;3;8].\nProof.\n apply s_diff.\n apply s_diff.\n apply s_same.\n apply s_diff.\n apply s_diff.\n apply s_same.\n apply s_diff.\n apply s_same.\n apply s_nil.\nQed.\n\nExample not_subseq_1_2_3__1_2 : not (subseq [1;2;3] [1;2]).\nProof.\n unfold \"~\".\n intros.\n inversion H.\n inversion H2.\n inversion H6.\n inversion H1.\n inversion H6.\n inversion H5.\nQed.\n\nExample not_subseq_1_2_3__1_3 : not (subseq [1;2;3] [1;3]).\nProof.\n unfold \"~\".\n intros.\n inversion H.\n inversion H2.\n inversion H6.\n inversion H1.\n inversion H6.\nQed.\n\nExample not_subseq_1_2_3__5_6_2_1_7_3_8 : not (subseq [1;2;3] [5;6;2;1;7;3;8]).\nProof.\n unfold \"~\".\n intros.\n inversion H.\n inversion H2.\n inversion H6.\n inversion H10.\n inversion H14.\n inversion H18.\n inversion H22.\n inversion H26.\n inversion H13.\n inversion H18.\n inversion H22.\n inversion H26.\nQed.\n\nTheorem subseq_refl : forall (X : Type) (xs : list X),\n subseq xs xs.\nProof.\n induction xs as [|y ys].\n Case \"nil\".\n apply s_nil.\n Case \"cons\".\n apply s_same. apply IHys.\nQed.\n\nLemma app_nil : forall (X : Type) (xs : list X),\n xs ++ [] = xs.\nProof.\n induction xs as [|y ys].\n reflexivity.\n simpl. rewrite IHys. reflexivity.\nQed.\n\nTheorem subseq_app : forall (X : Type) (xs ys zs : list X),\n subseq xs ys ->\n subseq xs (ys ++ zs).\nProof.\n intros.\n induction H.\n Case \"nil\".\n apply s_nil.\n Case \"s_diff\".\n simpl. apply s_diff. apply IHsubseq.\n Case \"s_same\".\n simpl. apply s_same. apply IHsubseq.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (R_provability) *)\n(** Suppose we give Coq the following definition: *)\nInductive R : nat -> list nat -> Prop :=\n | c1 : R 0 []\n | c2 : forall n l, R n l -> R (S n) (n :: l)\n | c3 : forall n l, R (S n) l -> R n l.\n(* Which of the following propositions are provable?\n\n - [R 2 [1,0]]\n - [R 1 [1,2,1,0]]\n - [R 6 [3,2,1,0]]\n*)\nExample R_2__1_0 : R 2 [1;0].\nProof. apply c2. apply c2. apply c1. Qed.\n\nExample R_1__1_2_1_0 : R 1 [1;2;1;0].\nProof.\n apply c3. apply c2. apply c3. apply c3. apply c2.\n apply c2. apply c2. apply c1.\nQed.\n\n(* Obviously, [c1] doesn't match. With [n = 6], the list must start\nwith [5] in order to match [c2]: [forall (l : list nat), R (S 5) (5 ::\nl)], and [c3] cannot be used to achieve that since it only increases\n[n]. So [R 6 [3;2;1;0]] cannot be proved using these rules. *)\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** * Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n [beautiful]) can be thought of as a _property_ -- i.e., it defines\n a subset of [nat], namely those numbers for which the proposition\n is provable. In the same way, a two-argument proposition can be\n thought of as a _relation_ -- i.e., it defines a set of pairs for\n which the proposition is provable. *)\n\nModule LeModule. \n\n\n(** One useful example is the \"less than or equal to\"\n relation on numbers. *)\n\n(** The following definition should be fairly intuitive. It\n says that there are two ways to give evidence that one number is\n less than or equal to another: either observe that they are the\n same number, or give evidence that the first is less than or equal\n to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n | le_n : forall n, le n n\n | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n [le_S] follow the same patterns as proofs about properties, like\n [ev] in chapter [Prop]. We can [apply] the constructors to prove [<=]\n goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n tactics like [inversion] to extract information from [<=]\n hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition. (Notice that,\n although these are the same kind of simple \"unit tests\" as we gave\n for the testing functions we wrote in the first few lectures, we\n must construct their proofs explicitly -- [simpl] and\n [reflexivity] don't do the job, because the proofs aren't just a\n matter of simplifying computations.) *)\n\nTheorem test_le1 :\n 3 <= 3.\nProof.\n (* WORKED IN CLASS *)\n apply le_n. Qed.\n\nTheorem test_le2 :\n 3 <= 6.\nProof.\n (* WORKED IN CLASS *)\n apply le_S. apply le_S. apply le_S. apply le_n. Qed.\n\nTheorem test_le3 :\n (2 <= 1) -> 2 + 2 = 5.\nProof. \n (* WORKED IN CLASS *)\n intros H. inversion H. inversion H2. Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n | nn : next_nat n (S n).\n\nInductive next_even (n:nat) : nat -> Prop :=\n | ne_1 : ev (S n) -> next_even n (S n)\n | ne_2 : ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation) *)\n(** Define an inductive binary relation [total_relation] that holds\n between every pair of natural numbers. *)\nInductive total_relation : nat -> nat -> Prop :=\n | tr : forall (x y : nat), total_relation x y.\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n that never holds. *)\n\nDefinition empty_relation (x y : nat) := False .\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\n(** Here are a number of facts about the [<=] and [<] relations that\n we are going to need later in the course. The proofs make good\n practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n intros.\n induction H0.\n apply H.\n apply le_S.\n apply IHle.\nQed.\n\nTheorem O_le_n : forall n,\n 0 <= n.\nProof.\n induction n as [|n].\n apply le_n.\n apply le_S.\n apply IHn.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n n <= m -> S n <= S m.\nProof. \n intros.\n induction H.\n Case \"n = m\".\n apply le_n.\n Case \"n < m\".\n apply le_S.\n apply IHle.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n S n <= S m -> n <= m.\nProof. \n induction m as [|m'].\n Case \"m = 0\".\n intros.\n inversion H.\n SCase \"S n = 1; n = 0\".\n apply le_n.\n SCase \"S n < 1; n <= 0; n = 0\".\n inversion H1.\n Case \"m = S m'\".\n intros.\n inversion H.\n SCase \"S n = S (S m'); n = S m'\".\n apply le_n.\n SCase \"S n < S (S m'); n <= S m'\".\n apply le_S.\n apply IHm'.\n apply H1.\nQed.\n\nTheorem le_plus_l : forall a b,\n a <= a + b.\nProof. \n induction b as [|b'].\n Case \"b = 0\".\n rewrite plus_0_r.\n apply le_n.\n Case \"b = S b'\".\n rewrite <- plus_n_Sm.\n apply le_S.\n apply IHb'.\nQed.\n\nTheorem Sx_le_Sx_y : forall x y, S x <= S (x + y).\nProof.\n induction y as [|y'].\n Case \"y' = 0\".\n rewrite <- plus_n_O.\n apply le_n.\n Case \"y' = S y\".\n apply le_S.\n rewrite <- plus_n_Sm.\n apply IHy'.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n n1 + n2 < m ->\n n1 < m /\\ n2 < m.\nProof. \n intros.\n unfold \"<\" in H.\n unfold \"<\".\n induction H.\n Case \"S (n1 + n2) = m\".\n split.\n SCase \"S n1 <= S (n1 + n2)\".\n apply Sx_le_Sx_y.\n SCase \"S n2 <= S (n1 + n2)\".\n rewrite plus_comm.\n apply Sx_le_Sx_y.\n Case \"S (n1 + n2) < m\".\n split.\n SCase \"S n1 <= S m\".\n apply le_S.\n (* inversion IHle as [F G]. *)\n apply IHle.\n SCase \"S n2 <= S m\".\n apply le_S.\n apply IHle.\nQed.\n\nTheorem lt_S : forall n m,\n n < m ->\n n < S m.\nProof.\n unfold \"<\".\n intros.\n induction H.\n Case \"S n = m\".\n apply le_S.\n apply le_n.\n Case \"S n < m\".\n apply le_S.\n apply IHle.\nQed.\n\nTheorem ble_nat_true : forall n m,\n ble_nat n m = true -> n <= m.\nProof. \n induction n as [|n'].\n Case \"n' = 0\".\n intros.\n induction m as [|m'].\n SCase \"m' = 0\".\n apply le_n.\n SCase \"m' = S m\".\n apply le_S.\n apply IHm'.\n reflexivity.\n Case \"n' = S n\".\n intros.\n destruct m as [|m'].\n SCase \"m' = 0\".\n inversion H.\n SCase \"m' = S m\".\n inversion H.\n apply IHn' in H1.\n inversion H1.\n SSCase \"n' = m'\".\n reflexivity.\n SSCase \"n' < m'\".\n apply le_S.\n apply n_le_m__Sn_le_Sm.\n apply H0.\nQed.\n\n\nTheorem le_ble_nat : forall n m,\n n <= m ->\n ble_nat n m = true.\nProof.\n (* Hint: This may be easiest to prove by induction on [m]. *)\n induction n as [|n'].\n Case \"n = 0\".\n reflexivity.\n Case \"n = S n'\".\n intros.\n destruct m as [|m'].\n inversion H.\n apply IHn'.\n apply le_S_n.\n apply H.\nQed.\n\nTheorem ble_nat_true_trans : forall n m o,\n ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true. \nProof.\n (* Hint: This theorem can be easily proved without using [induction]. *)\n intros.\n apply le_ble_nat.\n apply ble_nat_true in H.\n apply ble_nat_true in H0.\n apply le_trans with (n:=m).\n apply H.\n apply H0.\nQed.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false) *)\nTheorem ble_nat_false : forall n m,\n ble_nat n m = false -> ~(n <= m).\nProof.\n unfold \"~\".\n intros.\n destruct n as [|n'].\n Case \"n = 0\".\n inversion H.\n Case \"n = S n'\".\n destruct m as [|m'].\n SCase \"m = 0\".\n inversion H0.\n SCase \"m = S m'\".\n apply le_ble_nat in H0.\n rewrite H0 in H.\n inversion H.\nQed.\n(** [] *)\n\n\n(** **** Exercise: 3 stars (R_provability2) *)\nModule R.\n(** We can define three-place relations, four-place relations,\n etc., in just the same way as binary relations. For example,\n consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n | c1 : R 0 0 0 \n | c2 : forall m n o, R m n o -> R (S m) n (S o)\n | c3 : forall m n o, R m n o -> R m (S n) (S o)\n | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n - [R 1 1 2]\n - [R 2 2 6]\n\n - If we dropped constructor [c5] from the definition of [R],\n would the set of provable propositions change? Briefly (1\n sentence) explain your answer.\n \n - If we dropped constructor [c4] from the definition of [R],\n would the set of provable propositions change? Briefly (1\n sentence) explain your answer.\n\nOnly the first one is provable.\n\nNo, the first one is provable without it while the second doesn't hold\nregardless.\n\nDitto.\n[]\n *)\nExample R_1_1_2 : R 1 1 2.\nProof.\n apply c2.\n apply c3.\n apply c1.\nQed.\n\n(** **** Exercise: 3 stars, optional (R_fact) *) \n(** Relation [R] actually encodes a familiar function. State and prove two\n theorems that formally connects the relation and the function. \n That is, if [R m n o] is true, what can we say about [m],\n [n], and [o], and vice versa?\n*)\nTheorem R_plus : forall m n o, R m n o -> m + n = o.\nProof.\n intros.\n induction H.\n Case \"c1\".\n reflexivity.\n Case \"c2\".\n rewrite plus_Sn_m.\n rewrite IHR.\n reflexivity.\n Case \"c3\".\n rewrite <- plus_n_Sm.\n rewrite IHR.\n reflexivity.\n Case \"c4\".\n inversion IHR.\n rewrite <- plus_n_Sm in H1.\n inversion H1.\n rewrite plus_comm.\n reflexivity.\n Case \"c5\".\n rewrite plus_comm.\n apply IHR.\nQed.\n\nExample not_R_2_2_6 : ~(R 2 2 6).\nProof.\n unfold \"~\".\n intros.\n apply R_plus in H.\n inversion H.\nQed.\n\nTheorem plus_R : forall m n o, m + n = o -> R m n o.\nProof.\n intros.\n induction H.\n induction m as [|m'].\n Case \"m = 0\".\n simpl.\n induction n as [|n'].\n SCase \"n = 0\".\n apply c1.\n apply c3.\n SCase \"n = S n'\".\n apply IHn'.\n Case \"m = S m'\".\n rewrite plus_Sn_m.\n apply c2.\n apply IHm'.\nQed.\n(** [] *)\n\nEnd R.\n\n\n(* ##################################################### *)\n(** * Programming with Propositions Revisited *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n like \"two plus two equals four.\" In Coq, propositions are written\n as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n propositions. Simply _being_ a proposition is one thing; being\n _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 : \n 2 + 2 = 4.\nProof. reflexivity. Qed.\n\n(** But they can be used in many other ways. For example, we have also seen that\n we can give a name to a proposition using a [Definition], just as we have\n given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop := 2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true : \n plus_fact.\nProof. reflexivity. Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions. \n\n - We can define a new proposition primitively using [Inductive].\n\n - Given two expressions [e1] and [e2] of the same type, we can\n form the proposition [e1 = e2], which states that their\n values are equal.\n\n - We can combine propositions using implication and\n quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even. \n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n three equivalent ways: (1) \"[even] is a _function_ from numbers to\n propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n by a number [n],\" or (3) \"[even] is a _property_ of numbers.\" *)\n\n(** Propositions -- including parameterized propositions -- are\n first-class citizens in Coq. For example, we can define functions\n from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n as arguments to a function. \n\n The first function, [true_for_all_numbers], takes a proposition\n [P] as argument and builds the proposition that [P] is true for\n all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n that, if [P] is true for some natural number [n'], then it is also\n true by the successor of [n'] -- i.e. that [P] is _preserved by\n successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n forall (P:nat->Prop),\n true_for_zero P ->\n preserved_by_S P -> \n true_for_all_numbers P. \n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even) *)\n(** Complete the definition of the [combine_odd_even] function\n below. It takes as arguments two properties of numbers [Podd] and\n [Peven]. As its result, it should return a new property [P] such\n that [P n] is equivalent to [Podd n] when [n] is odd, and\n equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n fun n => if oddb n then Podd n else Peven n.\n\n(** To test your definition, see whether you can prove the following\n facts: *)\n\nTheorem combine_odd_even_intro : \n forall (Podd Peven : nat -> Prop) (n : nat),\n (oddb n = true -> Podd n) ->\n (oddb n = false -> Peven n) ->\n combine_odd_even Podd Peven n.\nProof.\n intros.\n unfold combine_odd_even.\n destruct (oddb n) as [|n'].\n apply H.\n reflexivity.\n apply H0.\n reflexivity.\nQed.\n\nTheorem combine_odd_even_elim_odd :\n forall (Podd Peven : nat -> Prop) (n : nat),\n combine_odd_even Podd Peven n ->\n oddb n = true ->\n Podd n.\nProof.\n intros.\n unfold combine_odd_even in H.\n rewrite H0 in H.\n apply H.\nQed.\n\nTheorem combine_odd_even_elim_even :\n forall (Podd Peven : nat -> Prop) (n : nat),\n combine_odd_even Podd Peven n ->\n oddb n = false ->\n Peven n.\nProof.\n intros.\n unfold combine_odd_even in H.\n rewrite H0 in H.\n apply H.\nQed.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n parameterized propositions using [Definition], then can we also\n define them using [Fixpoint]? Of course we can! However, this\n kind of \"recursive parameterization\" doesn't correspond to\n anything very familiar from everyday mathematics. The following\n exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)\n(** Define a recursive function\n [true_upto_n__true_everywhere] that makes\n [true_upto_n_example] work. *)\n\nFixpoint true_upto_n__true_everywhere (n:nat) (P : nat -> Prop) : Prop :=\n match n with\n | 0 => forall m : nat, P m\n | S n' => P n -> true_upto_n__true_everywhere n' P\n end.\n\nExample true_upto_n_example :\n (true_upto_n__true_everywhere 3 (fun n => even n))\n = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity. Qed.\n(** [] *)\n\n\n(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)\n\n\n", "meta": {"author": "nkaretnikov", "repo": "software-foundations", "sha": "8347b96ba043a184b91b264808d6f2c2e1f3a138", "save_path": "github-repos/coq/nkaretnikov-software-foundations", "path": "github-repos/coq/nkaretnikov-software-foundations/software-foundations-8347b96ba043a184b91b264808d6f2c2e1f3a138/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.9046505447409665, "lm_q1q2_score": 0.8526392172943128}} {"text": "Require Export ZArith.\nOpen Scope Z_scope.\n\nInductive expr : Set :=\n| Cte : Z -> expr\n| Plus : expr -> expr -> expr\n| Moins : expr -> expr -> expr\n| Mult : expr -> expr -> expr\n| Div : expr -> expr -> expr.\n\nInductive eval : expr -> Z -> Prop :=\n| ECte : forall c : Z , eval (Cte c) c\n| EPlus : forall (e1 e2 : expr) (v v1 v2 : Z),\neval e1 v1 -> eval e2 v2 -> v = v1 + v2 ->\neval (Plus e1 e2) v\n| EMoins : forall (e1 e2 :expr) (v v1 v2 : Z),\neval e1 v1 -> eval e2 v2 -> v = v1 - v2 ->\neval (Moins e1 e2) v\n| EMult : forall (e1 e2 : expr) (v v1 v2 : Z),\neval e1 v1 -> eval e2 v2 -> v = v1 * v2 ->\neval (Mult e1 e2) v\n| EDiv : forall (e1 e2 : expr) (v v1 v2 : Z),\neval e1 v1 -> eval e2 v2 -> v = v1 / v2 ->\neval (Div e1 e2) v.\n\nInductive eval2 : expr -> Z -> Prop :=\n| ECte2 : forall c : Z , eval2 (Cte c) c\n| EPlus2 : forall (e1 e2 : expr) (v1 v2 : Z),\neval2 e1 v1 -> eval2 e2 v2 ->\neval2 (Plus e1 e2) (v1 + v2)\n| EMoins2 : forall (e1 e2 :expr) (v1 v2 : Z),\neval2 e1 v1 -> eval2 e2 v2 ->\neval2 (Moins e1 e2) (v1 - v2)\n| EMult2 : forall (e1 e2 : expr) (v1 v2 : Z),\neval2 e1 v1 -> eval2 e2 v2 -> \neval2 (Mult e1 e2) (v1 * v2)\n| EDiv2 : forall (e1 e2 : expr) (v1 v2 : Z),\neval2 e1 v1 -> eval2 e2 v2 ->\neval2 (Div e1 e2) (v1 / v2).\n\nFixpoint f_eval (e:expr) : Z :=\n match e with \n | Cte c => c\n | Plus e1 e2 =>\n let v1 := f_eval e1 in\n let v2 := f_eval e2 in \n v1 + v2\n | Moins e1 e2 =>\n let v1 := f_eval e1 in\n let v2 := f_eval e2 in\n v1 - v2\n | Mult e1 e2 =>\n let v1 := f_eval e1 in\n let v2 := f_eval e2 in \n v1 * v2\n | Div e1 e2 =>\n let v1 := f_eval e1 in\n let v2 := f_eval e2 in \n v1 / v2\nend.\n\n\nDefinition t1 : expr := Plus (Cte 1) (Cte 2).\n\nLemma add : eval t1 3.\nunfold t1.\neapply EPlus.\neapply ECte.\neapply ECte.\nreflexivity.\nQed.\n\nEval compute in (f_eval t1).\n\nDefinition t2 : expr := Moins (Cte 3) (Cte 2).\n\nLemma moins : eval t2 1.\nunfold t2.\neapply EMoins.\neapply ECte.\neapply ECte.\nreflexivity.\nQed.\n\n\nDefinition t3 : expr := Mult (Cte 3) (Cte 2).\n\nLemma mult : eval t3 6.\nunfold t3.\neapply EMult.\neapply ECte.\neapply ECte.\nreflexivity.\nQed.\n\n\nDefinition t4 : expr := Div (Cte 4) (Cte 2).\n\nLemma div : eval t4 2.\n\nunfold t4.\neapply EDiv.\napply ECte.\napply ECte.\nsimpl.\nreflexivity.\nQed.\n\n\nLtac calcul :=\nintros;\n(repeat\n match goal with \n | |- (eval (Cte _)_) => eapply ECte\n | |- (eval( Plus _ _)_) => eapply EPlus\n | |- (eval( Moins _ _)_)=> eapply EMoins\n | |- (eval (Mult _ _)_) => eapply EMult\n | |- (eval (Div _ _)_) => eapply EDiv\n end);\ntry reflexivity.\n\nDefinition test_calcul : expr := Div (Mult (Cte 3) (Cte 2)) (Cte 2).\n\nLemma test_calcul_eval : eval test_calcul 3.\nunfold test_calcul.\ncalcul.\n\nLemma correction :\n forall (e : expr) (v : Z),\n v=f_eval(e) -> eval e v.\nintros.\nrewrite H.\nelim e;intros.\neapply ECte.\neapply EPlus.\napply H0.\napply H1.\nreflexivity.\n\neapply EMoins.\napply H0.\napply H1.\nreflexivity.\n\neapply EMult.\napply H0.\napply H1.\nreflexivity.\n\neapply EDiv.\napply H0.\napply H1.\nreflexivity.\nQed.\n\nLemma completude:\n forall (e : expr) (v :Z),\n eval e v -> f_eval e = v.\nintros.\n", "meta": {"author": "hogoww", "repo": "spec_formelles", "sha": "01818eac3794a70a6888c5a791971646dcf777af", "save_path": "github-repos/coq/hogoww-spec_formelles", "path": "github-repos/coq/hogoww-spec_formelles/spec_formelles-01818eac3794a70a6888c5a791971646dcf777af/tp3.exparith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920617, "lm_q2_score": 0.8872045922259088, "lm_q1q2_score": 0.8525607685927694}} {"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export Lists.\nRequire Export Logic.\nRequire Import DmoonTactics.\n\n\n(* ####################################################### *)\n(** * From Boolean Functions to Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n number for evenness, yielding [true] if so. We can use this\n function to define the _proposition_ that some number [n] is\n even: *)\n\nDefinition even (n:nat) : Prop := \n evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n returns [true] when applied to [n].\" \n\n Note that here we have given a name\n to a proposition using a [Definition], just as we have\n given names to expressions of other sorts. This isn't a fundamentally\n new kind of proposition; it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n directly. Instead of going via the [evenb] function (\"a number is\n even if a certain computation yields [true]\"), we can say what the\n concept of evenness means by giving two different ways of\n presenting _evidence_ that a number is even. *)\n\n(** * Inductively Defined Propositions *)\n\nInductive ev : nat -> Prop :=\n | ev_0 : ev O\n | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(** This definition says that there are two ways to give\n evidence that a number [m] is even. First, [0] is even, and\n [ev_0] is evidence for this. Second, if [m = S (S n)] for some\n [n] and we can give evidence [e] that [n] is even, then [m] is\n also even, and [ev_SS n e] is the evidence. *)\n\n\n(** **** Exercise: 1 star (double_even) *)\n\nTheorem double_even : forall n,\n ev (double n).\nProof.\n intros. induction n.\n - unfold double. apply ev_0.\n - unfold double in *.\n apply ev_SS.\n apply IHn.\nQed.\n(** [] *)\n\n\n(** *** Discussion: Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n phrased in two different ways -- indirectly, via a boolean testing\n function [evenb], or directly, by inductively describing what\n constitutes evidence for evenness. These two ways of defining\n evenness are about equally easy to state and work with. Which we\n choose is basically a question of taste.\n\n However, for many other properties of interest, the direct\n inductive definition is preferable, since writing a testing\n function may be awkward or even impossible. \n\n One such property is [beautiful]. This is a perfectly sensible\n definition of a set of numbers, but we cannot translate its\n definition directly into a Coq Fixpoint (or into a recursive\n function in any other common programming language). We might be\n able to find a clever way of testing this property using a\n [Fixpoint] (indeed, it is not too hard to find one in this case),\n but in general this could require arbitrarily deep thinking. In\n fact, if the property we are interested in is uncomputable, then\n we cannot define it as a [Fixpoint] no matter how hard we try,\n because Coq requires that all [Fixpoint]s correspond to\n terminating computations.\n\n On the other hand, writing an inductive definition of what it\n means to give evidence for the property [beautiful] is\n straightforward. *)\n\n\n\n(** **** Exercise: 1 star (ev__even) *)\n(** Here is a proof that the inductive definition of evenness implies\n the computational one. *)\n\nTheorem ev__even : forall n,\n ev n -> even n.\nProof.\n intros n E. induction E as [| n' E'].\n Case \"E = ev_0\". \n unfold even. reflexivity.\n Case \"E = ev_SS n' E'\". \n unfold even. apply IHE'. \nQed.\n\n(** Could this proof also be carried out by induction on [n] instead\n of [E]? If not, why not? *)\n\nTheorem ev__even' : forall n,\n ev n -> even n.\nProof.\n intros n E. induction n.\n - unfold even. reflexivity.\n - Abort.\n (* \n Ah, here is the problem. Induction on\n nat asks us to show that the statement\n holds for [S n] if it holds for [n]. But\n this is not compatible with the inductive\n definition of ev and even.\n *)\n \n(** [] *)\n\n(** The induction principle for inductively defined propositions does\n not follow quite the same form as that of inductively defined\n sets. For now, you can take the intuitive view that induction on\n evidence [ev n] is similar to induction on [n], but restricts our\n attention to only those numbers for which evidence [ev n] could be\n generated. We'll look at the induction principle of [ev] in more\n depth below, to explain what's really going on. *)\n\n(** **** Exercise: 1 star (l_fails) *)\n(** The following proof attempt will not succeed. *)\nTheorem l : forall n,\n ev n.\nProof.\n intros n. induction n.\n Case \"O\". simpl. apply ev_0.\n Case \"S\". Abort.\n\n(** Intuitively, we expect the proof to fail because not every\n number is even. However, what exactly causes the proof to fail?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars (ev_sum) *)\n(** Here's another exercise requiring induction. *)\n\nTheorem ev_sum : forall n m,\n ev n -> ev m -> ev (n+m).\nProof. \n intros. induction H.\n - assumption.\n - apply ev_SS.\n assumption.\nQed.\n(** [] *)\n\n\n(* ##################################################### *)\n(** ** Example *)\n\n(** As a running example, let's\n define a simple property of natural numbers -- we'll call it\n \"[beautiful].\" *)\n\n(** Informally, a number is [beautiful] if it is [0], [3], [5], or the\n sum of two [beautiful] numbers. \n\n More pedantically, we can define [beautiful] numbers by giving four\n rules:\n\n - Rule [b_0]: The number [0] is [beautiful].\n - Rule [b_3]: The number [3] is [beautiful]. \n - Rule [b_5]: The number [5] is [beautiful]. \n - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is\n their sum. *)\n(** ** Inference Rules *)\n(** We will see many definitions like this one during the rest\n of the course, and for purposes of informal discussions, it is\n helpful to have a lightweight notation that makes them easy to\n read and write. _Inference rules_ are one such notation: *)\n(**\n ----------- (b_0)\n beautiful 0\n \n ------------ (b_3)\n beautiful 3\n\n ------------ (b_5)\n beautiful 5 \n\n beautiful n beautiful m\n --------------------------- (b_sum)\n beautiful (n+m) \n*)\n\n(** *** *)\n(** Each of the textual rules above is reformatted here as an\n inference rule; the intended reading is that, if the _premises_\n above the line all hold, then the _conclusion_ below the line\n follows. For example, the rule [b_sum] says that, if [n] and [m]\n are both [beautiful] numbers, then it follows that [n+m] is\n [beautiful] too. If a rule has no premises above the line, then\n its conclusion holds unconditionally.\n\n These rules _define_ the property [beautiful]. That is, if we\n want to convince someone that some particular number is [beautiful],\n our argument must be based on these rules. For a simple example,\n suppose we claim that the number [5] is [beautiful]. To support\n this claim, we just need to point out that rule [b_5] says so.\n Or, if we want to claim that [8] is [beautiful], we can support our\n claim by first observing that [3] and [5] are both [beautiful] (by\n rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n is therefore [beautiful] by rule [b_sum]. This argument can be\n expressed graphically with the following _proof tree_: *)\n(**\n ----------- (b_3) ----------- (b_5)\n beautiful 3 beautiful 5\n ------------------------------- (b_sum)\n beautiful 8 \n*)\n(** *** *)\n(** \n Of course, there are other ways of using these rules to argue that\n [8] is [beautiful], for instance:\n ----------- (b_5) ----------- (b_3)\n beautiful 5 beautiful 3\n ------------------------------- (b_sum)\n beautiful 8 \n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty) *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* An infinite number of ways, since we have that [0] is [beautiful]. *)\n(** [] *)\n\n(** *** *)\n(** In Coq, we can express the definition of [beautiful] as\n follows: *)\n\nInductive beautiful : nat -> Prop :=\n b_0 : beautiful 0\n| b_3 : beautiful 3\n| b_5 : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n\n(** The first line declares that [beautiful] is a proposition -- or,\n more formally, a family of propositions \"indexed by\" natural\n numbers. (That is, for each number [n], the claim that \"[n] is\n [beautiful]\" is a proposition.) Such a family of propositions is\n often called a _property_ of numbers. Each of the remaining lines\n embodies one of the rules for [beautiful] numbers.\n*)\n(** *** *)\n(** \n The rules introduced this way have the same status as proven \n theorems; that is, they are true axiomatically. \n So we can use Coq's [apply] tactic with the rule names to prove \n that particular numbers are [beautiful]. *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n (* This simply follows from the rule [b_3]. *)\n apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n (* First we use the rule [b_sum], telling Coq how to\n instantiate [n] and [m]. *)\n apply b_sum with (n:=3) (m:=5).\n (* To solve the subgoals generated by [b_sum], we must provide\n evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n have rules for both. *)\n apply b_3.\n apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n intros n B.\n apply b_sum with (n:=8) (m:=n).\n apply eight_is_beautiful.\n apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2) *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n intros. simpl.\n apply b_sum with (n := n) (m := n+0).\n - assumption.\n - apply b_sum with (n := n) (m := 0).\n + assumption.\n + apply b_0.\nQed.\n(** [] *)\n\n\n\n(** **** Exercise: 3 stars (b_timesm) *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n intros. induction m.\n - simpl. apply b_0.\n - simpl.\n apply b_sum; assumption.\nQed.\n(** [] *)\n\n\n(* ####################################################### *)\n(** ** Induction Over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n declaration tells Coq not only that the constructors [b_0], [b_3],\n [b_5] and [b_sum] are ways to build evidence, but also that these\n four constructors are the _only_ ways to build evidence that\n numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n [beautiful n], then we know that [E] must have one of four shapes:\n\n - [E] is [b_0] (and [n] is [O]),\n - [E] is [b_3] (and [n] is [3]), \n - [E] is [b_5] (and [n] is [5]), or \n - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n evidence that [n1] is beautiful and [E2] is evidence that [n2]\n is beautiful). *)\n\n(** *** *) \n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n n] to see how it was constructed, using the tactics we already\n know. In particular, we can use the [induction] tactic that we\n have already seen for reasoning about inductively defined _data_\n to reason about inductively defined _evidence_.\n\n To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree) *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n notation.\n \n(* FILL IN HERE *)\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13) *)\nTheorem gorgeous_plus13: forall n, \n gorgeous n -> gorgeous (13+n).\nProof.\n intros.\n apply g_plus3.\n apply g_plus5.\n apply g_plus5.\n assumption.\nQed.\n(** [] *)\n\n(** *** *)\n(** It seems intuitively obvious that, although [gorgeous] and\n [beautiful] are presented using slightly different rules, they are\n actually the same property in the sense that they are true of the\n same numbers. Indeed, we can prove this. *)\n\nTheorem gorgeous__beautiful : forall n, \n gorgeous n -> beautiful n.\nProof.\n intros n H.\n induction H as [|n'|n'].\n Case \"g_0\".\n apply b_0.\n Case \"g_plus3\". \n apply b_sum. apply b_3.\n apply IHgorgeous.\n Case \"g_plus5\".\n apply b_sum. apply b_5. apply IHgorgeous. \nQed.\n\n(** Notice that the argument proceeds by induction on the _evidence_ [H]! *) \n\n(** Let's see what happens if we try to prove this by induction on [n]\n instead of induction on the evidence [H]. *)\n\nTheorem gorgeous__beautiful_FAILED : forall n, \n gorgeous n -> beautiful n.\nProof.\n intros. induction n as [| n'].\n Case \"n = 0\". apply b_0.\n Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n useful induction hypothesis. Knowing how the property we are\n interested in behaves on the predecessor of [n] doesn't help us\n prove that it holds for [n]. Instead, we would like to be able to\n have induction hypotheses that mention other numbers, such as [n -\n 3] and [n - 5]. This is given precisely by the shape of the\n constructors for [gorgeous]. *)\n\n\n\n\n(** **** Exercise: 2 stars (gorgeous_sum) *)\nTheorem gorgeous_sum : forall n m,\n gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n intros. induction H.\n - assumption.\n - apply g_plus3.\n assumption.\n - apply g_plus5.\n assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n intros. induction H.\n - apply g_0.\n - apply g_plus3. apply g_0.\n - apply g_plus5. apply g_0.\n - apply gorgeous_sum; assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (g_times2) *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y)= z + x + y.\nProof.\n intros. \n rewrite plus_assoc.\n rewrite plus_comm with (n := x) (m := z).\n reflexivity.\nQed.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n intros n H. simpl. \n induction H.\n - apply g_0.\n - apply g_plus3. fold plus.\n rewrite helper_g_times2 with (x := n) (z := 3 + n) (y := 0).\n apply g_plus3. fold plus.\n rewrite <- plus_assoc.\n assumption.\n - apply g_plus5. fold plus.\n rewrite helper_g_times2 with (x := n) (z := 5 + n) (y := 0).\n apply g_plus5. fold plus.\n rewrite <- plus_assoc.\n assumption.\nQed.\n(** [] *)\n\n\n\n\n(* ####################################################### *)\n(** ** [Inversion] on Evidence *)\n\n(** Another situation where we want to analyze evidence for evenness\n is when proving that, if [n] is even, then [pred (pred n)] is\n too. In this case, we don't need to do an inductive proof. The\n right tactic turns out to be [inversion]. *)\n\n(*\nLemma sum_0 : forall n m,\n n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n induction n; split.\n - reflexivity.\n - simpl in H. apply H.\n - discriminate.\n - discriminate.\nQed.\n\nTheorem ev_double : forall n m,\n ev (n + m) -> (ev n /\\ ev m) \\/ (~(ev n) /\\ ~(ev m)).\nProof.\n intros.\n inversion H.\n - symmetry in H1.\n apply sum_0 in H1.\n inversion H1.\n apply or_introl.\n split.\n + rewrite H0. apply ev_0.\n + rewrite H2. apply ev_0.\n - destruct \n*)\n\nTheorem ev_minus2: forall n,\n ev n -> ev (pred (pred n)). \nProof.\n intros n E.\n inversion E as [| n' E'].\n Case \"E = ev_0\". simpl. apply ev_0. \n Case \"E = ev_SS n' E'\". simpl. apply E'. Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n) *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** *)\n(** Another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n ev (S (S n)) -> ev n.\nProof.\n intros n E. \n inversion E as [| n' E']. \n apply E'. Qed.\n\n(** ** [inversion] revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n Until now, we've only used [inversion] on equality\n propositions, to utilize injectivity of constructors or to\n discriminate between different constructors. But we see here\n that [inversion] can also be applied to analyzing evidence\n for inductively defined propositions.\n\n (You might also expect that [destruct] would be a more suitable\n tactic to use here. Indeed, it is possible to use [destruct], but \n it often throws away useful information, and the [eqn:] qualifier\n doesn't help much in this case.) \n\n Here's how [inversion] works in general. Suppose the name\n [I] refers to an assumption [P] in the current context, where\n [P] has been defined by an [Inductive] declaration. Then,\n for each of the constructors of [P], [inversion I] generates\n a subgoal in which [I] has been replaced by the exact,\n specific conditions under which this constructor could have\n been used to prove [P]. Some of these subgoals will be\n self-contradictory; [inversion] throws these away. The ones\n that are left represent the cases that must be proved to\n establish the original goal.\n\n In this particular case, the [inversion] analyzed the construction\n [ev (S (S n))], determined that this could only have been\n constructed using [ev_SS], and generated a new subgoal with the\n arguments of that constructor as new hypotheses. (It also\n produced an auxiliary equality, which happens to be useless here.)\n We'll begin exploring this more general behavior of inversion in\n what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice) *)\nTheorem SSSSev__even : forall n,\n ev (S (S (S (S n)))) -> ev n.\nProof.\n intros.\n apply SSev__even.\n apply SSev__even.\n assumption.\nQed.\n\n(** The [inversion] tactic can also be used to derive goals by showing\n the absurdity of a hypothesis. *)\n\nTheorem even5_nonsense : \n ev 5 -> 2 + 2 = 9.\nProof.\n intros.\n inversion H.\n inversion H1.\n inversion H3.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev) *)\n(** Finding the appropriate thing to do induction on is a\n bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n ev (n+m) -> ev n -> ev m.\nProof.\n intros. \n generalize dependent H. generalize dependent m.\n induction H0.\n - intros. assumption.\n - intros.\n apply IHev.\n apply SSev__even.\n assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus) *)\n(** Here's an exercise that just requires applying existing lemmas. No\n induction or even case analysis is needed, but some of the rewriting\n may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n intros.\n apply ev_ev__ev with (n := n + n) (m := m + p).\n - rewrite <- plus_assoc with (n := n) (m := n) (p := m + p).\n rewrite plus_assoc with (n := n) (m := m) (p := p).\n rewrite plus_comm with (n := n) (m := m).\n rewrite <- plus_assoc with (n := m) (m := n) (p := p).\n rewrite plus_assoc with (n := n) (m := m) (p := n + p).\n apply ev_sum; assumption.\n - rewrite <- double_plus.\n apply double_even.\nQed.\n(** [] *)\n\n\n\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 4 stars (palindromes) *)\n(** A palindrome is a sequence that reads the same backwards as\n forwards.\n\n - Define an inductive proposition [pal] on [list X] that\n captures what it means to be a palindrome. (Hint: You'll need\n three cases. Your definition should be based on the structure\n of the list; just having a single constructor\n c : forall l, l = rev l -> pal l\n may seem obvious, but will not work very well.)\n \n - Prove that \n forall l, pal (l ++ rev l).\n - Prove that \n forall l, pal l -> l = rev l.\n*)\n\nInductive pal {X : Type} : list X -> Prop :=\n | pal_nil : pal []\n | pal_single : forall x : X, pal [x]\n | pal_ht : forall (x : X) (p : list X), pal p -> pal (x :: p ++ [x]).\n\nLemma snoc_append :\n forall {X : Type} (x : X) (l : list X),\n snoc l x = l ++ [x].\nProof.\n intros. induction l.\n - reflexivity.\n - simpl. rewrite IHl. reflexivity.\nQed.\n\nLemma app_assoc : \n forall {X : Type} (l1 l2 l3 : list X),\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n intros X l1. induction l1.\n - intros. simpl. reflexivity.\n - intros. simpl. rewrite IHl1. reflexivity.\nQed.\n\nTheorem pal_mirror : \n forall {X : Type} (l : list X),\n pal (l ++ rev l).\nProof.\n intros. induction l.\n - apply pal_nil.\n - simpl.\n rewrite snoc_append.\n rewrite <- app_assoc. \n apply pal_ht.\n assumption.\nQed.\n\nTheorem palindrome :\n forall {X : Type} (l : list X),\n pal l -> l = rev l.\nProof.\n intros. \n induction H; try reflexivity.\n simpl.\n rewrite <- snoc_append.\n rewrite rev_snoc.\n simpl.\n rewrite <- IHpal.\n reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse) *)\n(** Using your definition of [pal] from the previous exercise, prove\n that\n forall l, l = rev l -> pal l.\n*)\n\n(* An initial approach using strong induction *)\n\nInductive list_length {X : Type} : list X -> nat -> Prop := \n | length_nil : list_length [] 0\n | length_n : forall x l n, list_length l n -> list_length (x :: l) (S n).\n\nTheorem blah : \n forall {X : Type} (l : list X),\n l = nil \\/ \n (exists (x : X), l = [x]) \\/ \n (exists (x y : X) (l' : list X), l = x :: l' ++ [y]).\nProof.\n induction l.\n - apply or_introl. reflexivity.\n - intuition.\n + apply or_intror.\n apply or_introl.\n exists x.\n rewrite H.\n reflexivity.\n + apply or_intror.\n apply or_intror.\n destruct H0 as [x0 H0].\n exists x.\n exists x0.\n exists [].\n rewrite H0.\n reflexivity.\n + apply or_intror.\n apply or_intror.\n destruct H0 as [x0 [y [l' H0]]].\n exists x.\n exists y.\n exists (x0 :: l').\n rewrite H0.\n reflexivity.\nQed.\n\nLemma rev_app_single :\n forall {X : Type} (x : X) (l : list X),\n rev (l ++ [x]) = x :: (rev l).\nProof.\n induction l.\n - simpl in *. reflexivity.\n - simpl in *.\n rewrite IHl.\n simpl.\n reflexivity.\nQed.\n\nLemma remove_head_length :\n forall {X : Type} (x : X) (l : list X) (n : nat),\n list_length (x :: l) (S n) -> list_length l n.\nProof.\n Admitted.\n\nLemma remove_tail_length :\n forall {X : Type} (x : X) (l : list X) (n : nat),\n list_length (l ++ [x]) (S n) -> list_length l n.\nProof.\n Admitted.\n\nLemma remove_head_tail_length: \n forall {X : Type} (x y : X) (l : list X) (n : nat),\n list_length (x :: l ++ [y]) n ->\n exists n', n = S (S n') /\\ list_length l n'.\nProof.\n Admitted.\n \nLemma snoc_inversion : \n forall {X : Type} (l1 l2 : list X) (x : X),\n snoc l1 x = snoc l2 x -> l1 = l2.\nProof.\n Admitted.\n\nLemma palindrome_converse' :\n forall {X : Type} (n m : nat) (l : list X),\n m < n ->\n list_length l m ->\n l = rev l -> pal l.\nProof.\n induction n.\n - intros. inversion H.\n - intros.\n inversion H.\n + pose proof (blah l).\n intuition.\n * rewrite H4. apply pal_nil.\n * destruct H2 as [x H2].\n rewrite H2.\n apply pal_single.\n * destruct H2 as [x [y [l' H2]]].\n rewrite H2 in H1.\n simpl in *.\n rewrite rev_app_single in H1.\n simpl in *.\n inversion H1.\n rewrite H5 in *.\n rewrite H2.\n apply pal_ht.\n rewrite H2 in H0.\n pose proof (remove_head_tail_length y y l' m H0).\n destruct H4 as [n' [H4 H4']].\n apply IHn with (m := n').\n rewrite <- H3. rewrite H4.\n apply le_S. apply le_n.\n assumption.\n rewrite <- snoc_append in H6.\n apply snoc_inversion in H6.\n assumption.\n + apply IHn with m; assumption.\nQed.\n\n\n(* ************** *)\n\n(* A much sleeker approach that defines a new inductive structure on lists *)\n\n\nInductive lsplit {X : Type} : list X -> Prop :=\n | l_nil : lsplit []\n | l_single : forall (x : X), lsplit [x]\n | l_tips : forall (x y : X) (l : list X), lsplit l -> lsplit (x :: l ++ [y]).\n\nTheorem list_tips : \n forall {X : Type} (l : list X),\n l = nil \\/ \n (exists (x : X), l = [x]) \\/ \n (exists (x y : X) (l' : list X), l = x :: l' ++ [y]).\nProof.\n induction l.\n - apply or_introl. reflexivity.\n - intuition.\n + apply or_intror, or_introl.\n exists x.\n rewrite H.\n reflexivity.\n + apply or_intror, or_intror.\n destruct H0 as [x0 H0].\n exists x, x0, [].\n rewrite H0.\n reflexivity.\n + apply or_intror, or_intror.\n destruct H0 as [x0 [y [l' H0]]].\n exists x, y, (x0 :: l').\n rewrite H0.\n reflexivity.\nQed.\n\nLemma all_lists_have_length : \n forall (X : Type) (l : list X),\n exists n : nat, length l = n.\nProof.\n Admitted.\n\nLemma remove_head_length' :\n forall (X : Type) (l : list X) (x : X) (n : nat),\n length (x :: l) < S n -> length l < n.\nProof.\n Admitted.\n \nLemma remove_tail_length' : \n forall (X : Type) (l : list X) (x : X) (n : nat),\n length (l ++ [x]) < S n -> length l < n.\nProof.\n Admitted.\n \nTheorem all_lists_lsplittable' :\n forall (X : Type) (n : nat) (l : list X),\n length l < n ->\n lsplit l.\nProof.\n induction n; intros; inversion H.\n destruct l.\n - apply l_nil.\n - pose proof (list_tips l).\n intuition.\n + rewrite H2. apply l_single.\n + destruct H0 as [x0 H0].\n rewrite H0.\n assert_rewrite_by_refl ([x; x0] = x :: [] ++ [x0]).\n apply l_tips, l_nil.\n + destruct H0 as [x0 [y [l' H0]]]. \n rewrite H0 in *.\n assert_rewrite_by_refl (x :: x0 :: l' ++ [y] = x :: (x0 :: l') ++ [y]).\n apply l_tips, IHn.\n apply remove_tail_length' with (x := y).\n apply remove_head_length' with (x := x).\n apply Lt.lt_trans with (m := S n); auto.\n - apply IHn; assumption.\nQed. \n\nTheorem all_lists_lsplittable : \n forall (X : Type) (l : list X),\n lsplit l.\nProof.\n intros.\n destruct (all_lists_have_length X l) as [n H].\n apply (all_lists_lsplittable' X (S n) l).\n rewrite H.\n apply le_n.\nQed.\n\nLemma rev_snoc : \n forall (X : Type) (l : list X) (x : X),\n rev (snoc l x) = x :: rev l.\nProof.\n Admitted.\n\nLemma snoc_inj : \n forall (X : Type) (x : X)(l1 l2 : list X),\n snoc l1 x = snoc l2 x -> l1 = l2.\nProof.\n Admitted.\n\n\nLemma rev_lsplit : \n forall (X : Type) (l : list X) (x y : X),\n (x :: l ++ [y]) = rev (x :: l ++ [y]) -> x = y /\\ l = rev l.\nProof.\n intros X l.\n induction (all_lists_lsplittable X l).\n - intros. \n simpl in *.\n inversion H.\n split; reflexivity.\n - intros.\n simpl in *.\n inversion H.\n split; reflexivity.\n - intros.\n simpl in *.\n repeat (rewrite <- snoc_append in H).\n repeat (rewrite rev_snoc in H).\n inversion H.\n split.\n + reflexivity.\n + rewrite <- snoc_append.\n rewrite rev_snoc.\n simpl. f_equal. f_equal.\n apply (snoc_inj _ y).\n apply (snoc_inj _ y0).\n assumption.\nQed.\n\nTheorem palindrome_converse :\n forall (X : Type) (l : list X),\n l = rev l -> pal l.\nProof.\n intros.\n induction (all_lists_lsplittable X l).\n - apply pal_nil.\n - apply pal_single.\n - cut_rewrite (x = y).\n + apply pal_ht, IHl0.\n apply (rev_lsplit X l x y).\n assumption.\n + apply (rev_lsplit X l x y).\n assumption.\nQed.\n\n(** [] *)\n\n \n(** **** Exercise: 4 stars, advanced (subsequence) *)\n(** A list is a _subsequence_ of another list if all of the elements\n in the first list occur in the same order in the second list,\n possibly with some extra elements in between. For example,\n [1,2,3]\n is a subsequence of each of the lists\n [1,2,3]\n [1,1,1,2,2,3]\n [1,2,7,3]\n [5,6,1,9,9,2,7,3,8]\n but it is _not_ a subsequence of any of the lists\n [1,2]\n [1,3]\n [5,6,2,1,7,3,8]\n\n - Define an inductive proposition [subseq] on [list nat] that\n captures what it means to be a subsequence. (Hint: You'll need\n three cases.)\n\n - Prove that subsequence is reflexive, that is, any list is a\n subsequence of itself. \n\n - Prove that for any lists [l1], [l2], and [l3], if [l1] is a\n subsequence of [l2], then [l1] is also a subsequence of [l2 ++\n l3].\n\n - (Optional, harder) Prove that subsequence is transitive -- that\n is, if [l1] is a subsequence of [l2] and [l2] is a subsequence\n of [l3], then [l1] is a subsequence of [l3]. Hint: choose your\n induction carefully!\n*)\n\nInductive subseq {X : Type} : list X -> list X -> Prop :=\n | sub_nil : forall (l : list X), subseq [] l\n | sub_junk : forall (x : X) (s l : list X),\n subseq s l -> subseq s (x :: l)\n | sub_cons : forall (x : X) (s l : list X), \n subseq s l -> subseq (x :: s) (x :: l). \n\nTheorem subseq_refl : \n forall {X : Type} (l : list X), \n subseq l l.\nProof.\n intros. induction l.\n - apply sub_nil.\n - apply sub_cons. assumption.\nQed.\n\nTheorem subseq_app : \n forall {X : Type} (l1 l2 l3 : list X),\n subseq l1 l2 -> subseq l1 (l2 ++ l3).\nProof.\n intros. generalize dependent l3.\n induction H.\n - intros. apply sub_nil.\n - intros. \n simpl in *.\n apply sub_junk.\n apply IHsubseq.\n - intros.\n simpl in *.\n apply sub_cons.\n apply IHsubseq.\nQed.\n\nLemma subseq_of_nil : \n forall (X : Type) (l : list X),\n subseq l [] -> l = [].\nProof.\n intros. destruct l.\n - reflexivity.\n - inversion H.\nQed.\n\nLemma subseq_extra : \n forall (X : Type) (x : X) (s l : list X),\n subseq (x :: s) l -> subseq s l.\nProof.\n intros. induction l; inversion H; subst.\n - apply sub_junk, IHl. assumption.\n - apply sub_junk. assumption.\nQed.\n\nLemma subseq_length : \n forall (X : Type) (l1 l2 : list X),\n subseq l1 l2 -> length l1 <= length l2.\nProof.\n Admitted.\n\n(* A first approach using strong induction *)\n\nTheorem subseq_trans' : \n forall (X : Type) (n : nat) (l1 l2 l3 : list X),\n length l3 < n ->\n subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof.\n induction n.\n - intros. inversion H.\n - intros.\n induction H1.\n + intros.\n rewrite (subseq_of_nil X l1 H0).\n apply sub_nil.\n + intros.\n apply sub_junk, IHsubseq.\n * apply remove_head_length' with (x := x).\n apply Lt.lt_trans with (m := S n); auto.\n * assumption.\n + intros.\n destruct l1.\n * apply sub_nil.\n * {\n inversion H0; subst.\n - apply sub_junk, IHsubseq.\n + apply remove_head_length' with (x := x).\n apply Lt.lt_trans with (m := S n); auto.\n + assumption.\n - apply sub_cons.\n apply IHn with (l2 := s).\n + apply remove_head_length' with (x := x).\n assumption.\n + assumption.\n + assumption.\n }\nQed.\n \n(* A second, much simpler approach that simply rephrased the theorem\nstatement. It's crucial for our proof by induction that the\nuniversal quantifier be in the conclusion of our theorem, not in\nthe hypothesis *)\n\nTheorem subseq_trans : \n forall (X : Type) (l2 l3 : list X),\n subseq l2 l3 -> forall l1, subseq l1 l2 -> subseq l1 l3.\nProof.\n induction 1.\n - intros.\n rewrite (subseq_of_nil X l1 H).\n apply sub_nil.\n - intros.\n apply sub_junk, IHsubseq.\n assumption.\n - intros.\n destruct l1.\n + apply sub_nil.\n + inversion H0; subst.\n * apply sub_junk, IHsubseq. assumption.\n * apply sub_cons, IHsubseq. assumption.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (R_provability) *)\n(** Suppose we give Coq the following definition:\n Inductive R : nat -> list nat -> Prop :=\n | c1 : R 0 []\n | c2 : forall n l, R n l -> R (S n) (n :: l)\n | c3 : forall n l, R (S n) l -> R n l.\n Which of the following propositions are provable?\n\n - [R 2 [1,0]]\n - [R 1 [1,2,1,0]]\n - [R 6 [3,2,1,0]]\n*)\n\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** * Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n [beautiful]) can be thought of as a _property_ -- i.e., it defines\n a subset of [nat], namely those numbers for which the proposition\n is provable. In the same way, a two-argument proposition can be\n thought of as a _relation_ -- i.e., it defines a set of pairs for\n which the proposition is provable. *)\n\nModule LeModule. \n\n\n(** One useful example is the \"less than or equal to\"\n relation on numbers. *)\n\n(** The following definition should be fairly intuitive. It\n says that there are two ways to give evidence that one number is\n less than or equal to another: either observe that they are the\n same number, or give evidence that the first is less than or equal\n to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n | le_n : forall n, le n n\n | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n [le_S] follow the same patterns as proofs about properties, like\n [ev] in chapter [Prop]. We can [apply] the constructors to prove [<=]\n goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n tactics like [inversion] to extract information from [<=]\n hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition. (Notice that,\n although these are the same kind of simple \"unit tests\" as we gave\n for the testing functions we wrote in the first few lectures, we\n must construct their proofs explicitly -- [simpl] and\n [reflexivity] don't do the job, because the proofs aren't just a\n matter of simplifying computations.) *)\n\nTheorem test_le1 :\n 3 <= 3.\nProof.\n (* WORKED IN CLASS *)\n apply le_n. Qed.\n\nTheorem test_le2 :\n 3 <= 6.\nProof.\n (* WORKED IN CLASS *)\n apply le_S. apply le_S. apply le_S. apply le_n. Qed.\n\nTheorem test_le3 :\n (2 <= 1) -> 2 + 2 = 5.\nProof. \n (* WORKED IN CLASS *)\n intros H. inversion H. inversion H2. Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n | nn : next_nat n (S n).\n\nInductive next_even (n:nat) : nat -> Prop :=\n | ne_1 : ev (S n) -> next_even n (S n)\n | ne_2 : ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation) *)\n(** Define an inductive binary relation [total_relation] that holds\n between every pair of natural numbers. *)\n\nInductive total_relation : nat -> nat -> Prop := \n R_total : forall n m, total_relation n m.\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n that never holds. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\n(** Here are a number of facts about the [<=] and [<] relations that\n we are going to need later in the course. The proofs make good\n practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem O_le_n : forall n,\n 0 <= n.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n n <= m -> S n <= S m.\nProof. \n intros. induction m.\n - inversion H.\n apply le_n.\n - inversion H.\n + apply le_n.\n + apply le_S.\n apply IHm.\n apply H1.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n S n <= S m -> n <= m.\nProof. \n intros. induction m.\n - inversion H.\n + apply le_n.\n + inversion H1.\n - inversion H.\n + apply le_n.\n + apply le_S.\n apply IHm.\n assumption.\nQed.\n\n\nTheorem le_plus_l : forall a b,\n a <= a + b.\nProof. \n intros. induction a.\n - apply O_le_n.\n - apply n_le_m__Sn_le_Sm.\n apply IHa.\nQed.\n \nTheorem plus_lt : forall n1 n2 m,\n n1 + n2 < m ->\n n1 < m /\\ n2 < m.\nProof. \n unfold lt. \n (* FILL IN HERE *) Admitted.\n\nTheorem lt_S : forall n m,\n n < m ->\n n < S m.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true : forall n m,\n ble_nat n m = true -> n <= m.\nProof. \n (* FILL IN HERE *) Admitted.\n\nTheorem le_ble_nat : forall n m,\n n <= m ->\n ble_nat n m = true.\nProof.\n (* Hint: This may be easiest to prove by induction on [m]. *)\n (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true_trans : forall n m o,\n ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true. \nProof.\n (* Hint: This theorem can be easily proved without using [induction]. *)\n (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false) *)\nTheorem ble_nat_false : forall n m,\n ble_nat n m = false -> ~(n <= m).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 3 stars (R_provability2) *)\nModule R.\n(** We can define three-place relations, four-place relations,\n etc., in just the same way as binary relations. For example,\n consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n | c1 : R 0 0 0 \n | c2 : forall m n o, R m n o -> R (S m) n (S o)\n | c3 : forall m n o, R m n o -> R m (S n) (S o)\n | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n - [R 1 1 2]\n - [R 2 2 6]\n\n - If we dropped constructor [c5] from the definition of [R],\n would the set of provable propositions change? Briefly (1\n sentence) explain your answer.\n \n - If we dropped constructor [c4] from the definition of [R],\n would the set of provable propositions change? Briefly (1\n sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact) *) \n(** Relation [R] actually encodes a familiar function. State and prove two\n theorems that formally connects the relation and the function. \n That is, if [R m n o] is true, what can we say about [m],\n [n], and [o], and vice versa?\n*)\n\nTheorem R_plus :\n forall (m n o : nat),\n R m n o -> m + n = o.\nProof.\n intros.\n induction H.\n - reflexivity.\n - simpl. rewrite IHR. reflexivity.\n - rewrite plus_comm.\n simpl.\n rewrite plus_comm.\n rewrite IHR.\n reflexivity.\n - simpl in *.\n rewrite plus_comm in *.\n simpl in *.\n inversion IHR.\n reflexivity.\n - rewrite plus_comm.\n assumption.\nQed.\n\nTheorem plus_R : \n forall (m n o : nat),\n m + n = o -> R m n o.\nProof.\n intro m. induction m.\n - induction n.\n + intros. rewrite <- H. apply c1.\n + intros. destruct o.\n * inversion H.\n * apply c3.\n apply IHn.\n inversion H.\n reflexivity.\n - intros. destruct n; destruct o.\n + inversion H.\n + apply c2.\n apply IHm.\n rewrite plus_comm in *.\n inversion H.\n reflexivity.\n + inversion H.\n + destruct o.\n * inversion H.\n rewrite plus_comm in H1.\n inversion H1.\n * apply c3, c2, IHm.\n inversion H.\n rewrite plus_comm in H1.\n inversion H1.\n apply plus_comm.\nQed. \n\n(** [] *)\n\nEnd R.\n\n\n(* ##################################################### *)\n(** * Programming with Propositions Revisited *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n like \"two plus two equals four.\" In Coq, propositions are written\n as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n propositions. Simply _being_ a proposition is one thing; being\n _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 : \n 2 + 2 = 4.\nProof. reflexivity. Qed.\n\n(** But they can be used in many other ways. For example, we have also seen that\n we can give a name to a proposition using a [Definition], just as we have\n given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop := 2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true : \n plus_fact.\nProof. reflexivity. Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions. \n\n - We can define a new proposition primitively using [Inductive].\n\n - Given two expressions [e1] and [e2] of the same type, we can\n form the proposition [e1 = e2], which states that their\n values are equal.\n\n - We can combine propositions using implication and\n quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even. \n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n three equivalent ways: (1) \"[even] is a _function_ from numbers to\n propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n by a number [n],\" or (3) \"[even] is a _property_ of numbers.\" *)\n\n(** Propositions -- including parameterized propositions -- are\n first-class citizens in Coq. For example, we can define functions\n from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n as arguments to a function. \n\n The first function, [true_for_all_numbers], takes a proposition\n [P] as argument and builds the proposition that [P] is true for\n all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n that, if [P] is true for some natural number [n'], then it is also\n true by the successor of [n'] -- i.e. that [P] is _preserved by\n successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n forall (P:nat->Prop),\n true_for_zero P ->\n preserved_by_S P -> \n true_for_all_numbers P. \n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even) *)\n(** Complete the definition of the [combine_odd_even] function\n below. It takes as arguments two properties of numbers [Podd] and\n [Peven]. As its result, it should return a new property [P] such\n that [P n] is equivalent to [Podd n] when [n] is odd, and\n equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n fun n => match (oddb n) with\n | true => Podd n\n | false => Peven n\n end. \n\n(** To test your definition, see whether you can prove the following\n facts: *)\n\nTheorem combine_odd_even_intro : \n forall (Podd Peven : nat -> Prop) (n : nat),\n (oddb n = true -> Podd n) ->\n (oddb n = false -> Peven n) ->\n combine_odd_even Podd Peven n.\nProof.\n intros.\n destruct (oddb n) eqn:Hoddn; unfold combine_odd_even; rewrite Hoddn; auto.\nQed.\n\nTheorem combine_odd_even_elim_odd :\n forall (Podd Peven : nat -> Prop) (n : nat),\n combine_odd_even Podd Peven n ->\n oddb n = true ->\n Podd n.\nProof.\n intros.\n unfold combine_odd_even in *.\n rewrite H0 in *.\n assumption.\nQed.\n\nTheorem combine_odd_even_elim_even :\n forall (Podd Peven : nat -> Prop) (n : nat),\n combine_odd_even Podd Peven n ->\n oddb n = false ->\n Peven n.\nProof.\n intros.\n unfold combine_odd_even in *.\n rewrite H0 in *.\n assumption.\nQed.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n parameterized propositions using [Definition], then can we also\n define them using [Fixpoint]? Of course we can! However, this\n kind of \"recursive parameterization\" doesn't correspond to\n anything very familiar from everyday mathematics. The following\n exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)\n(** Define a recursive function\n [true_upto_n__true_everywhere] that makes\n [true_upto_n_example] work. *)\n\nFixpoint true_upto_n__true_everywhere (n : nat) (P : nat -> Prop) :=\n match n with\n | O => forall m : nat, P m\n | S n' => P n -> true_upto_n__true_everywhere n' P\n end.\n\nExample true_upto_n_example :\n (true_upto_n__true_everywhere 3 (fun n => even n))\n = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity. Qed.\n\n(** [] *)\n\n\n(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)\n\n\n", "meta": {"author": "dm0n3y", "repo": "sf", "sha": "bbc34446bf35bd9be29e545c617702c4411157f0", "save_path": "github-repos/coq/dm0n3y-sf", "path": "github-repos/coq/dm0n3y-sf/sf-bbc34446bf35bd9be29e545c617702c4411157f0/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535725, "lm_q2_score": 0.8976952989498449, "lm_q1q2_score": 0.8525137241164286}} {"text": "Require Import List Arith.\n\n(* General instructions: Follow the specifc instructions below, and replace\nevery occurrence of \"admitted\" with your own code or proof. *)\n\n(* Exercise 1 *)\n(* Define an inductive predicate to specify lists whose length is even. *)\nInductive len_ev {A : Type}: list A -> Prop :=\n | ev_nil : len_ev nil\n | ev_ss : forall {m n : A} {L : list A}, len_ev L -> len_ev (m::(n::L)).\n\n(* Name this predicate \"len_ev\" *)\n\n(* Use \"Arguments len_ev {A} _.\" to make the type argument implicit *)\n\nLemma len_ev_example :\n forall a : nat, len_ev (a::(2*a)::(3*a)::(4*a)::nil).\nProof.\n intros. apply ev_ss. apply ev_ss. apply ev_nil.\n Qed.\n\n(* Exercise 2 *)\n(* Define an inductive predicate named \"swapped\" to express that list1 \n is the same as list2 where two consecutive elements have been\n swapped.\n - the first constructor specifies that the first two elements of the\n list have been swapped and the rest is the same for the two lists.\n For instance (swapped (1::3::2::4::nil) (3::1::2::4::nil)) should be\n provable using this constructor.\n - the second constructor specifies that the two lists have the same first\n element, but their tails have a swap in them.\n For instance (swapped (1::3::2::4::nil) (1::2::3::4::nil)) should have\n a proof that starts by using this constructor.\n This predicate should have three arguments: a type A and two lists of\n type A. Make the type A an implicit argument using the command\n \"Arguments swapped {A} _ _.\" *)\nInductive swapped {A : Type} : list A -> list A -> Prop :=\n | swapped_base : forall {h1 h2 : list A} {t1 t2 : A}, (h1 = h2) -> swapped (t1::(t2::h1)) (t2::(t1::h2))\n | swapped_tail : forall {h1 : A} {h3 h4 : list A}, swapped h3 h4 -> swapped (h1::h3) (h1::h4).\n\nLemma swapped_ex : swapped (1::3::2::4::nil) (1::2::3::4::nil).\nProof.\n apply swapped_tail.\n apply swapped_base.\n reflexivity.\nQed.\n \n\n(* Exercise 3 *)\n(* Define an inductive relation named \"rearranged\" that is satisfied by list1 list2 if\n one of the following cases is satisfied:\n 1/ list1 and list2 are the same\n 2/ list1 is a swap of list3 and list3 is a rearranged list2.\n Again, this relation should be polymorphic, and you should add an\n implicit argument declaration. *)\nInductive rearranged {A : Type} : list A -> list A -> Prop :=\n | c1 : forall (list1 list2 : list A), (list1 = list2) -> rearranged list1 list2\n | c2 : forall (list1 list2 list3: list A), (swapped list1 list3) -> (rearranged list3 list2) -> rearranged list1 list2.\n\n(* Exercise 4 *)\nLemma rearranged_refl : forall (A : Type) (list1 : list A), rearranged list1 list1.\nProof.\n intros. apply c1. reflexivity.\nQed.\n\nLemma swapped_rearranged : forall (A : Type) (l1 l2 : list A), swapped l1 l2 -> rearranged l1 l2.\nProof.\n intros.\n apply c2 with (list3:=l2). apply H. apply c1. reflexivity.\nQed.\n\nLemma rearranged_transitive : forall (A : Type) (list1 list2 list3 : list A),\n rearranged list1 list2 -> rearranged list2 list3 -> rearranged list1 list3.\nProof.\n intros A l1 l2 l3 I1 I2.\n induction I1.\n - rewrite H. apply I2.\n - apply c2 with (list6:=list3).\n + apply H.\n + apply IHI1. apply I2.\nQed.\n\nLemma swapped_sym : forall A (list1 list2:list A), swapped list1 list2 -> swapped list2 list1.\nProof.\n intros.\n induction H.\n - rewrite H. apply swapped_base. reflexivity.\n - apply swapped_tail. apply IHswapped.\nQed.\n\nLemma rearranged_sym : forall (A : Type) (list1 list2 : list A), rearranged list1 list2 -> rearranged list2 list1.\nProof.\n intros.\n induction H.\n - rewrite H. apply c1. reflexivity.\n - apply swapped_sym in H. apply swapped_rearranged in H. \n apply rearranged_transitive with (list2:=list3).\n + apply IHrearranged.\n + apply H.\nQed.\n\nLemma rearranged_Tail : forall A (a:A) list1 list2, rearranged list1 list2 -> rearranged (a::list1) (a::list2).\nProof.\n intros. \n induction H.\n - rewrite H. apply c1. reflexivity.\n - apply c2 with (list6:=(a::list3)).\n + apply swapped_tail. apply H.\n + apply IHrearranged.\nQed.\n\nFixpoint insert x l :=\n match l with \n nil => x::nil\n | y::tl => if leb x y then x::l else y::insert x tl\n end.\n\nFixpoint sort l :=\n match l with\n nil => nil\n | x::tl => insert x (sort tl)\n end.\n\n(* Now prove that sorting a list returns an output that satisfies the rearranged relation on the input. *)\n\nLemma insert_rearranged : forall x l, rearranged (insert x l) (x::l).\nProof.\n intros.\n induction l.\n - unfold insert. apply c1. reflexivity.\n - simpl. destruct (x <=? a) eqn:eqn1.\n + apply c1. reflexivity.\n + apply rearranged_Tail with (a:=a) in IHl. apply rearranged_sym. apply c2 with (list3 := (a::x::l)). apply swapped_base. reflexivity. apply rearranged_sym. apply IHl.\nQed.\n\nLemma sort_rearranged : forall l, rearranged (sort l) l.\nProof.\n intros.\n induction l.\n - unfold sort. apply c1. reflexivity.\n - apply rearranged_Tail with (a:=a) in IHl. simpl. apply rearranged_sym in IHl. apply rearranged_transitive with (list2 := (a :: sort l)). apply insert_rearranged. apply rearranged_sym. apply IHl.\nQed.\n", "meta": {"author": "kartik894", "repo": "Intro-to-Math-Logic", "sha": "622ed387478980381f096afd2c56e7fe392fe739", "save_path": "github-repos/coq/kartik894-Intro-to-Math-Logic", "path": "github-repos/coq/kartik894-Intro-to-Math-Logic/Intro-to-Math-Logic-622ed387478980381f096afd2c56e7fe392fe739/MidtermS18.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.9263037313111812, "lm_q1q2_score": 0.8518683121826239}} {"text": "(** * Lists: Working with Structured Data *)\n\nFrom LF Require Export Induction.\nModule NatList.\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one (as with [nybble], and here): *)\n\nInductive natprod : Type :=\n| pair (n1 n2 : nat).\n\n(** This declaration can be read: \"The one and only way to\n construct a pair of numbers is by applying the constructor [pair]\n to two arguments of type [nat].\" *)\n\nCheck (pair 3 5) : natprod.\n\n(** Here are simple functions for extracting the first and\n second components of a pair. *)\n\nDefinition fst (p : natprod) : nat :=\n match p with\n | pair x y => x\n end.\n\nDefinition snd (p : natprod) : nat :=\n match p with\n | pair x y => y\n end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs will be used heavily in what follows, it is nice\n to be able to write them with the standard mathematical notation\n [(x,y)] instead of [pair x y]. We can tell Coq to allow this with\n a [Notation] declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in pattern\n matches. *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n match p with\n | (x,y) => x\n end.\n\nDefinition snd' (p : natprod) : nat :=\n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n match p with\n | (x,y) => (y,x)\n end.\n\n(** Note that pattern-matching on a pair (with parentheses: [(x, y)])\n is not to be confused with the \"multiple pattern\" syntax (with no\n parentheses: [x, y]) that we have seen previously. The above\n examples illustrate pattern matching on a pair with elements [x]\n and [y], whereas, for example, the definition of [minus] in\n [Basics] performs pattern matching on the values [n] and [m]:\n\n Fixpoint minus (n m : nat) : nat :=\n match n, m with\n | O , _ => O\n | S _ , O => n\n | S n', S m' => minus n' m'\n end.\n\n The distinction is minor, but it is worth knowing that they\n are not the same. For instance, the following definitions are\n ill-formed:\n\n (* Can't match on a pair with multiple patterns: *)\n Definition bad_fst (p : natprod) : nat :=\n match p with\n | x, y => x\n end.\n\n (* Can't match on multiple values with pair patterns: *)\n Definition bad_minus (n m : nat) : nat :=\n match n, m with\n | (O , _ ) => O\n | (S _ , O ) => n\n | (S n', S m') => bad_minus n' m'\n end.\n*)\n\n(** Now let's try to prove a few simple facts about pairs.\n\n If we state properties of pairs in a slightly peculiar way, we can\n sometimes complete their proofs with just reflexivity (and its\n built-in simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** Instead, we need to expose the structure of [p] so that\n [simpl] can perform the pattern match in [fst] and [snd]. We can\n do this with [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** Notice that, unlike its behavior with [nat]s, where it\n generates two subgoals, [destruct] generates just one subgoal\n here. That's because [natprod]s can only be constructed in one\n way. *)\n\n(** **** Exercise: 1 star, standard (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n destruct p. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n destruct p. simpl. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n type of _lists_ of numbers like this: \"A list is either the empty\n list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n | nil\n | cons (n : nat) (l : natlist).\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n declarations, but here is roughly what's going on in case you are\n interested. The \"[right associativity]\" annotation tells Coq how to\n parenthesize expressions involving multiple uses of [::] so that,\n for example, the next three declarations mean exactly the same\n thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The \"[at level 60]\" part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\n\n Notation \"x + y\" := (plus x y)\n (at level 50, left associativity).\n\n the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than\n [1 + (2 :: [3])].\n\n (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n you read them in a [.v] file. The inner brackets, around 3, indicate\n a list, but the outer brackets, which are invisible in the HTML\n rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n part should be displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** Next let's look at several functions for constructing and\n manipulating lists. First, the [repeat] function takes a number\n [n] and a [count] and returns a list of length [count] in which\n every element is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n match l with\n | nil => O\n | h :: t => S (length t)\n end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\n\n(** Since [app] will be used extensively, it is again convenient\n to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first element (the\n \"tail\"). Since the empty list has no first element, we pass\n a default value to be returned in that case. *)\n\nDefinition hd (default : nat) (l : natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l : natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, standard, especially useful (list_funs)\n\n Complete the definitions of [nonzeros], [oddmembers], and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n match l with\n | [] => []\n | (0 :: xs) => nonzeros xs\n | (n :: xs) => n :: nonzeros xs\n end.\n\n\nExample test_nonzeros:\n nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n match l with\n | [] => []\n | (n :: xs) => match oddb n with\n | true => n :: (oddmembers xs)\n | false => oddmembers xs\n end\n end.\n\n\nExample test_oddmembers:\n oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\nDefinition countoddmembers (l:natlist) : nat :=\n length (oddmembers l).\n\nExample test_countoddmembers1:\n countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers2:\n countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers3:\n countoddmembers nil = 0.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate)\n\n Complete the following definition of [alternate], which\n interleaves two lists into one, alternating between elements taken\n from the first list and elements from the second. See the tests\n below for more specific examples.\n\n (Note: one natural and elegant way of writing [alternate] will\n fail to satisfy Coq's requirement that all [Fixpoint] definitions\n be \"obviously terminating.\" If you find yourself in this rut,\n look for a slightly more verbose solution that considers elements\n of both lists at the same time. One possible solution involves\n defining a new kind of pairs, but this is not the only way.) *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l1 with\n | [] => l2\n | (x::xs) => match l2 with\n | [] => x::xs\n | (y::ys) => x :: y :: (alternate xs ys)\n end\n end.\n\nExample test_alternate1:\n alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. reflexivity. Qed.\n\nExample test_alternate2:\n alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\n\nExample test_alternate3:\n alternate [1;2;3] [4] = [1;4;2;3].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate4:\n alternate [] [20;30] = [20;30].\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n can appear multiple times rather than just once. One possible\n representation for a bag of numbers is as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, standard, especially useful (bag_functions)\n\n Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v : nat) (s : bag) : nat :=\n match s with\n | [] => 0\n | n::xs => match eqb n v with\n | true => S (count v xs)\n | false => count v xs\n end\n end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\n\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n the elements of [a] and of [b]. (Mathematicians usually define\n [union] on multisets a little bit differently -- using max instead\n of sum -- which is why we don't call this operation [union].) For\n [sum], we're giving you a header that does not give explicit names\n to the arguments. Moreover, it uses the keyword [Definition]\n instead of [Fixpoint], so even if you had names for the arguments,\n you wouldn't be able to process them recursively. The point of\n stating the question this way is to encourage you to think about\n whether [sum] can be implemented in another way -- perhaps by\n using one or more functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := app.\n\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v : nat) (s : bag) : bag := cons v s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nDefinition member (v : nat) (s : bag) : bool := ltb 0 (count v s).\n\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\n\n\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (bag_more_functions)\n\n Here are some more [bag] functions for you to practice with. *)\n\n(** When [remove_one] is applied to a bag without the number to\n remove, it should return the same bag unchanged. (This exercise\n is optional, but students following the advanced track will need\n to fill in the definition of [remove_one] for a later\n exercise.) *)\n\nFixpoint remove_one (v : nat) (s : bag) : bag :=\n match s with\n | [] => []\n | x::xs => match eqb v x with\n | true => xs\n | false => x :: (remove_one v xs)\n end\n end.\n\nExample test_remove_one1:\n count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\n\nExample test_remove_one2:\n count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one3:\n count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\nExample test_remove_one4:\n count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with\n | [] => []\n | x::xs => match eqb v x with\n | true => remove_all v xs\n | false => x :: (remove_all v xs)\n end\n end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. reflexivity. Qed.\n\n\nFixpoint subset (s1 : bag) (s2 : bag) : bool :=\n match s1 with\n | [] => true\n | (x::xs) => match member x s2 with\n | true => subset xs (remove_one x s2)\n | false => false\n end\n end.\n\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, especially useful (add_inc_count)\n\n Adding a value to a bag should increase the value's count by one.\n State that as a theorem and prove it. *)\n\nTheorem eqb_n : forall n, n =? n = true.\nProof.\n intros.\n induction n.\n - reflexivity.\n - simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem add_inc_count : forall b v n,\n n = count v b -> S n = count v (add v b).\nProof.\n intros.\n simpl. rewrite eqb_n.\n rewrite H. reflexivity.\nQed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_add_inc_count : option (nat*string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, just the simplification performed by [reflexivity] is\n enough for this theorem... *)\n\nTheorem nil_app : forall l : natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ...because the [[]] is substituted into the\n \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n the match) in the definition of [app], allowing the match itself\n to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons n l' *)\n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. We'll see how to do this next. *)\n\n(** (Micro-Sermon: As we get deeper into this material, simply\n _reading_ proof scripts will not get you very far! It is\n important to step through the details of each one using Coq and\n think about what each step achieves. Otherwise it is more or less\n guaranteed that the exercises will make no sense when you get to\n them. 'Nuff said.) *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n little less familiar than standard natural number induction, but\n the idea is equally simple. Each [Inductive] declaration defines\n a set of data values that can be built up using the declared\n constructors. For example, a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to another\n number; and a list can be either [nil] or [cons] applied to a\n number and a list. Moreover, applications of the declared\n constructors to one another are the _only_ possible shapes\n that elements of an inductively defined set can have.\n\n This last fact directly gives rise to a way of reasoning about\n inductively defined sets: a number is either [O] or else it is [S]\n applied to some _smaller_ number; a list is either [nil] or else\n it is [cons] applied to some number and some _smaller_ list;\n etc. So, if we have in mind some proposition [P] that mentions a\n list [l] and we want to argue that [P] holds for _all_ lists, we\n can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can always be broken down into smaller ones,\n eventually reaching [nil], these two arguments together establish\n the truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons n l1' *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n [as...] clause provided to the [induction] tactic gives a name to\n the induction hypothesis corresponding to the smaller list [l1']\n in the [cons] case.\n\n Once again, this Coq proof is not especially illuminating as a\n static document -- it is easy to see what's going on if you are\n reading the proof in an interactive Coq session and you can see\n the current goal and context at each point, but this state is not\n visible in the written-down parts of the Coq proof. So a\n natural-language proof -- one written for human readers -- will\n need to include more explicit signposts; in particular, it will\n help the reader stay oriented if we remind them exactly what the\n induction hypothesis is in the second case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n (the induction hypothesis). We must show\n\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n By the definition of [++], this follows from\n\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n which is immediate from the induction hypothesis. [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n lists, suppose we use [app] to define a list-reversing\n function [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n match l with\n | nil => nil\n | h :: t => rev t ++ [h]\n end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** For something a bit more challenging than the proofs\n we've seen so far, let's prove that reversing a list does not\n change its length. Our first attempt gets stuck in the successor\n case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n reflexivity.\n - (* l = n :: l' *)\n (* This is the tricky case. Let's begin as usual\n by simplifying. *)\n simpl.\n (* Now we seem to be stuck: the goal is an equality\n involving [++], but we don't have any useful equations\n in either the immediate context or in the global\n environment! We can make a little progress by using\n the IH to rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n would have enabled us to make progress at the point where we got\n stuck and state it as a separate lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1' IHl1'].\n - (* l1 = nil *)\n reflexivity.\n - (* l1 = cons *)\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Note that, to make the lemma as general as possible, we\n quantify over _all_ [natlist]s, not just those that result from an\n application of [rev]. This should seem natural, because the truth\n of the goal clearly doesn't depend on the list having been\n reversed. Moreover, it is easier to prove the more general\n property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l' IHl'].\n - (* l = nil *)\n reflexivity.\n - (* l = cons *)\n simpl. rewrite -> app_length.\n simpl. rewrite -> IHl'. rewrite plus_comm.\n reflexivity.\nQed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n _Theorem_: For all lists [l1] and [l2],\n [length (l1 ++ l2) = length l1 + length l2].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n\n length ([] ++ l2) = length [] + length l2,\n\n which follows directly from the definitions of\n [length], [++], and [plus].\n\n - Next, suppose [l1 = n::l1'], with\n\n length (l1' ++ l2) = length l1' + length l2.\n\n We must show\n\n length ((n::l1') ++ l2) = length (n::l1') + length l2.\n\n This follows directly from the definitions of [length] and [++]\n together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n\n length (rev []) = length [],\n\n which follows directly from the definitions of [length]\n and [rev].\n\n - Next, suppose [l = n::l'], with\n\n length (rev l') = length l'.\n\n We must show\n\n length (rev (n :: l')) = length (n :: l').\n\n By the definition of [rev], this follows from\n\n length ((rev l') ++ [n]) = S (length l')\n\n which, by the previous lemma, is the same as\n\n length (rev l') + length [n] = S (length l').\n\n This follows directly from the induction hypothesis and the\n definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n After reading a couple like this, we might find it easier to\n follow proofs that give fewer details (which we can easily work\n out in our own minds or on scratch paper if necessary) and just\n highlight the non-obvious steps. In this more compressed style,\n the above proof might look like this: *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n for any [l], by a straightforward induction on [l]. The main\n property again follows by induction on [l], using the observation\n together with the induction hypothesis in the case where [l =\n n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and how similar the\n proof at hand is to ones that they will already be familiar with.\n The more pedantic style is a good default for our present\n purposes. *)\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, e.g., using [rewrite]. But in order to refer to a\n theorem, we need to know its name! Indeed, it is often hard even\n to remember what theorems have been proven, much less what they\n are called.\n\n Coq's [Search] command is quite helpful with this. Let's say\n you've forgotten the name of a theorem about [rev]. The command\n [Search rev] will cause Coq to display a list of all theorems\n involving [rev]. *)\n\nSearch rev.\n\n(** Or say you've forgotten the name of the theorem showing that plus\n is commutative. You can use a pattern to search for all theorems\n involving the equality of two additions. *)\n\nSearch (_ + _ = _ + _).\n\n(** You'll see a lot of results there, nearly all of them from the\n standard library. To restrict the results, you can search inside\n a particular module: *)\n\nSearch (_ + _ = _ + _) inside Induction.\n\n(** You can also make the search more precise by using variables in\n the search pattern instead of wildcards: *)\n\nSearch (?x + ?y = ?y + ?x).\n\n(** The question mark in front of the variable is needed to indicate\n that it is a variable in the search pattern, rather than a\n variable that is expected to be in scope currently. *)\n\n(** Keep [Search] in mind as you do the following exercises and\n throughout the rest of the book; it can save you a lot of time!\n\n Your IDE likely has its own functionality to help with searching.\n For example, in ProofGeneral, you can run [Search] with [C-c C-a\n C-a], and paste its response into your buffer with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars, standard (list_exercises)\n\n More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n l ++ [] = l.\nProof.\n intros.\n induction l.\n - reflexivity.\n - simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n intros.\n induction l1.\n - simpl. rewrite app_nil_r. reflexivity.\n - simpl. rewrite IHl1. rewrite app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros.\n induction l.\n - reflexivity.\n - simpl. rewrite rev_app_distr. simpl. rewrite IHl. reflexivity.\nQed.\n\n(** There is a short solution to the next one. If you find yourself\n getting tangled up, step back and try to look for a simpler\n way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros.\n induction l1.\n - simpl. rewrite app_assoc. reflexivity.\n - simpl. rewrite IHl1. reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros.\n induction l1.\n - simpl. reflexivity.\n - simpl. induction n.\n + rewrite IHl1. reflexivity.\n + simpl. rewrite IHl1. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (eqblist)\n\n Fill in the definition of [eqblist], which compares\n lists of numbers for equality. Prove that [eqblist l l]\n yields [true] for every list [l]. *)\n\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n match l1, l2 with\n | [], [] => true\n | (x::xs), (y::ys) => match eqb x y with\n | true => eqblist xs ys\n | false => false\n end\n | _, _ => false\n end.\n\n\nExample test_eqblist1 :\n (eqblist nil nil = true).\nProof. reflexivity. Qed.\n\nExample test_eqblist2 :\n eqblist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\nExample test_eqblist3 :\n eqblist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\n\nTheorem eqblist_refl : forall l:natlist,\n true = eqblist l l.\nProof.\n intros.\n induction l.\n - reflexivity.\n - simpl. rewrite eqb_n. rewrite <- IHl. reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** Here are a couple of little theorems to prove about your\n definitions about bags above. *)\n\n(** **** Exercise: 1 star, standard (count_member_nonzero) *)\nTheorem count_member_nonzero : forall (s : bag),\n 1 <=? (count 1 (1 :: s)) = true.\nProof. intros. simpl. reflexivity. Qed.\n\n(** [] *)\n\n(** The following lemma about [leb] might help you in the next exercise. *)\n\nTheorem leb_n_Sn : forall n,\n n <=? (S n) = true.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* 0 *)\n simpl. reflexivity.\n - (* S n' *)\n simpl. rewrite IHn'. reflexivity. Qed.\n\n(** Before doing the next exercise, make sure you've filled in the\n definition of [remove_one] above. *)\n(** **** Exercise: 3 stars, advanced (remove_does_not_increase_count) *)\nTheorem remove_does_not_increase_count: forall (s : bag),\n (count 0 (remove_one 0 s)) <=? (count 0 s) = true.\nProof.\n intros.\n induction s.\n - reflexivity.\n - induction n.\n + simpl. rewrite leb_n_Sn. reflexivity.\n + simpl. rewrite IHs. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (bag_count_sum)\n\n Write down an interesting theorem [bag_count_sum] about bags\n involving the functions [count] and [sum], and prove it using\n Coq. (You may find that the difficulty of the proof depends on\n how you defined [count]!) *)\n\nTheorem bag_count_sum: forall n b1 b2,\n count n b1 + count n b2 = count n (sum b1 b2).\nProof.\n intros.\n induction b1.\n - simpl. reflexivity.\n - simpl. destruct (n0 =? n).\n + simpl. rewrite IHb1. reflexivity.\n + rewrite IHb1. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective)\n\n Prove that the [rev] function is injective. There is a hard way\n and an easy way to do this. *)\n\nTheorem rev_injective : forall (l1 l2 : natlist),\n rev l1 = rev l2 -> l1 = l2.\nProof.\n intros.\n assert (Hx: rev (rev l1) = rev (rev l2)).\n rewrite H. reflexivity.\n rewrite rev_involutive in Hx; rewrite rev_involutive in Hx.\n rewrite Hx.\n reflexivity.\nQed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n element of some list. If we give it type [nat -> natlist -> nat],\n then we'll have to choose some number to return when the list is\n too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n match l with\n | nil => 42\n | a :: l' => match n with\n | 0 => a\n | S n' => nth_bad l' n'\n end\n end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n can't tell whether that value actually appears on the input\n without further processing. A better alternative is to change the\n return type of [nth_bad] to include an error value as a possible\n outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n | Some (n : nat)\n | None.\n\n(** We can then change the above definition of [nth_bad] to\n return [None] when the list is too short and [Some a] when the\n list has enough members and [a] appears at position [n]. We call\n this new function [nth_error] to indicate that it may result in an\n error. As we see here, constructors of inductive definitions can\n be capitalized. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => match n with\n | O => Some a\n | S n' => nth_error l' n'\n end\n end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n examples are elided. Click on a box if you want to see one.)\n\n This example is also an opportunity to introduce one more small\n feature of Coq's programming language: conditional\n expressions... *)\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n match l with\n | nil => None\n | a :: l' => if n =? O then Some a\n else nth_error' l' (pred n)\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the [bool] type\n is not built in, Coq actually supports conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\n\n(** **** Exercise: 2 stars, standard (hd_error)\n\n Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_error (l : natlist) : natoption :=\n match l with\n | [] => None\n | x::_ => Some x\n end.\n\n\nExample test_hd_error1 : hd_error [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (option_elim_hd)\n\n This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_error l).\nProof.\n intros.\n destruct l; reflexivity.\nQed.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n Coq, here is a simple _partial map_ data type, analogous to the\n map or dictionary data structures found in most programming\n languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n | Id (n : nat).\n\n(** Internally, an [id] is just a number. Introducing a separate type\n by wrapping each nat with the tag [Id] makes definitions more\n readable and gives us more flexibility. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition eqb_id (x1 x2 : id) :=\n match x1, x2 with\n | Id n1, Id n2 => n1 =? n2\n end.\n\n(** **** Exercise: 1 star, standard (eqb_id_refl) *)\nTheorem eqb_id_refl : forall x, true = eqb_id x x.\nProof.\n intros. destruct x. induction n.\n - reflexivity.\n - simpl. rewrite <- eqb_refl. reflexivity.\nQed.\n\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n\nInductive partial_map : Type :=\n | empty\n | record (i : id) (v : nat) (m : partial_map).\n\n(** This declaration can be read: \"There are two ways to construct a\n [partial_map]: either using the constructor [empty] to represent an\n empty partial map, or applying the constructor [record] to\n a key, a value, and an existing [partial_map] to construct a\n [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n partial map by shadowing it with a new one (or simply adds a new\n entry if the given key is not already present). *)\n\nDefinition update (d : partial_map)\n (x : id) (value : nat)\n : partial_map :=\n record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n key. It returns [None] if the key was not found and [Some val] if\n the key was associated with [val]. If the same key is mapped to\n multiple values, [find] will return the first one it\n encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n match d with\n | empty => None\n | record y v d' => if eqb_id x y\n then Some v\n else find x d'\n end.\n\n(** **** Exercise: 1 star, standard (update_eq) *)\nTheorem update_eq :\n forall (d : partial_map) (x : id) (v: nat),\n find x (update d x v) = Some v.\nProof.\n intros. simpl. rewrite <- eqb_id_refl. reflexivity.\nQed.\n\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard (update_neq) *)\nTheorem update_neq :\n forall (d : partial_map) (x y : id) (o: nat),\n eqb_id x y = false -> find x (update d y o) = find x d.\nProof.\n intros.\n simpl.\n rewrite H. reflexivity.\nQed.\n\n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 stars, standard, optional (baz_num_elts)\n\n Consider the following inductive definition: *)\n\nInductive baz : Type :=\n | Baz1 (x : baz)\n | Baz2 (y : baz) (b : bool).\n\n(** How _many_ elements does the type [baz] have? (Explain in words,\n in a comment.) *)\n\n(* There is no base constructor, so there is no\n possible, \"finite\" element. However, there can be elements that are infinite.\n\n The \"baz\" type can be thought of a infinite list of either:\n\n - a bottom value\n - either true or false\n\n Overall, there are 3*infinity = infinity of possible elements.\n *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_baz_num_elts : option (nat*string) := None.\n(** [] *)\n\n(* 2020-09-09 20:51 *)\n", "meta": {"author": "shouya", "repo": "thinking-dumps", "sha": "bfe50272459ddfca95de74a1857e2e649218584e", "save_path": "github-repos/coq/shouya-thinking-dumps", "path": "github-repos/coq/shouya-thinking-dumps/thinking-dumps-bfe50272459ddfca95de74a1857e2e649218584e/software-foundations-2/lf/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.9273632986579697, "lm_q1q2_score": 0.8517648709208057}} {"text": "Module NatPlayground.\n\n(** S is the successor constructor*)\n\nInductive nat :Type :=\n| O \n| S (n:nat).\n\nDefinition pred(n: nat) : nat :=\nmatch n with\n| O => O\n| S n' => n'\nend.\n\nEnd NatPlayground.\n\nCheck (S (S (S (S O)))).\n\nDefinition minustwo (n:nat) : nat :=\n match n with \n | O => O\n | S O => O\n | S (S n') => n'\n end.\n\nCompute (minustwo 4).\n\n(** For recursive functions, we use Fixpoint instead of Definition. This recursively matched the conditions*)\n\nFixpoint even (n: nat ) : bool :=\n match n with \n | O => true\n | S O => false\n | S (S n') => even n'\n end.\n\nDefinition odd (n: nat) : bool :=\n negb (even n).\n\nExample test_odd1: odd 1 = true.\nProof. simpl. reflexivity. Qed.\nExample test_odd2: odd 4 = false.\nProof. simpl. reflexivity. Qed.", "meta": {"author": "ayushpandey8439", "repo": "CoqProofs", "sha": "a5e7c8ed86eed738a1b70a6a047a5408fdaa6c7b", "save_path": "github-repos/coq/ayushpandey8439-CoqProofs", "path": "github-repos/coq/ayushpandey8439-CoqProofs/CoqProofs-a5e7c8ed86eed738a1b70a6a047a5408fdaa6c7b/Numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620573763839, "lm_q2_score": 0.8872045974451017, "lm_q1q2_score": 0.8515053097576972}} {"text": "Add LoadPath \"$COQ_PROOFS\" as Path.\nLoad Basics. \n\nTheorem plus_n_O: forall n: nat, n = n + 0.\nProof.\n intros n.\n induction n as [| n' IHn'].\n - reflexivity.\n - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n intros n.\n induction n.\n - reflexivity.\n - simpl. rewrite -> IHn. reflexivity.\nQed.\n\nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof.\n intros.\n induction n.\n - reflexivity.\n - simpl. rewrite -> IHn. reflexivity.\nQed.\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros.\n induction n.\n {\n induction m. {\n reflexivity. \n } {\n simpl. rewrite <- IHm. reflexivity. \n }\n }\n {\n simpl. rewrite -> IHn. rewrite -> plus_n_Sm. reflexivity.\n }\nQed.\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros. \n induction n.\n - simpl. reflexivity.\n - simpl. rewrite <- IHn. reflexivity.\nQed.\n\nLemma minus_Sn_n : forall n, S n - n = 1.\nProof.\n intros.\n induction n.\n - reflexivity.\n - simpl in IHn. simpl. rewrite -> IHn. reflexivity.\nQed.\n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\nLemma double_plus : forall n, double n = n + n.\nProof.\n intros.\n induction n.\n - reflexivity.\n - simpl. rewrite -> IHn. rewrite <- plus_n_Sm. reflexivity.\nQed.\n\nLemma double_plus' : forall n, double n = n + n.\nProof.\n (* Auxiliary proof *)\n assert (H1: forall m k, S(m + k) = m + (S k)).\n { intros. induction m.\n - simpl. reflexivity.\n - simpl. rewrite -> IHm. reflexivity. \n }\n intros.\n induction n.\n - reflexivity.\n - simpl. rewrite -> IHn. simpl in H1. rewrite <- H1. reflexivity.\nQed.\n\nTheorem evenb_S : forall n : nat,\n evenb (S n) = negb (evenb n).\nProof.\n intros.\n induction n.\n - simpl. reflexivity.\n - rewrite -> IHn. simpl. rewrite -> negb_involutive. reflexivity.\nQed.\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n). { reflexivity. }\n rewrite -> H.\n reflexivity. \nQed.\n\nTheorem plus_rearrange : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros.\n assert (H: n + m = m + n). {\n intros.\n induction n.\n {\n induction m. {\n reflexivity. \n } {\n simpl. rewrite <- IHm. reflexivity. \n }\n }\n {\n simpl. rewrite -> IHn. rewrite -> plus_n_Sm. reflexivity.\n }\n }\n rewrite -> H. reflexivity. Qed.\n\nInductive bin : Type :=\n | BZ : bin (* binary zero *)\n | T2 : bin -> bin (* twice a binary number *)\n | T2P1 : bin -> bin. (* twice a binary number plus 1 *)\n\nFixpoint incr (m:bin) : bin :=\n match m with\n | BZ => T2P1 BZ\n | T2 m' => T2P1 m'\n | T2P1 m' => T2 (incr m')\n end.\n\nFixpoint bin_to_nat (m:bin) : nat :=\n match m with\n | BZ => O\n | T2 m' => 2 * bin_to_nat m'\n | T2P1 m' => 1 + 2 * bin_to_nat m'\n end.\n\nCompute bin_to_nat (T2 (T2 (T2P1 BZ))).\n\nTheorem bin_commute: forall b: bin, bin_to_nat (incr b) = S (bin_to_nat b).\nProof.\n assert(forall n: nat, n + 0 = n). {\n intros.\n induction n.\n - reflexivity.\n - simpl. rewrite -> IHn. reflexivity.\n }\n\n assert(forall b: bin, bin_to_nat b + 0 = bin_to_nat b). {\n intros.\n induction b.\n - reflexivity.\n - rewrite -> H. reflexivity.\n - rewrite -> H. reflexivity. \n }\n\n assert(forall n m: nat, S(n) + S(m) = S(S(n+m))). {\n intros.\n induction n.\n - simpl. reflexivity.\n - simpl. rewrite <- IHn. simpl. reflexivity.\n }\n \n intros.\n induction b.\n - simpl. reflexivity.\n - simpl. reflexivity.\n - simpl. rewrite -> H. rewrite -> H. rewrite -> IHb. rewrite <- H1. reflexivity. \nQed.\n\n\n\n \n", "meta": {"author": "kino6052", "repo": "coq-course", "sha": "57de05e6eca44d8617794be1d8b41803af0a7cda", "save_path": "github-repos/coq/kino6052-coq-course", "path": "github-repos/coq/kino6052-coq-course/coq-course-57de05e6eca44d8617794be1d8b41803af0a7cda/unit_2_001_induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145364, "lm_q2_score": 0.9032942119105696, "lm_q1q2_score": 0.8513608674051703}} {"text": "Theorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof.\n intros n m. induction n as [| n' IHn'].\n - simpl. reflexivity.\n - simpl. induction m as [| m' IHm'].\n -- rewrite IHn'. reflexivity.\n -- rewrite IHn'. reflexivity.\nQed.\n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\n(** Use induction to prove this simple fact about [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n intros n. induction n.\n - simpl. reflexivity.\n - simpl. rewrite <- plus_n_Sm. rewrite IHn. reflexivity.\nQed.\n", "meta": {"author": "cristianlepore", "repo": "Coq_exercises", "sha": "109d34794edee6bd2b255ed4f7fc3c91edb8c8f5", "save_path": "github-repos/coq/cristianlepore-Coq_exercises", "path": "github-repos/coq/cristianlepore-Coq_exercises/Coq_exercises-109d34794edee6bd2b255ed4f7fc3c91edb8c8f5/Software_foundation/Chapter2/double.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8962513668985, "lm_q1q2_score": 0.8511424660827692}} {"text": "From LF Require Export Basics.\n\nTheorem plus_n_0_firsttry : forall n:nat,\n n = n + 0.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0*)\n reflexivity.\n - (* n = S n' *)\n simpl. rewrite <- IHn'. reflexivity.\nQed.\n\n(*Exercise*)\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n intros n. induction n as [| n' IHn'].\n - (* n = 0 *)\n reflexivity.\n - (* n * 0 = 0 -> S n * 0 = 0 *)\n simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof.\n intros n m. induction n as [| n' IHn'].\n - reflexivity.\n - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\n(* 加法交换律 *)\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros n m. induction m as [| m' IHm'].\n - rewrite <- (plus_n_0_firsttry n). reflexivity.\n - simpl. rewrite <- IHm'. rewrite -> (plus_n_Sm n m'). reflexivity.\nQed.\n\n\n(*加法结合律*)\nTheorem plus_assoc : forall n m p : nat,\n (n + m) + p = n + (m + p).\nProof.\n intros n m p. induction n as [| n IHn'].\n - reflexivity.\n - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nFixpoint double (n: nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\nLemma double_plus : forall n: nat,\n double n = n + n.\nProof.\n intros n. induction n as [| n' IHn'].\n - reflexivity.\n - simpl. rewrite <- plus_comm. simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem evenb_S : forall n : nat,\n evenb (S n) = negb (evenb n).\nProof.\n intros n. induction n as [| n' IHn'].\n - reflexivity.\n - rewrite -> IHn'. simpl. rewrite -> (negb_involutive (evenb n')).\n reflexivity.\nQed.\n\n(*proofs within proofs*)\n\nTheorem mult_0_plus' : forall n m: nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n). { reflexivity. }\n rewrite -> H.\n reflexivity.\nQed.\n\nTheorem plus_rearrange_firsttry : forall n m p q: nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n rewrite -> (plus_comm n m).\n reflexivity.\nQed.\n\n\n(*更多练习*)\n\nTheorem plus_swap : forall n m p: nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n rewrite -> (plus_comm n p).\n rewrite -> (plus_comm n (m + p)).\n rewrite <- (plus_assoc m p n).\n reflexivity.\nQed.\n\n(*乘法交换律*)\n\nLemma mult_0_eq_0 : forall n: nat,\n 0 = n * 0.\nProof.\n intros n. induction n as [| n' IHn'].\n - simpl. reflexivity.\n - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nLemma mult_plus_1 : forall n m : nat,\n m * n + m = m * S n.\nProof.\n intros n m. induction m as [| m' IHm'].\n - simpl. reflexivity.\n - simpl. rewrite <- IHm'.\n rewrite <- (plus_assoc n (m' * n) m').\n rewrite <- (plus_n_Sm (n + m' * n) m').\n reflexivity.\nQed.\n\nTheorem mult_comm : forall n m: nat,\n n * m = m * n.\nProof.\n intros n m. induction n as [| n' IHn'].\n - simpl. rewrite <- (mult_0_eq_0 m). reflexivity.\n - simpl. rewrite -> IHn'.\n rewrite -> (plus_comm m (m * n')).\n rewrite <- (mult_plus_1 n' m). reflexivity.\nQed.\n\n\n(*练习*)\n\nTheorem leb_refl : forall n: nat,\n true = (n <=? n).\nProof.\n intros n. induction n as [| n' IHn'].\n - simpl. reflexivity.\n - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\n\nTheorem zero_nbeq_S : forall n : nat,\n 0 =? (S n) = false.\nProof.\n intros n. destruct n as [| n'].\n - simpl. reflexivity.\n - simpl. reflexivity.\nQed.\n\nTheorem andb_false_r : forall b: bool,\n andb b false = false.\nProof.\n intros b. destruct b.\n - simpl. reflexivity.\n - simpl. reflexivity.\nQed.\n\n\nTheorem plus_ble_compat_l : forall n m p: nat,\n n <=? m = true -> (p + n) <=? (p + m) = true.\nProof.\n intros n m p. intros H. induction p as [| p' IHp'].\n - simpl. rewrite -> H. reflexivity.\n - simpl. rewrite -> IHp'. reflexivity.\nQed.\n\n\n(*乘法结合律*)\n\nTheorem mult_plus_distr_r : forall n m p: nat,\n (n + m) * p = (n * p) + (m * p).\nProof.\n intros n m p. induction p as [| p' IHp'].\n - simpl. rewrite -> (mult_0_r n). rewrite -> (mult_0_r m). rewrite -> (mult_0_r (n + m)). reflexivity.\n - rewrite <- (mult_plus_1 p' (n + m)).\n rewrite <- (mult_plus_1 p' n).\n rewrite <- (mult_plus_1 p' m).\n rewrite -> IHp'.\n rewrite -> (plus_assoc (n * p') (m * p') (n + m)).\n rewrite -> (plus_assoc (n * p') n (m * p' + m)).\n rewrite -> (plus_comm (n * p') (m * p' + (n + m))).\n rewrite -> (plus_comm (n * p') (n + (m * p' + m))).\n rewrite -> (plus_swap n (m * p') m).\n reflexivity.\nQed.\n\nTheorem mult_assoc : forall n m p : nat,\n n * (m * p) = (n * m) * p.\nProof.\n intros n m p. induction n as [| n' IHn'].\n - simpl. reflexivity.\n - simpl. rewrite -> IHn'.\n rewrite -> (mult_plus_distr_r m (n' * m) p).\n reflexivity.\nQed.\n\nTheorem eqb_refl : forall n: nat,\n true = (n <=? n).\nProof.\n intros n. induction n.\n - simpl. reflexivity.\n - simpl. rewrite <- IHn. reflexivity.\nQed.\n\n\nTheorem plus_swap' : forall n m p: nat,\n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\nAdmitted.\n\n\n(**)\nInductive bin : Type :=\n| Z\n| Bin0 : bin -> bin (* B_0 n = 2*n *)\n| Bin1 : bin -> bin. (* B_1 = 2*n + 1 *)\n\nFixpoint incr (m: bin) : bin :=\n match m with\n | Z => Bin1 Z\n | Bin0 m' => Bin1 m'\n | Bin1 m' => Bin0 (incr m')\n end.\n\n(* bin 转化为 nat *)\n\nFixpoint bin_to_nat (m: bin) : nat :=\n match m with\n | Z => O\n | Bin0 m' => 2 * (bin_to_nat m')\n | Bin1 m' => 2 * (bin_to_nat m') + 1\n end.\n\nLemma plus_1_eq_S : forall n : nat,\n n + 1 = S n.\nProof.\n intros n. induction n.\n - simpl. reflexivity.\n - simpl. rewrite <- IHn. reflexivity.\nQed.\n\nLemma plus_0_equal : forall n: nat,\n n + 0 = n.\nProof.\n intros. induction n.\n - reflexivity.\n - simpl. rewrite -> IHn. reflexivity.\nQed.\n\nTheorem bin_to_nat_pres_inrc : forall b : bin,\n S (bin_to_nat b) = bin_to_nat (incr b).\nProof.\n intros b. induction b.\n - simpl. reflexivity.\n - simpl. rewrite <- plus_1_eq_S. reflexivity.\n - simpl. rewrite <- IHb. rewrite -> plus_0_equal.\n rewrite -> (plus_0_equal (S (bin_to_nat b))).\n rewrite <- plus_1_eq_S.\n rewrite <- (plus_1_eq_S (bin_to_nat b)).\n rewrite -> (plus_assoc (bin_to_nat b) 1 (bin_to_nat b + 1)).\n rewrite -> (plus_swap 1 (bin_to_nat b) 1).\n rewrite <- (plus_assoc (bin_to_nat b) (bin_to_nat b) (1 + 1)).\n rewrite -> plus_assoc. reflexivity.\nQed.\n\n\nFixpoint nat_to_bin (n: nat) : bin :=\n match n with\n | O => Z\n | S n' => incr (nat_to_bin n')\n end.\n\nTheorem nat_bin_nat : forall n: nat,\n bin_to_nat (nat_to_bin n) = n.\nProof.\n intros n. induction n.\n - reflexivity.\n - simpl. rewrite <- (bin_to_nat_pres_inrc (nat_to_bin n)).\n rewrite -> IHn. reflexivity.\nQed.\n\n(* 不明白 normalize 函数的意思 *)\n\n", "meta": {"author": "unformalized", "repo": "software-foundations", "sha": "3e55bcf4b1f2413c49c52fe9e41c1885093d9dfd", "save_path": "github-repos/coq/unformalized-software-foundations", "path": "github-repos/coq/unformalized-software-foundations/software-foundations-3e55bcf4b1f2413c49c52fe9e41c1885093d9dfd/Logical_Foundations/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188345, "lm_q2_score": 0.9046505370289057, "lm_q1q2_score": 0.8510859534000141}} {"text": "(* Example of proof by simplification *)\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof. intros n. simpl. reflexivity. Qed.\n\n(* \nIn Coq, we use tactics to manipulate the goal and context, where Coq \nwill keep track of the goal and context for us \n\nTactics (used in the previous proof) :\n \"intros\" - introduces things into our context\n whatever been quantified\n \"simpl\" - simplifies our goal running a few steps of computation\n \"reflexivity\" - named after the property of equality (all things are equal to themselves\n \"Qed\" - quod erat demonstrandum, latin for 'that which was to be proved'\n\n*)\n\n(* Example of proof by rewriting *)\nTheorem plus_id_example : forall (n m: nat), \n n = m -> n + n = m + m.\n\n(* The way a proof with implies ('->') works is: you have to prove what's to the right of \nthe arrow... but you may assume what's to the left. *)\n\nProof. \n (* move both quantifiers into the context *)\n intros n m .\n (* move the hypothesis into the context *)\n intros H.\n (* rewrite the goal usign the hypothesis *)\n rewrite -> H.\n reflexivity. Qed.\n\n(* (The arrow symbol in the rewrite has nothing to do with implication:\n it tells Coq to apply the rewrite from left to right. To rewrite from \nright to left, you can use rewrite <-. *)\n\n(* Exercise *)\nTheorem plus_id_exercise : forall n m o : nat, \n n = m -> m = o -> n + m = m + o.\n\nProof. intros n m o. intros H. rewrite <- H.\nintros G. rewrite -> G. reflexivity. Qed.\n\nTheorem mult_S_1 : forall n m : nat, \n m = S n-> \n m * (1 + n) = m * m.\n\nProof. intros n m. intros H. rewrite -> H.\nsimpl. reflexivity. Qed.\n\n\n(* Example of proof by case analysis *)\n\nFixpoint beq_nat (n m : nat) : bool :=\n match n with\n | O => match m with\n | O => true\n | S m' => false\n end\n | S n' => match m with\n | O => false\n | S m' => beq_nat n' m'\n end\n end.\n\nTheorem plus_1_neq_firsttry : forall n : nat,\n beq_nat (n + 1) 0 = false.\n\nProof. intros n. simpl. Abort.\n\n(* More tactics\n \"Abort\" - ends the proof but doesn't prove it\n \"destruct\" - tells Coq to consider seperate cases on a\n a variable in the context\n\n*)\n\nTheorem plus_1_neq_0 : forall n : nat,\n beq_nat (n + 1) 0 = false.\n \nProof. \n intros n. destruct n as [| n'].\n - reflexivity.\n - reflexivity. Qed.\n\n(* The annotation \"as [| n']\" is called an intro pattern. \nIt tells Coq what variable names to introduce in each subgoal\n\nThe - signs on the second and third lines are called bullets, \nand they mark the parts of the proof that correspond to each generated subgoal.\n\nThe destruct tactic can be used with any inductively defined datatype.\n *)\n\nTheorem negb_involutive : forall b : bool,\n negb (negb b) = b.\n\nProof. intros b. destruct b.\n - reflexivity.\n - reflexivity. Qed.\n\n(* Note that the destruct here has no as clause because none of the subcases \nof the destruct need to bind any variables, so there is no need to specify\nany names. (We could also have written as [|], or as [].)\n*)\n\nTheorem andb_commutative : forall b c, andb b c = andb c b.\n\nProof. intros b c. destruct b.\n - destruct c.\n + reflexivity.\n + reflexivity.\n - destruct c.\n + reflexivity.\n + reflexivity.\n Qed.\n\nTheorem and3b_commutative : forall b c d, andb (andb b c) d = andb (andb b d ) c.\n\nProof.\n intros b c d. destruct b.\n - destruct c.\n { destruct d.\n - reflexivity.\n - reflexivity. }\n { destruct d.\n - reflexivity.\n - reflexivity. }\n - destruct c.\n { destruct d.\n - reflexivity.\n - reflexivity. }\n { destruct d.\n - reflexivity.\n - reflexivity. }\nQed.\n\n(* You can perform the destructing in the same\n command as the intros. *)\n\nTheorem plus_1_neg_0' : forall n : nat, \n beq_nat (n + 1) 0 = false.\n \nProof.\n intros [|n].\n - reflexivity.\n - reflexivity. \nQed.\n\n(* Exercise 1 *)\n\nLemma minus_n_O : forall n : nat, n = n - 0.\n\nProof. intros n. destruct n as [a|b].\n - reflexivity.\n - reflexivity.\n Qed.\n\nTheorem andb_commutative'' :\n forall b c : bool, andb b c = andb c b.\n\n(* If there are no arguments to name, we can just write [] *)\nProof. intros [] [].\n - reflexivity.\n - reflexivity.\n - reflexivity.\n - reflexivity.\nQed.\n\n(* Exercise 2 need to come back and finish this one*)\n\nTheorem andb_true_elim2 : forall b c : bool, \n andb b c = true -> c = true.\n\nProof. intros b c. destruct c as [c'|c']. Abort.\n\n(* Exercise 3 *)\nTheorem zero_nbeq_plus_1 : forall n : nat, \n beq_nat 0 (n + 1) = false.\n \nProof. intros []. \n - reflexivity.\n - reflexivity.\nQed.\n\n(* I should come back to this section to understand \n how i can translate coq proofs into paper proofs *)\n \n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "dschneck", "repo": "coq-code", "sha": "3f8455c41488d95b7295b03b078d8499c6dc0034", "save_path": "github-repos/coq/dschneck-coq-code", "path": "github-repos/coq/dschneck-coq-code/coq-code-3f8455c41488d95b7295b03b078d8499c6dc0034/chapters/functional-programming-in-coq/Data_and_Functions/proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.9241418121440552, "lm_q1q2_score": 0.850940233655103}} {"text": "(* Exercise for the reader: look into what these standard-library modules contain :-) *)\nRequire Import Coq.Unicode.Utf8 Arith Bool Ring Setoid.\n\n(** This next command (roughly) turns on the sort of implicit-argument behavior we're used to from Haskell or ML: type arguments to polymorphic functions need not be passed explicitly. *)\nSet Implicit Arguments.\n\n\n(** * A simple state machine for factorial *)\n\n(** Here's a classic recursive, functional program for factorial. *)\nFixpoint fact (n : nat) : nat :=\n match n with\n | O => 1\n | S n' => fact n' * S n'\n end.\n\n(** But let's reformulate factorial relationally, as an example to explore treatment of inductive relations in Coq. First, these are the states of our state machine. *)\nInductive fact_state : Set :=\n| AnswerIs : nat -> fact_state\n| WithAccumulator : nat -> nat -> fact_state.\n\n(** This predicate captures which states are starting states. *)\nInductive fact_init (original_input : nat) : fact_state -> Prop :=\n| FactInit : fact_init original_input (WithAccumulator original_input 1).\n\n(** And here are the states where we declare execution complete. *)\nInductive fact_final : fact_state -> Prop :=\n| FactFinal : forall ans, fact_final (AnswerIs ans).\n\n(** The most important part: the relation to step between states *)\nInductive fact_step : fact_state -> fact_state -> Prop :=\n| FactDone : forall acc,\n fact_step (WithAccumulator O acc) (AnswerIs acc)\n| FactStep : forall n acc,\n fact_step (WithAccumulator (S n) acc) (WithAccumulator n (acc * S n)).\n\n(** To prove that our state machine really computes factorial, we introduce an *invariant* on states. *)\nDefinition fact_invariant (original_input : nat) (st : fact_state) : Prop :=\n match st with\n | AnswerIs ans => fact original_input = ans\n | WithAccumulator n acc => fact original_input = fact n * acc\n end.\n\n(** It should hold at the start. *)\nTheorem fact_invariant_init : forall original_input st,\n fact_init original_input st\n -> fact_invariant original_input st.\nProof.\n destruct 1; simpl.\n (** Notice that here we have done case analysis (with [destruct]) on *which*rule*was*used*to*derive*a*predicate*, in the same way that we would use case analysis on e.g. whether a list is [nil] or [cons]. *)\n ring.\n (** Here's a handy tactic for proving goals that follow from the axioms of the algebraic structure *ring*. Actually, it's generalized to semirings, and here we appeal to the semiring structure of the naturals. *)\nQed.\n\n(** And every step should preserve the invariant. *)\nTheorem fact_invariant_preserve : forall original_input st st',\n fact_step st st'\n -> fact_invariant original_input st\n -> fact_invariant original_input st'.\nProof.\n destruct 1; simpl; intros.\n \n rewrite H.\n ring.\n\n rewrite H.\n ring.\nQed.\n\n(** Finally, when the state machine completes, the state must look how we expected. *)\nTheorem fact_invariant_final : forall original_input st,\n fact_final st\n -> fact_invariant original_input st\n -> st = AnswerIs (fact original_input).\nProof.\n destruct 1; simpl; intros.\n\n rewrite H.\n reflexivity.\nQed.\n\n\n(** * Transition systems in general *)\n\n(** Let's define a polymorphic type of states machines, packaging the components we coded in an ad-hoc way for factorial. *)\nRecord transition_system' (State : Set) := {\n Init : State -> Prop;\n Step : State -> State -> Prop;\n Final : State -> Prop\n}.\n\n(** Here's a fun construction, to package a type along with its associated polymorphic value. The [:>] declares a *coercion*, where the [transition_system'] within a [transition_system] is automatically extracted as required by typing. *)\nRecord transition_system := {\n State : Set;\n Super :> transition_system' State\n}.\n\n(** As an example, here's factorial in the new format. *)\nDefinition fact_ts (original_input : nat) := {|\n State := fact_state;\n Super := {| Init := fact_init original_input;\n Step := fact_step;\n Final := fact_final |}\n|}.\n\n(** Now a general relation to capture zero or more steps of transition-system execution *)\nInductive runFrom (ts : transition_system) : State ts -> State ts -> Prop :=\n| RunFinal : forall st,\n Final ts st\n -> runFrom ts st st\n| RunStep : forall st st' st'',\n Step ts st st'\n -> runFrom ts st' st''\n -> runFrom ts st st''.\n\n(** Wrapping it with an extra check that we start in an initial state *)\nInductive run (ts : transition_system) (st : State ts) : Prop :=\n| Run : forall st0,\n Init ts st0\n -> runFrom ts st0 st\n -> run ts st.\n\n(** Here's our first example of *rule*induction*, using the inductive tree structure of proofs. Let's show that [runFrom] only finishes in final states. *)\nLemma runFrom_final : forall ts st st',\n runFrom ts st st'\n -> Final ts st'.\nProof.\n induction 1.\n\n assumption.\n\n assumption.\nQed.\n\n(** It's a simple corollary to lift to [run] insteadof [runFrom]. *)\nLemma run_final : forall ts st,\n run ts st\n -> Final ts st.\nProof.\n destruct 1.\n\n eapply runFrom_final.\n (** [eapply]: like [apply], but leaves *unification*variables* to be determined later *)\n eassumption.\n (** [eassumption]: like [assumption], but will try to fill in *unification*variables *)\nQed.\n\n(** A formal characterization for when a predicate is an invariant of a transition system *)\nInductive isInvariant (ts : transition_system) (inv : State ts -> Prop) : Prop :=\n| IsInvariant : (forall st, Init ts st -> inv st)\n -> (forall st st', Step ts st st' -> inv st -> inv st')\n -> isInvariant ts inv.\n\n(** Let's prove that the conditions we chose are strong enough to show that the invariant is preserved by [runFrom]. *)\nTheorem invariant_preserved : forall ts (inv : State ts -> Prop),\n (forall st st', Step ts st st' -> inv st -> inv st')\n -> forall st st', runFrom ts st st'\n -> inv st\n -> inv st'.\nProof.\n induction 2; intros.\n\n assumption.\n\n apply IHrunFrom.\n eapply H.\n eassumption.\n assumption.\nQed.\n\n(** And it's easy to lift to [run] again. *)\nTheorem invariant_final : forall ts inv st,\n isInvariant ts inv\n -> run ts st\n -> inv st.\nProof.\n destruct 1.\n destruct 1.\n eapply invariant_preserved.\n assumption.\n eassumption.\n apply H.\n assumption.\nQed.\n\n(** So now we can do another proof of factorial via our generic machinery. *)\nTheorem fact_ts_correct : forall original_input st,\n run (fact_ts original_input) st\n -> st = AnswerIs (fact original_input).\nProof.\n intros.\n\n assert (Final (fact_ts original_input) st).\n (** [assert]: a kind of \"cut\": prove an extra fact, then have it as a new hypothesis *)\n apply run_final.\n assumption.\n\n assert (fact_invariant original_input st).\n apply invariant_final.\n apply IsInvariant.\n apply fact_invariant_init.\n apply fact_invariant_preserve.\n assumption.\n\n destruct H0.\n simpl in H1.\n rewrite H1.\n reflexivity.\nQed.\n\n(** * Running transition systems in parallel *)\n\n(** Consider two transition systems with a common notion of shared state and (potentially) their own notions of private state. Let's build a transition system for running them in parallel with nondeterministic interleaving. *)\nInductive parallel_init (Shared Private1 Private2 : Set)\n (Init1 : Shared * Private1 -> Prop)\n (Init2 : Shared * Private2 -> Prop)\n : Shared * Private1 * Private2 -> Prop :=\n| Pinit : forall sh pr1 pr2,\n Init1 (sh, pr1)\n -> Init2 (sh, pr2)\n -> parallel_init Init1 Init2 (sh, pr1, pr2).\n\nInductive parallel_step (Shared Private1 Private2 : Set)\n (Step1 : Shared * Private1 -> Shared * Private1 -> Prop)\n (Step2 : Shared * Private2 -> Shared * Private2 -> Prop)\n : Shared * Private1 * Private2 -> Shared * Private1 * Private2 -> Prop :=\n| Pstep1 : forall sh pr1 pr2 sh' pr1',\n Step1 (sh, pr1) (sh', pr1')\n -> parallel_step Step1 Step2 (sh, pr1, pr2) (sh', pr1', pr2)\n| Pstep2 : forall sh pr1 pr2 sh' pr2',\n Step2 (sh, pr2) (sh', pr2')\n -> parallel_step Step1 Step2 (sh, pr1, pr2) (sh', pr1, pr2').\n\nInductive parallel_final (Shared Private1 Private2 : Set)\n (Final1 : Shared * Private1 -> Prop)\n (Final2 : Shared * Private2 -> Prop)\n : Shared * Private1 * Private2 -> Prop :=\n| Pfinal : forall sh pr1 pr2,\n Final1 (sh, pr1)\n -> Final2 (sh, pr2)\n -> parallel_final Final1 Final2 (sh, pr1, pr2).\n\nDefinition parallel (Shared Private1 Private2 : Set)\n (ts1 : transition_system' (Shared * Private1))\n (ts2 : transition_system' (Shared * Private2)) := {|\n State := Shared * Private1 * Private2;\n Super := {| Init := parallel_init (Init ts1) (Init ts2);\n Step := parallel_step (Step ts1) (Step ts2);\n Final := parallel_final (Final ts1) (Final ts2) |}\n|}.\n\n(** * A simple example of another program as a state transition system *)\n\n(** We'll formalize this pseudocode for one thread of a concurrent, shared-memory program.\n thread(me, other):\n flag[me] = true; (I'm going to wait)\n turn = other; (You go ahead)\n while (flag[other] && turn == other); (I'll wait until you're done)\n local = global; (Access the global state)\n global = local + 1; (increment the global state)\n flag[me] = false; (I'm done)\n *)\n\n(** This inductive state effectively encodes all possible combinations of two kinds of *local*state* in a thread:\n * program counter\n * values of local variables that may be ready eventually *)\n\nInductive peterson_program : Set :=\n| Flag: peterson_program\n| Wait: peterson_program\n| Read : peterson_program\n| Write : nat -> peterson_program\n| Unlock : peterson_program\n| Done : peterson_program.\n\n(** Next, a type for state shared between threads, using Coq's handy record facility, which desugars to single-constructor inductive definitions. *)\nRecord pet_state := {\n FlagOne : bool;\n FlagTwo : bool;\n Turn : bool;\n Global : nat (** A shared counter *)\n}.\n\n(** The combined state, from one thread's perspective. [%type] gets [*] to be parsed as Cartesian product instead of numeric multiplication. *)\nDefinition peterson_state := (pet_state * peterson_program)%type.\n\n(** Now a routine definition of the three key relations of a state-transition system. The most interesting logic surrounds saving the counter value in the local state after reading. *)\n\nInductive peterson_init : peterson_state -> Prop :=\n| IncInit :\n peterson_init ({| FlagOne := false;\n FlagTwo := false;\n Turn := false;\n Global := O |}, Flag).\n\nInductive peterson_step : peterson_state -> peterson_state -> Prop :=\n| IncFlag : forall g t,\n peterson_step ({| FlagOne := false; FlagTwo := false; Turn := t; Global := g |}, Flag)\n ({| FlagOne := true; FlagTwo := false; Turn := false; Global := g |}, Wait)\n| IncWait : forall f1 f2 t g,\n peterson_step ({| FlagOne := f1; FlagTwo := f2; Turn := t; Global := g |}, Wait)\n ({| FlagOne := f1; FlagTwo := f2; Turn := t; Global := g |}, Read)\n| IncRead : forall f1 f2 t g,\n peterson_step ({| FlagOne := f1; FlagTwo := f2; Turn := t; Global := g |}, Read)\n ({| FlagOne := f1; FlagTwo := f2; Turn := t; Global := g |}, Write g)\n| IncWrite : forall f1 f2 t g v,\n peterson_step ({| FlagOne := f1; FlagTwo := f2; Turn := t; Global := g |}, Write v)\n ({| FlagOne := f1; FlagTwo := f2; Turn := t; Global := S v |}, Unlock)\n| IncUnlock : forall f1 f2 t g,\n peterson_step ({| FlagOne := f1; FlagTwo := f2; Turn := t; Global := g |}, Unlock)\n ({| FlagOne := false; FlagTwo := f2; Turn := t; Global := g |}, Done).\n\nInductive peterson_final : peterson_state -> Prop :=\n| IncFinal : forall p: pet_state,\n peterson_final (p, Done).\n\nDefinition peterson_ts := {|\n State := peterson_state;\n Super := {| Init := peterson_init;\n Step := peterson_step;\n Final := peterson_final |}\n|}.\n\n(** * Running transition systems in parallel *)\n\n(** Consider two transition systems with a common notion of shared state and (potentially) their own notions of private state. Let's build a transition system for running them in parallel with nondeterministic interleaving. *)\n\n(** Example: composing two threads of the kind we formalized earlier *)\nDefinition peterson2_ts := parallel peterson_ts peterson_ts.\n\n(** Let's prove that the counter is always 2 when the composed program terminates. *)\n\n(** First big idea: the program counter of a thread tells us how much it has added to the shared counter so far. *)\nDefinition contribution_from (pr : peterson_program) : nat :=\n match pr with\n | Unlock | Done => 1\n | _ => 0\n end.\n\n(** Second big idea: the program counter also tells us whether a thread holds the lock. *)\nDefinition has_lock (pr : peterson_program) : bool :=\n match pr with\n | Read => true\n | Write _ => true\n | Unlock => true\n | _ => false\n end.\n\n(** Now we see that the shared state is a function of the two program counters, as follows. *)\nDefinition shared_from_private (pr1 pr2 : peterson_program) :=\n {| FlagOne := has_lock pr1;\n FlagTwo := has_lock pr2;\n Global := contribution_from pr1 + contribution_from pr2 |}.\n\n(** We also need a condition to formalize compatibility between program counters, e.g. that they shouldn't both be in the critical section at once. *)\nDefinition instruction_ok (self other : peterson_program): Prop :=\n match self with\n | Flag => True\n | Wait => True\n | Read => has_lock other = false\n | Write n => has_lock other = false /\\ n = contribution_from other\n | Unlock => has_lock other = false\n | Done => True\n end.\n\n(** Now we have the ingredients to state the invariant. *)\nInductive peterson2_invariant : State peterson2_ts -> Prop :=\n| Inc2Inv : forall pr1 pr2,\n instruction_ok pr1 pr2\n -> instruction_ok pr2 pr1\n -> peterson2_invariant (shared_from_private pr1 pr2, pr1, pr2).\n\n(** It's convenient to prove this alternative equality-based \"constructor\" for the invariant. *)\nLemma Inc2Inv' : forall sh pr1 pr2,\n sh = shared_from_private pr1 pr2\n -> instruction_ok pr1 pr2\n -> instruction_ok pr2 pr1\n -> peterson2_invariant (sh, pr1, pr2).\nProof.\n intros.\n rewrite H.\n apply Inc2Inv; assumption.\nQed.\n\nLemma final_eq : forall st,\n Final peterson2_ts st\n -> peterson2_invariant st\n -> st = ({| FlagOne := false; FlagTwo := false; Turn := false; Global := 2 |}, Done, Done).\nProof.\n destruct 1.\n inversion H; subst.\n inversion H0; subst.\n intros.\n inversion H1; subst. compute.\n reflexivity.\nQed.\n\nHint Resolve run_final.\n\n(** Now we can prove that the system only runs to happy states. *)\nTheorem increment2_ts_correct : forall st,\n run peterson2_ts st\n -> st = ({| FlagOne := false; FlagTwo := false; Turn := false; Global := 2 |}, Done, Done).\nProof.\n intros.\n apply final_eq; eauto.\n apply invariant_final; auto.\n constructor.\n (** [constructor]: a convenient shorthand for [apply] that picks the rule to apply for you, by searching through the constructors for the inductive type you're trying to prove *)\n\n destruct 1.\n inversion H0; subst.\n inversion H1; subst.\n change {| FlagOne := false; FlagTwo := false; Turn := false; Global := 0 |} with (shared_from_private Flag Flag).\n (** [change]: replace one term with another, when it is sufficiently easy for Coq to see that the two terms are equal (actually when they are *definitionally*equal*, but I won't go into the details here). *)\n constructor; simpl; intuition.\n (** [intuition] simplifies goals according to the rules of propositional (Boolean) logic. (The name tells us that it follows *intuitionistic*, rather than classical, logic.) *)\n\n destruct 1.\n\n (** Some long tactic chains help us consider many cases whether bothering with the details manually. Details are a bit beyond the scope of this lecture. We use [subst], which finds equalities over variables and then eliminates those variables, replacing them with the terms they are equated to. *)\n\n destruct pr2; inversion H0; subst; inversion 1; subst; apply Inc2Inv'; simpl in *; intuition; subst. compute.\n reflexivity || congruence.\n\n destruct pr1; inversion H0; subst; inversion 1; subst; apply Inc2Inv'; simpl in *; intuition; subst;\n reflexivity || congruence.\nQed.\n\n(* assignment *)\n\n", "meta": {"author": "kolemannix", "repo": "oplss2015", "sha": "d2973dfbcb3bc345bec49841fb6c8bbf78d65a16", "save_path": "github-repos/coq/kolemannix-oplss2015", "path": "github-repos/coq/kolemannix-oplss2015/oplss2015-d2973dfbcb3bc345bec49841fb6c8bbf78d65a16/chlipala/Peterson.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248208414329, "lm_q2_score": 0.9059898222871762, "lm_q1q2_score": 0.8507469305573773}} {"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\n\nCheck orb.\nCheck plus_assoc.\nModule NatList. \n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n any number of arguments -- none (as with [true] and [O]), one (as\n with [S]), or more than one, as in this definition: *)\n\nInductive natprod : Type :=\n pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n construct a pair of numbers: by applying the constructor [pair] to\n two arguments of type [nat].\" *)\n\n(** We can construct an element of [natprod] like this: *)\n\nCheck (pair 3 5).\n\n(** *** *)\n\n(** Here are two simple function definitions for extracting the\n first and second components of a pair. (The definitions also\n illustrate how to do pattern matching on two-argument\n constructors.) *)\n\nDefinition fst (p : natprod) : nat := \n match p with\n | pair x y => x\n end.\nDefinition snd (p : natprod) : nat := \n match p with\n | pair x y => y\n end.\n\nEval compute in (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** *** *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n write them with the standard mathematical notation [(x,y)] instead\n of [pair x y]. We can tell Coq to allow this with a [Notation]\n declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n pattern matches (indeed, we've seen it already in the previous\n chapter -- this notation is provided as part of the standard\n library): *)\n\nEval compute in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat := \n match p with\n | (x,y) => x\n end.\nDefinition snd' (p : natprod) : nat := \n match p with\n | (x,y) => y\n end.\n\nDefinition swap_pair (p : natprod) : natprod := \n match p with\n | (x,y) => (y,x)\n end.\n\n(** *** *)\n\n(** Let's try and prove a few simple facts about pairs. If we\n state the lemmas in a particular (and slightly peculiar) way, we\n can prove them with just reflexivity (and its built-in\n simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n (n,m) = (fst (n,m), snd (n,m)).\nProof.\n reflexivity. Qed.\n\n(** Note that [reflexivity] is not enough if we state the lemma in a\n more natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** *** *)\n(** We have to expose the structure of [p] so that [simpl] can\n perform the pattern match in [fst] and [snd]. We can do this with\n [destruct].\n\n Notice that, unlike for [nat]s, [destruct] doesn't generate an\n extra subgoal here. That's because [natprod]s can only be\n constructed in one way. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n p = (fst p, snd p).\nProof.\n intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n intros p. destruct p as [n m].\n simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n fst (swap_pair p) = snd p.\nProof.\n intros p. destruct p as [n m].\n simpl. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n describe the type of _lists_ of numbers like this: \"A list is\n either the empty list or else a pair of a number and another\n list.\" *)\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\nCheck mylist.\n\n(** *** *)\n(** As with pairs, it is more convenient to write lists in\n familiar programming notation. The following two declarations\n allow us to use [::] as an infix [cons] operator and square\n brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n but in case you are interested, here is roughly what's going on.\n\n The [right associativity] annotation tells Coq how to parenthesize\n expressions involving several uses of [::] so that, for example,\n the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n expressions that involve both [::] and some other infix operator.\n For example, since we defined [+] as infix notation for the [plus]\n function at level 50,\nNotation \"x + y\" := (plus x y) \n (at level 50, left associativity).\n The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n + (2 :: [3])].\n\n (By the way, it's worth noting in passing that expressions like \"[1\n + 2 :: [3]]\" can be a little confusing when you read them in a .v\n file. The inner brackets, around 3, indicate a list, but the outer\n brackets, which are invisible in the HTML rendering, are there to\n instruct the \"coqdoc\" tool that the bracketed part should be\n displayed as Coq code rather than running text.)\n\n The second and third [Notation] declarations above introduce the\n standard square-bracket notation for lists; the right-hand side of\n the third one illustrates Coq's syntax for declaring n-ary\n notations and translating them to nested sequences of binary\n constructors. *)\n\n(** *** Repeat *)\n(** A number of functions are useful for manipulating lists.\n For example, the [repeat] function takes a number [n] and a\n [count] and returns a list of length [count] where every element\n is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist := \n match count with\n | O => nil\n | S count' => n :: (repeat n count')\n end.\nEval compute in (repeat 3 5).\n(** *** Length *)\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat := \n match l with\n | nil => O\n | h :: t => S (length t)\n end.\nEval compute in (length [1;1;1;1]).\n\n(** *** Append *)\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist := \n match l1 with\n | nil => l2\n | h :: t => h :: (app t l2)\n end.\nEval compute in (app [1;2] [2;3;4]).\n(** Actually, [app] will be used a lot in some parts of what\n follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y) \n (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(** Here are two smaller examples of programming with lists.\n The [hd] function returns the first element (the \"head\") of the\n list, while [tl] returns everything but the first\n element (the \"tail\"). \n Of course, the empty list has no first element, so we\n must pass a default value to be returned in that case. *)\n\n(** *** Head (with default) and Tail *)\nDefinition hd (default:nat) (l:natlist) : nat :=\n match l with\n | nil => default\n | h :: t => h\n end.\n\nDefinition tl (l:natlist) : natlist :=\n match l with\n | nil => nil \n | h :: t => t\n end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n [countoddmembers] below. Have a look at the tests to understand\n what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\nmatch l with\n| nil => nil\n| h :: t => match h with\n | O => nonzeros t\n | S n' => S n' :: (nonzeros t)\n end\nend.\n\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. simpl. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\nmatch l with\n| nil => nil\n| h :: t => if(oddb h) then h::(oddmembers t) else oddmembers t\nend.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. simpl. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\nmatch l with\n| nil => O\n| h :: t => if(oddb h) then (plus (S O) (countoddmembers t)) else countoddmembers t\nend.\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\nProof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\nProof. simpl. reflexivity. Qed.\nExample test_countoddmembers3: countoddmembers nil = 0.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n into one, alternating between elements taken from the first list\n and elements from the second. See the tests below for more\n specific examples.\n\n Note: one natural and elegant way of writing [alternate] will fail\n to satisfy Coq's requirement that all [Fixpoint] definitions be\n \"obviously terminating.\" If you find yourself in this rut, look\n for a slightly more verbose solution that considers elements of\n both lists at the same time. (One possible solution requires\n defining a new kind of pairs, but this is not the only way.) *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\nmatch l1 with\n| nil => l2\n| h :: t => match l2 with\n | nil => h :: t\n | h' :: t' => h::h'::(alternate t t')\n end\nend.\nExample test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. simpl. reflexivity. Qed.\nExample test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].\nProof. simpl. reflexivity. Qed.\nExample test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].\nProof. simpl. reflexivity. Qed.\nExample test_alternate4: alternate [] [20;30] = [20;30].\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n multiple times instead of just once. One reasonable\n implementation of bags is to represent a bag of numbers as a\n list. *)\n\nDefinition bag := natlist. \n\n(** **** Exercise: 3 stars (bag_functions) *)\n(** Complete the following definitions for the functions\n [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat := \nmatch s with\n| nil => O\n| h :: t=> if(beq_nat v h) then (plus (S O) (count v t)) else (count v t)\nend.\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. simpl. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. simpl. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n all the elements of [a] and of [b]. (Mathematicians usually\n define [union] on multisets a little bit differently, which\n is why we don't use that name for this operation.)\n For [sum] we're giving you a header that does not give explicit\n names to the arguments. Moreover, it uses the keyword\n [Definition] instead of [Fixpoint], so even if you had names for\n the arguments, you wouldn't be able to process them recursively.\n The point of stating the question this way is to encourage you to\n think about whether [sum] can be implemented in another way --\n perhaps by using functions that have already been defined. *)\n\nDefinition sum : bag -> bag -> bag := app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := v::s.\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool := ble_nat 1 (count v s).\nExample test_member1: member 1 [1;4;1] = true.\nProof. simpl. reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\nmatch s with\n| nil => nil\n| h :: t => if(beq_nat v h) then t else h :: (remove_one v t)\nend.\n\nExample test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_one2: count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nEval compute in (remove_one 5 [2;1;4;5;1;4]).\nExample test_remove_one3: count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\nExample test_remove_one4: count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. simpl. reflexivity. Qed.\nEval compute in (remove_one 1 [1;1;1;1;2;3]).\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\nmatch s with\n| nil => nil\n| h :: t => if beq_nat v h then remove_all v t else h :: (remove_all v t)\nend.\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. simpl. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\nmatch s1 with\n| nil => true\n| h :: t => if ble_nat (count h s1) (count h s2) then subset t s2 else false\nend.\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. simpl. reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (bag_theorem) *)\n(** Write down an interesting theorem [bag_theorem] about bags involving\n the functions [count] and [add], and prove it. Note that, since this\n problem is somewhat open-ended, it's possible that you may come up\n with a theorem which is true, but whose proof requires techniques\n you haven't learned yet. Feel free to ask for help if you get\n stuck! *)\nTheorem bag_theorem : forall n:nat, forall s:bag,\ncount n (add n s) = (count n s) + 1.\nProof.\n intros.\n simpl.\n rewrite <- beq_nat_refl.\n rewrite <- plus_comm.\n simpl.\n reflexivity.\nQed.\n(* FILL IN HERE *)\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n functions can sometimes be proved entirely by simplification. For\n example, the simplification performed by [reflexivity] is enough\n for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match position\n in the definition of [app], allowing the match itself to be\n simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n analysis on the possible shapes (empty or non-empty) of an unknown\n list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n pred (length l) = length (tl l).\nProof.\n intros l. destruct l as [| n l'].\n Case \"l = nil\".\n reflexivity.\n Case \"l = cons n l'\". \n reflexivity. Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n tactic here introduces two names, [n] and [l'], corresponding to\n the fact that the [cons] constructor for lists takes two\n arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n It is very important to work through the details of each one,\n using Coq and thinking about what each step achieves. Otherwise\n it is more or less guaranteed that the exercises will make no\n sense... *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n perhaps a little less familiar than standard natural number\n induction, but the basic idea is equally simple. Each [Inductive]\n declaration defines a set of data values that can be built up from\n the declared constructors: a boolean can be either [true] or\n [false]; a number can be either [O] or [S] applied to a number; a\n list can be either [nil] or [cons] applied to a number and a list.\n\n Moreover, applications of the declared constructors to one another\n are the _only_ possible shapes that elements of an inductively\n defined set can have, and this fact directly gives rise to a way\n of reasoning about inductively defined sets: a number is either\n [O] or else it is [S] applied to some _smaller_ number; a list is\n either [nil] or else it is [cons] applied to some number and some\n _smaller_ list; etc. So, if we have in mind some proposition [P]\n that mentions a list [l] and we want to argue that [P] holds for\n _all_ lists, we can reason as follows:\n\n - First, show that [P] is true of [l] when [l] is [nil].\n\n - Then show that [P] is true of [l] when [l] is [cons n l'] for\n some number [n] and some smaller list [l'], assuming that [P]\n is true for [l'].\n\n Since larger lists can only be built up from smaller ones,\n eventually reaching [nil], these two things together establish the\n truth of [P] for all lists [l]. Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist, \n (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3). \nProof.\n intros l1 l2 l3. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons n l1'\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n static written document -- it is easy to see what's going on if\n you are reading the proof in an interactive Coq session and you\n can see the current goal and context at each point, but this state\n is not visible in the written-down parts of the Coq proof. So a\n natural-language proof -- one written for human readers -- will\n need to include more explicit signposts; in particular, it will\n help the reader stay oriented if we remind them exactly what the\n induction hypothesis is in the second case. *)\n\n(** *** Informal version *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3], \n [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n _Proof_: By induction on [l1].\n\n - First, suppose [l1 = []]. We must show\n ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n which follows directly from the definition of [++].\n\n - Next, suppose [l1 = n::l1'], with\n (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n (the induction hypothesis). We must show\n ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]] \n By the definition of [++], this follows from\n n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n which is immediate from the induction hypothesis. []\n*)\n\n(** *** Another example *)\n(**\n Here is a similar example to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist, \n length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n (* WORKED IN CLASS *)\n intros l1 l2. induction l1 as [| n l1'].\n Case \"l1 = nil\".\n reflexivity.\n Case \"l1 = cons\".\n simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n\n(** *** Reversing a list *)\n(** For a slightly more involved example of an inductive proof\n over lists, suppose we define a \"cons on the right\" function\n [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist := \n match l with\n | nil => [v]\n | h :: t => h :: (snoc t v)\n end.\nEval compute in (snoc [1;2;3] 4).\n\n(** ... and use it to define a list-reversing function [rev]\n like this: *)\n\nFixpoint rev (l:natlist) : natlist := \n match l with\n | nil => nil\n | h :: t => snoc (rev t) h\n end.\nEval compute in (rev [1;2;3;4]).\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n(** *** Proofs about reverse *)\n(** Now let's prove some more list theorems using our newly\n defined [snoc] and [rev]. For something a little more challenging\n than the inductive proofs we've seen so far, let's prove that\n reversing a list does not change its length. Our first attempt at\n this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = []\".\n simpl.\n reflexivity.\n Case \"l = n :: l'\".\n (* This is the tricky case. Let's begin as usual \n by simplifying. *)\n simpl. \n (* Now we seem to be stuck: the goal is an equality \n involving [snoc], but we don't have any equations \n in either the immediate context or the global \n environment that have anything to do with [snoc]! \n\n We can make a little progress by using the IH to \n rewrite the goal... *)\n rewrite <- IHl'.\n (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation about [snoc] that would have\n enabled us to make progress and prove it as a separate lemma. \n*)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n length (snoc l n) = S (length l).\nProof.\n intros n l. induction l as [| n' l'].\n Case \"l = nil\".\n simpl.\n reflexivity.\n Case \"l = cons n' l'\".\n simpl. rewrite -> IHl'. reflexivity. Qed. \n\n(**\n Note that we make the lemma as _general_ as possible: in particular,\n we quantify over _all_ [natlist]s, not just those that result\n from an application of [rev]. This should seem natural, \n because the truth of the goal clearly doesn't depend on \n the list having been reversed. Moreover, it is much easier\n to prove the more general property. \n*)\n \n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n length (rev l) = length l.\nProof.\n intros l. induction l as [| n l'].\n Case \"l = nil\".\n simpl.\n reflexivity.\n Case \"l = cons\".\n simpl. rewrite -> length_snoc. \n rewrite -> IHl'. reflexivity. Qed.\n\n(** For comparison, here are informal proofs of these two theorems: \n\n _Theorem_: For all numbers [n] and lists [l],\n [length (snoc l n) = S (length l)].\n \n _Proof_: By induction on [l].\n\n - First, suppose [l = []]. We must show\n length (snoc [] n) = S (length []),\n which follows directly from the definitions of\n [length] and [snoc].\n\n - Next, suppose [l = n'::l'], with\n length (snoc l' n) = S (length l').\n We must show\n length (snoc (n' :: l') n) = S (length (n' :: l')).\n By the definitions of [length] and [snoc], this\n follows from\n S (length (snoc l' n)) = S (S (length l')),\n]] \n which is immediate from the induction hypothesis. [] *)\n \n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n \n _Proof_: By induction on [l]. \n\n - First, suppose [l = []]. We must show\n length (rev []) = length [],\n which follows directly from the definitions of [length] \n and [rev].\n \n - Next, suppose [l = n::l'], with\n length (rev l') = length l'.\n We must show\n length (rev (n :: l')) = length (n :: l').\n By the definition of [rev], this follows from\n length (snoc (rev l') n) = S (length l')\n which, by the previous lemma, is the same as\n S (length (rev l')) = S (length l').\n This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n and pedantic. After the first few, we might find it easier to\n follow proofs that give fewer details (since we can easily work\n them out in our own minds or on scratch paper if necessary) and\n just highlight the non-obvious steps. In this more compressed\n style, the above proof might look more like this: *)\n\n(** _Theorem_:\n For all lists [l], [length (rev l) = length l].\n\n _Proof_: First, observe that\n length (snoc l n) = S (length l)\n for any [l]. This follows by a straightforward induction on [l].\n The main property now follows by another straightforward\n induction on [l], using the observation together with the\n induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n the sophistication of the expected audience and on how similar the\n proof at hand is to ones that the audience will already be\n familiar with. The more pedantic style is a good default for\n present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n already proved, using [rewrite], and later we will see other ways\n of reusing previous theorems. But in order to refer to a theorem,\n we need to know its name, and remembering the names of all the\n theorems we might ever want to use can become quite difficult! It\n is often hard even to remember what theorems have been proven,\n much less what they are named.\n\n Coq's [SearchAbout] command is quite helpful with this. Typing\n [SearchAbout foo] will cause Coq to display a list of all theorems\n involving [foo]. For example, try uncommenting the following to\n see a list of theorems that we have proved about [rev]: *)\n\n(* SearchAbout rev. *)\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n throughout the rest of the course; it can save you a lot of time! *)\n\n(** Also, if you are using ProofGeneral, you can run [SearchAbout]\n with [C-c C-a C-a]. Pasting its response into your buffer can be\n accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist, \n l ++ [] = l. \nProof.\n intros l. induction l as [| n l'].\n Case \"l = nil\".\n simpl. reflexivity.\n Case \"l = n :: l'\".\n simpl. rewrite -> IHl'.\n reflexivity.\nQed.\nTheorem rev_snoc : forall l: natlist, forall n: nat,\nrev (snoc l n) = n :: (rev l).\nProof.\n intros l n. induction l.\n Case \"l = nil\".\n simpl. reflexivity.\n Case \"l = cons\".\n simpl.\n rewrite -> IHl.\n simpl. reflexivity.\nQed.\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\n intros l. induction l as [| n l].\n Case \"l = nil\".\n simpl. reflexivity.\n Case \"l = n :: l\".\n simpl.\n rewrite -> rev_snoc.\n simpl. rewrite -> IHl.\n reflexivity.\nQed.\n\n(** There is a short solution to the next exercise. If you find\n yourself getting tangled up, step back and try to look for a\n simpler way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n intros. \n rewrite -> app_assoc.\n rewrite -> app_assoc.\n reflexivity.\nQed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n snoc l n = l ++ [n].\nProof.\n intros. induction l as [| n' l'].\n Case \"l = nil\".\n simpl.\n reflexivity.\n Case \"l = n l\".\n simpl.\n rewrite -> IHl'.\n reflexivity.\nQed.\n\nTheorem distr_rev : forall l1 l2 : natlist,\n rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n intros. induction l1 as [| n l'].\n Case \"l1 = nil\".\n simpl. rewrite -> app_nil_end.\n reflexivity.\n Case \"l1 = cons\".\n simpl. rewrite -> IHl'.\n rewrite -> snoc_append.\n rewrite -> snoc_append.\n rewrite -> app_assoc.\n reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n intros.\n induction l1.\n Case \"l1 = nil\".\n simpl.\n reflexivity.\n Case \"l1 = cons\".\n simpl.\n rewrite -> IHl1.\n destruct n.\n SCase \"n = O\".\n simpl. reflexivity.\n SCase \"n = S O\".\n simpl. reflexivity.\nQed.\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n lists of numbers for equality. Prove that [beq_natlist l l]\n yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\nmatch l1 with\n| nil => match l2 with\n | nil => true\n | _ => false\n end\n| h :: t => match l2 with\n | nil => false\n | h' :: t' => if beq_nat h h' then beq_natlist t t' else false\n end\nend.\n\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\nExample test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\nExample test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\nTheorem beq_natlist_refl : forall l:natlist,\n true = beq_natlist l l.\nProof.\n intros. induction l.\n Case \"l = nil\".\n simpl. reflexivity.\n Case \"l = cons\".\n simpl. rewrite <- beq_nat_refl.\n rewrite -> IHl.\n reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 2 stars (list_design) *)\n(** Design exercise: \n - Write down a non-trivial theorem [cons_snoc_app]\n involving [cons] ([::]), [snoc], and [app] ([++]). \n - Prove it. *) \nTheorem app_cons_snoc_app: forall l1 l2:natlist, forall n:nat,\nl1 ++ (n::l2) = (snoc l1 n) ++ l2.\nProof.\n intros.\n rewrite -> snoc_append.\n rewrite -> app_assoc.\n assert (H: n :: l2 = [n] ++ l2).\n Case \"Proof of H\".\n simpl. reflexivity.\n rewrite -> H.\n reflexivity.\nQed.\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n definitions about bags earlier in the file. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n intros.\n destruct s.\n Case \"s = nil\".\n simpl. reflexivity.\n Case \"s = cons\".\n simpl. reflexivity.\nQed.\n\n(** The following lemma about [ble_nat] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n ble_nat n (S n) = true.\nProof.\n intros n. induction n as [| n'].\n Case \"0\". \n simpl. reflexivity.\n Case \"S n'\".\n simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n intros.\n induction s.\n Case \"s = nil\".\n simpl. reflexivity.\n Case \"s = cons\".\n simpl.\n destruct n.\n SCase \"n = O\".\n rewrite -> ble_n_Sn. reflexivity.\n SCase \"n = S n\".\n simpl.\n rewrite -> IHs.\n reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *) \n(** Write down an interesting theorem [bag_count_sum] about bags \n involving the functions [count] and [sum], and prove it.*)\nTheorem bag_sum_count: forall s1 s2:bag, forall n:nat,\ncount n (sum s1 s2) = (count n s1) + (count n s2).\nProof.\n intros s1 s2 n. induction s1 as [| h1 t1].\n Case \"s1 = []\". reflexivity.\n Case \"s1 = h1::t1\".\n simpl. rewrite IHt1. \n destruct (beq_nat n h1) as [false | true].\n SCase \"beq_nat n h1 = false\".\n simpl. reflexivity.\n SCase \"beq_nat n h1 = true\".\n reflexivity.\nQed.\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nThere is a hard way and an easy way to solve this exercise.\n*)\nTheorem rev_injective: forall l1 l2:natlist,\nrev l1 = rev l2 -> l1 = l2.\nProof.\n intros.\n rewrite <- rev_involutive.\n rewrite <- H.\n rewrite -> rev_involutive.\n reflexivity.\nQed.\n(* FILL IN HERE *)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n\n(** One use of [natoption] is as a way of returning \"error\n codes\" from functions. For example, suppose we want to write a\n function that returns the [n]th element of some list. If we give\n it type [nat -> natlist -> nat], then we'll have to return some\n number when the list is too short! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n match l with\n | nil => 42 (* arbitrary! *)\n | a :: l' => match beq_nat n O with \n | true => a \n | false => index_bad (pred n) l' \n end\n end.\nEval compute in (index_bad 2 [1;2;3;4]).\n(** *** *)\n(** On the other hand, if we give it type [nat -> natlist ->\n natoption], then we can return [None] when the list is too short\n and [Some a] when the list has enough members and [a] appears at\n position [n]. *)\n\nInductive natoption : Type :=\n | Some : nat -> natoption\n | None : natoption. \n\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => match beq_nat n O with \n | true => Some a\n | false => index (pred n) l' \n end\n end.\nEval compute in (index 2 [1;2;2]).\n\nExample test_index1 : index 0 [4;5;6;7] = Some 4.\nProof. reflexivity. Qed.\nExample test_index2 : index 3 [4;5;6;7] = Some 7.\nProof. reflexivity. Qed.\nExample test_index3 : index 10 [4;5;6;7] = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n small feature of Coq's programming language: conditional\n expressions... *)\n\n(** *** *)\n\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n match l with\n | nil => None \n | a :: l' => if beq_nat n O then Some a else index' (pred n) l'\n end.\n\n(** Coq's conditionals are exactly like those found in any other\n language, with one small generalization. Since the boolean type\n is not built in, Coq actually allows conditional expressions over\n _any_ inductively defined type with exactly two constructors. The\n guard is considered true if it evaluates to the first constructor\n in the [Inductive] definition and false if it evaluates to the\n second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n match o with\n | Some n' => n'\n | None => d\n end.\nEval compute in (option_elim 1 None).\n\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n have to pass a default element for the [nil] case. *)\n\nDefinition hd_opt (l : natlist) : natoption :=\nmatch l with\n| nil => None\n| h::t=> Some h\nend.\n\n\nExample test_hd_opt1 : hd_opt [] = None.\nProof. reflexivity. Qed.\nExample test_hd_opt2 : hd_opt [1] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n hd default l = option_elim default (hd_opt l).\nProof.\n intros.\n induction l.\n simpl. reflexivity.\n simpl. reflexivity.\nQed. \n(** [] *)\n\n(* ###################################################### *)\n(** * Dictionaries *)\n\n(** As a final illustration of how fundamental data structures\n can be defined in Coq, here is the declaration of a simple\n [dictionary] data type, using numbers for both the keys and the\n values stored under these keys. (That is, a dictionary represents\n a finite map from numbers to numbers.) *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n | empty : dictionary \n | record : nat -> nat -> dictionary -> dictionary. \n\n(** This declaration can be read: \"There are two ways to construct a\n [dictionary]: either using the constructor [empty] to represent an\n empty dictionary, or by applying the constructor [record] to\n a key, a value, and an existing [dictionary] to construct a\n [dictionary] with an additional key to value mapping.\" *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n (record key value d).\nEval compute in (insert 1 2 (record 3 4 empty)).\n\n(** Here is a function [find] that searches a [dictionary] for a\n given key. It evaluates evaluates to [None] if the key was not\n found and [Some val] if the key was mapped to [val] in the\n dictionary. If the same key is mapped to multiple values, [find]\n will return the first one it finds. *)\n\nFixpoint find (key : nat) (d : dictionary) : natoption := \n match d with \n | empty => None\n | record k v d' => if (beq_nat key k) \n then (Some v) \n else (find key d')\n end.\nEval compute in (find 1 empty).\nEval compute in (find 1 (record 1 2 empty)).\n\n\n(** **** Exercise: 1 star (dictionary_invariant1) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n (find k (insert k v d)) = Some v.\nProof.\n intros.\n simpl.\n rewrite <- beq_nat_refl.\n reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),\n beq_nat m n = false -> find m d = find m (insert n o d).\nProof.\n intros.\n simpl.\n rewrite -> H.\n reflexivity.\nQed.\n(** [] *)\n\n\n\nEnd Dictionary.\n\nEnd NatList.\n\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)\n\n", "meta": {"author": "ZefengZeng", "repo": "software-foundation", "sha": "852fe296ef91b8f25fb3a5939694e591c8d4df26", "save_path": "github-repos/coq/ZefengZeng-software-foundation", "path": "github-repos/coq/ZefengZeng-software-foundation/software-foundation-852fe296ef91b8f25fb3a5939694e591c8d4df26/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.9161096170250074, "lm_q1q2_score": 0.8505242307194975}} {"text": "(* week-15_two-by-two-matrices.v *)\n(* YSC3236 2017-2018, Sem1 *)\n(* Olivier Danvy *)\n(* Version of Tue 21 Nov 2017 *)\n\n(* ********** *)\n\n(*\n name:Jeremy Yew\n student ID number:A0156262H\n e-mail address:jeremy.yew@u.yale-nus.edu.sg\n*)\n\n(* ********** *)\n\nLtac unfold_tactic name :=\n intros;\n unfold name; (* fold name; *)\n reflexivity.\n \nRequire Import Arith Bool.\n\n(* ********** *)\n\n(* The goal of this project is to study 2x2 matrices,\n along the lines of Section 5 of\n http://users-cs.au.dk/danvy/more-about-induction-proofs.pdf\n*)\n\nInductive m22 : Type :=\n| M22 : nat -> nat -> nat -> nat -> m22.\n\n\n(*\n1. Definition 9: Multiplication of 2*2 matrices\n *)\n\n(*\n|x11 x12| |y11 y12|\n|x21 x22| * |y21 y22|\n *)\n\nDefinition mul_m22 (X Y : m22) : m22 :=\n match X with\n | M22 x11 x12\n x21 x22 =>\n match Y with\n | M22 y11 y12\n y21 y22 =>\n M22 (x11 * y11 + x12 * y21) (x11 * y12 + x12 * y22)\n (x21 * y11 + x22 * y21) (x21 * y12 + x22 * y22)\n end\n end.\n\nCompute mul_m22 (M22 1 2 3 4) (M22 1 0 0 1).\n\n (*\n2. Addition of Matrices\n*)\n\nDefinition add_m22 (X Y : m22) : m22 :=\n match X with\n | M22 x11 x12\n x21 x22 =>\n match Y with\n | M22 y11 y12\n y21 y22 =>\n M22 (x11 + y11) (x12 + y12)\n (x21 + y21) (x22 + y22)\n end\n end.\n\n(*\n3. Definitions 11 and 13\n*)\n\nDefinition I :=\n M22 1 0 0 1.\n \nFixpoint exp_m22 (n : nat) (M : m22) : m22 :=\n match n with\n | O =>\n I\n | S n' => mul_m22 (exp_m22 n' M) M\n end.\n\nLemma unfold_exp_m22_O:\n forall (M : m22),\n exp_m22 0 M = I.\nProof. \n unfold_tactic exp_m22.\nQed.\nLemma unfold_exp_m22_S:\n forall (n' : nat) (M : m22),\n exp_m22 (S n') M = mul_m22 (exp_m22 n' M) M.\nProof. \n unfold_tactic exp_m22.\nQed.\n\n(*\n4. Properties 10 and 12\n *)\n\nLemma shuffle_helper:\n forall (n m p q : nat),\n n + m + p + q = n + p + m + q.\nProof.\n intros n m p q.\n Check (Nat.add_assoc).\n rewrite <- Nat.add_assoc.\n rewrite -> Nat.add_shuffle1.\n rewrite -> Nat.add_assoc.\n reflexivity.\nQed.\n\nTheorem mul_m22_associative:\n forall (X Y Z : m22),\n mul_m22 X (mul_m22 Y Z) = mul_m22 (mul_m22 X Y) Z. \nProof.\n intros [x11 x12 x21 x22] [y11 y12 y21 y22] [z11 z12 z21 z22].\n unfold mul_m22.\n Check (Nat.mul_add_distr_l).\n rewrite ->8 Nat.mul_add_distr_l.\n rewrite ->8 Nat.mul_add_distr_r.\n Check (Nat.mul_assoc).\n rewrite -> 16 Nat.mul_assoc.\n rewrite ->8 Nat.add_assoc.\n rewrite -> (shuffle_helper _ (x11 * y12 * z21) (x12 * y21 * z11) _).\n rewrite -> (shuffle_helper _ (x11 * y12 * z22) (x12 * y21 * z12) _).\n rewrite -> (shuffle_helper _ (x21 * y12 * z21) (x22 * y21 * z11) _).\n rewrite -> (shuffle_helper _ (x21 * y12 * z22) (x22 * y21 * z12) _).\n reflexivity.\nQed.\n\nTheorem I_neutral_mul_m22_l:\n forall (M : m22),\n mul_m22 I M = M. \nProof.\n intros [x11 x12 x21 x22]. \n unfold I.\n unfold mul_m22. \n rewrite ->4 Nat.mul_1_l.\n rewrite ->4 Nat.mul_0_l.\n rewrite ->2 Nat.add_0_l.\n rewrite ->2 Nat.add_0_r.\n reflexivity.\nQed.\n\n\nTheorem I_neutral_mul_m22_r:\n forall (M : m22),\n mul_m22 M I = M. \nProof.\n intros [x11 x12 x21 x22]. \n unfold I.\n unfold mul_m22. \n rewrite ->4 Nat.mul_1_r.\n rewrite ->4 Nat.mul_0_r.\n rewrite ->2 Nat.add_0_l.\n rewrite ->2 Nat.add_0_r.\n reflexivity.\nQed.\n\n(*\n5. \nProposition 14\n*)\n\nProposition exponentiation_M22_1101:\n forall (n : nat),\n exp_m22 n (M22 1 1 0 1) = (M22 1 n 0 1).\nProof.\n intro n.\n induction n as [ | n' IHn'].\n rewrite -> unfold_exp_m22_O.\n unfold I.\n reflexivity.\n\n rewrite -> unfold_exp_m22_S.\n rewrite -> IHn'.\n unfold mul_m22.\n rewrite -> Nat.mul_0_l.\n rewrite ->2 Nat.mul_0_r.\n rewrite ->2 Nat.mul_1_r.\n rewrite ->2 Nat.add_0_r.\n rewrite -> Nat.add_0_l.\n rewrite -> Nat.add_1_l at 1.\n reflexivity.\nQed.\n(*\n6. Exercise 28\n*)\n\nFixpoint exp_m22_alt (n : nat) (M : m22) : m22 :=\n match n with\n | O =>\n I\n | S n' => mul_m22 M (exp_m22_alt n' M)\n end.\n\nLemma unfold_exp_m22_alt_O:\n forall (M : m22),\n exp_m22_alt 0 M = I.\nProof. \n unfold_tactic exp_m22_alt.\nQed.\nLemma unfold_exp_m22_alt_S:\n forall (n' : nat) (M : m22),\n exp_m22_alt (S n') M = mul_m22 M (exp_m22_alt n' M).\nProof. \n unfold_tactic exp_m22_alt.\nQed.\n\nProposition exponentiation_M22_1101':\n forall (n : nat),\n exp_m22_alt n (M22 1 1 0 1) = (M22 1 n 0 1).\nProof.\n intro n.\n induction n as [ | n' IHn'].\n rewrite -> unfold_exp_m22_alt_O.\n unfold I.\n reflexivity.\n\n rewrite -> unfold_exp_m22_alt_S.\n rewrite -> IHn'.\n unfold mul_m22.\n rewrite ->2 Nat.mul_0_l.\n rewrite -> Nat.mul_0_r.\n rewrite -> Nat.mul_1_r.\n rewrite -> Nat.mul_1_l.\n rewrite ->2 Nat.add_0_r. \n rewrite -> Nat.add_0_l.\n rewrite -> Nat.add_1_r.\n reflexivity.\nQed.\n\n(*\n7. Proposition 29\n*)\n\nProposition about_exp_m22_S:\n forall (n : nat) (M : m22),\n mul_m22 M (exp_m22 n M) = mul_m22 (exp_m22 n M) M. \nProof.\n intros n M.\n induction n as [ | n' IHn'].\n\n rewrite -> unfold_exp_m22_O.\n rewrite -> I_neutral_mul_m22_l.\n rewrite -> I_neutral_mul_m22_r.\n reflexivity.\n\n rewrite -> unfold_exp_m22_S.\n rewrite -> mul_m22_associative.\n rewrite -> IHn'.\n reflexivity.\nQed. \n\n(*\n8. Exercise 31\n*)\n\nProposition about_exp_m22_S':\n forall (n : nat) (M : m22),\n mul_m22 M (exp_m22_alt n M) = mul_m22 (exp_m22_alt n M) M. \nProof.\n intros n M.\n induction n as [ | n' IHn'].\n\n rewrite -> unfold_exp_m22_alt_O.\n rewrite -> I_neutral_mul_m22_l.\n rewrite -> I_neutral_mul_m22_r.\n reflexivity.\n\n rewrite -> unfold_exp_m22_alt_S.\n rewrite -> IHn'.\n rewrite -> mul_m22_associative.\n rewrite -> IHn'.\n reflexivity.\nQed. \n\n(* \n9. Corollary 32\n*)\n\nCorollary equivalence_of_exp_m22_and_exp_m22_alt:\n forall (n : nat) (M : m22),\n exp_m22 n M = exp_m22_alt n M.\nProof.\n intros n M.\n induction n as [ | n IHn'].\n\n rewrite -> unfold_exp_m22_O.\n rewrite -> unfold_exp_m22_alt_O.\n reflexivity.\n\n rewrite -> unfold_exp_m22_S.\n rewrite -> unfold_exp_m22_alt_S.\n rewrite <- IHn'.\n rewrite -> about_exp_m22_S.\n reflexivity.\nQed.\n\n(*\n10. Exercise 34 \n *)\n\nProposition exponentiation_M22_1011:\n forall (n : nat),\n exp_m22 n (M22 1 0 1 1) = M22 1 0 n 1.\nProof.\n intro n.\n induction n as [ | n' IHn'].\n \n rewrite -> unfold_exp_m22_O.\n unfold I.\n reflexivity.\n\n rewrite -> unfold_exp_m22_S.\n rewrite -> IHn'.\n unfold mul_m22.\n rewrite -> Nat.mul_0_l.\n rewrite ->2 Nat.mul_0_r.\n rewrite ->2 Nat.add_0_r.\n rewrite -> Nat.add_0_l.\n rewrite ->2 Nat.mul_1_r.\n rewrite -> Nat.add_1_r at 1.\n reflexivity.\nQed.\n\n(*\n11. Definition 35\n *)\n\nDefinition transpose_m22 (M : m22) : m22 :=\n match M with\n | M22 x11 x12\n x21 x22 =>\n M22 x11 x21\n x12 x22\n end.\n\nCompute transpose_m22 (M22 1 2 3 4).\n\n(*\n12. Proposition 36\n*)\n\nProposition transposition_involutive:\n forall (M : m22),\n transpose_m22 (transpose_m22 M) = M.\nProof.\n intros [x11 x12 x21 x22].\n unfold transpose_m22.\n unfold transpose_m22.\n reflexivity.\nQed.\n\n(*\n13. Lemma 37\n*)\n\nLemma transposition_distr_over_mul:\n forall (X Y : m22), \n transpose_m22 (mul_m22 X Y) = mul_m22 (transpose_m22 Y) (transpose_m22 X).\nProof.\n intros [x11 x12 x21 x22] [y11 y12 y21 y22].\n unfold mul_m22 at 1.\n unfold transpose_m22.\n unfold mul_m22.\n\n rewrite -> (Nat.mul_comm x11 y11).\n rewrite -> (Nat.mul_comm x12 y21).\n rewrite -> (Nat.mul_comm x21 y11).\n rewrite -> (Nat.mul_comm x22 y21).\n rewrite -> (Nat.mul_comm x11 y12).\n rewrite -> (Nat.mul_comm x12 y22).\n rewrite -> (Nat.mul_comm x21 y12).\n rewrite -> (Nat.mul_comm x22 y22).\n reflexivity.\nQed.\n\n(*\n14. Proposition 38\n *)\nProposition transp_and_exp_commutative:\n forall (n : nat) (M : m22),\n transpose_m22 (exp_m22 n M) = exp_m22 n (transpose_m22 M).\nProof.\n intros n [x11 x12 x21 x22].\n induction n as [ | n' IHn'].\n\n rewrite -> unfold_exp_m22_O.\n unfold transpose_m22 at 2.\n rewrite -> unfold_exp_m22_O.\n unfold I.\n unfold transpose_m22.\n reflexivity.\n\n unfold transpose_m22 at 2.\n rewrite ->2 unfold_exp_m22_S.\n rewrite -> transposition_distr_over_mul.\n rewrite -> IHn'.\n unfold transpose_m22.\n rewrite -> about_exp_m22_S.\n reflexivity.\nQed.\n\n(*\n15. Exercise 40\n *)\n\nProposition exponentiation_M22_1011':\n forall (n : nat),\n exp_m22 n (M22 1 0 1 1) = M22 1 0 n 1.\nProof.\n intro n.\n rewrite <- (transposition_involutive (M22 1 0 n 1)).\n rewrite <- (transposition_involutive (M22 1 0 1 1)). \n unfold transpose_m22 at 2.\n unfold transpose_m22 at 3.\n rewrite <- (exponentiation_M22_1101 n).\n rewrite -> transp_and_exp_commutative.\n reflexivity.\nQed.\n\n(*\n16. Exercise 25. \n *)\nDefinition F:= M22 1 1 1 0. \nCompute (exp_m22 0 F). (* M22 1 0 0 1 *)\nCompute (exp_m22 1 F). (* M22 1 1 1 0 *)\nCompute (exp_m22 2 F). (* M22 2 1 1 1 *)\nCompute (exp_m22 3 F). (* M22 3 2 2 1 *)\nCompute (exp_m22 4 F). (* M22 5 3 3 2 *)\nCompute (exp_m22 5 F). (* M22 8 5 5 3 *)\nCompute (exp_m22 6 F). (* M22 13 8 8 5 *)\nCompute (exp_m22 7 F). (* M22 21 13 13 8 *)\nCompute (exp_m22 8 F). (* M22 34 21 21 13 *)\n\n\nNotation \"A =n= B\" :=\n (beq_nat A B) (at level 70, right associativity).\n\n\nDefinition test_fib (candidate: nat -> nat) : bool :=\n (candidate 0 =n= 0)\n && \n (candidate 1 =n= 1)\n && \n (candidate 2 =n= 1)\n && \n (candidate 3 =n= 2)\n && \n (candidate 4 =n= 3)\n && \n (candidate 5 =n= 5)\n && \n (candidate 6 =n= 8)\n && \n (candidate 7 =n= 13)\n && \n (candidate 8 =n= 21)\n.\n\nFixpoint fib (n: nat) : nat:=\n match n with\n | 0 => O\n | S n' => match n' with\n | O => 1\n | S n'' => fib n' + fib n''\n end\n end.\n\nCompute (test_fib fib).\n \nLemma unfold_fib_0:\n fib 0 = 0.\nProof.\n unfold_tactic fib.\nQed.\n\nLemma unfold_fib_1:\n fib 1 = 1.\nProof.\n unfold_tactic fib.\nQed.\n\nLemma unfold_fib_SSn:\n forall (n'': nat),\n fib (S (S n'')) = fib (S n'') + fib n''.\nProof.\n unfold_tactic fib.\nQed.\n\nProposition powers_of_F:\n forall (n : nat),\n exp_m22 (S n) F = M22 (fib (S (S n)))\n (fib (S n))\n (fib (S n))\n (fib n).\nProof.\n intro n.\n induction n as [ | n' IHn'].\n\n unfold exp_m22.\n rewrite -> I_neutral_mul_m22_l.\n unfold F.\n rewrite -> unfold_fib_SSn.\n rewrite -> unfold_fib_0.\n rewrite -> unfold_fib_1.\n rewrite -> Nat.add_0_r.\n reflexivity.\n\n rewrite -> unfold_exp_m22_S.\n rewrite -> IHn'.\n unfold F.\n unfold mul_m22.\n rewrite ->3 Nat.mul_1_r.\n rewrite ->2 Nat.mul_0_r.\n rewrite ->2 Nat.add_0_r.\n\n rewrite ->2 unfold_fib_SSn.\n reflexivity.\nQed.\n\n\nFixpoint visit_fib_v3 (n : nat) : nat * nat :=\n match n with\n | 0 => (0, 1)\n | S n' => match visit_fib_v3 n' with\n | (a1, a2) => (a2, a1 + a2)\n end\n end.\n\nDefinition fib_v3 (n : nat) : nat :=\n match visit_fib_v3 n with\n | (a1, a2) => a1\n end.\n\nCompute (test_fib fib_v3).\n\n\nDefinition fib_v4 (n : nat) : nat :=\n match exp_m22 n F with\n | M22 m11 m12 m21 m22 => m12\n end.\n\nCompute (test_fib fib_v4).\n \nDefinition fib_v5 (n : nat) : nat :=\n match n with\n | O =>\n 0\n | S n =>\n match n with\n | O =>\n 1\n | S n' =>\n match (exp_m22 n' F) with\n | M22 m11 m12 m21 m22 => m11 + m12\n end\n end\n end.\n\nCompute (test_fib fib_v5).\n\nProposition fibonacci_addition_of_powers_of_F:\n forall (n : nat),\n add_m22 (exp_m22 n F) (exp_m22 (S n) F) = (exp_m22 (S (S n)) F). \nProof.\n intro n.\n induction n as [ | n' IHn'].\n\n unfold F.\n unfold exp_m22.\n rewrite -> I_neutral_mul_m22_l.\n unfold mul_m22.\n unfold I.\n unfold add_m22.\n rewrite ->2 Nat.mul_0_r.\n rewrite -> Nat.mul_0_l.\n rewrite ->2 Nat.add_0_r.\n rewrite -> Nat.add_0_l.\n rewrite -> Nat.mul_1_r.\n rewrite -> Nat.add_1_r.\n reflexivity.\n \n rewrite ->3 powers_of_F.\n unfold add_m22.\n rewrite -> (Nat.add_comm (fib (S (S n'))) (fib (S (S (S n'))))).\n rewrite <- (unfold_fib_SSn (S (S n'))).\n rewrite -> (Nat.add_comm (fib (S n')) (fib (S (S n')))).\n rewrite <- (unfold_fib_SSn (S n')).\n rewrite -> (Nat.add_comm (fib n') (fib (S n'))).\n rewrite <- (unfold_fib_SSn n').\n reflexivity.\nQed. \n\n\n (*\n X * implement Definition 9 (i.e., the multiplication of 2*2-matrices),\n\n X * implement the addition of 2*2-matrices\n\n X * implement Definitions 11 and 13,\n\n X * prove Properties 10 and 12,\n\n X * formalize Proposition 14 and its proof in Coq,\n\n X * implement Definition 27,\n\n X * solve Exercise 28,\n\n X * formalize Proposition 29 and its proof in Coq,\n\n X * solve Exercise 31,\n\n X * implement Corollary 32,\n\n X * solve Exercise 34,\n\n X * implement Definition 35,\n\n X * prove Property 36,\n\n X * formalize Proposition 37 and its proof in Coq,\n\n X * formalize Proposition 38 and its proof in Coq,\n\n X * solve Exercise 40, and to\n\n X * solve Exercise 25.\n\n X Subsidiary question for Exercise 25:\n characterize the result of adding F^n and F^(n+1), for any n : nat\n*)\n\n(* ********** *)\n\n(* end of week-15_two-by-two-matrices.v *)\n", "meta": {"author": "jeremyyew", "repo": "ync-capstone", "sha": "496ea60a2fe1e4bdd36ae9b2a8be1f7338c3823b", "save_path": "github-repos/coq/jeremyyew-ync-capstone", "path": "github-repos/coq/jeremyyew-ync-capstone/ync-capstone-496ea60a2fe1e4bdd36ae9b2a8be1f7338c3823b/misc/coq-samples/fpp-2017/jeremy_week-15_two-by-two-matrices-2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321807, "lm_q2_score": 0.8962513786759492, "lm_q1q2_score": 0.8504684078411293}} {"text": "Require Import Arith.\nRequire Import ArithRing Ring.\n\nTheorem invert : forall a b : nat, a + a = b + b -> a = b.\nProof.\n induction a.\n -intros b H. destruct b.\n +auto.\n +discriminate.\n -intros b H. destruct b.\n +discriminate.\n +inversion H.\n rewrite <- plus_n_Sm in H1.\n rewrite <- plus_n_Sm in H1.\n inversion H1.\n rewrite (IHa b H2).\n auto.\nQed.\n\n(*Tsinghua Class1*)\n\nDefinition f := fun x y => x^2+y^2.\n\nExample f_test : f 3 4 = 25.\nProof. auto. Qed.\n\nFixpoint sum (n : nat) :=\n match n with\n | 0 => 0\n | S n' => n^2 + sum(n')\n end.\n\nExample sum_test : sum 2 = 5.\nProof. auto. Qed.\n\nLemma Sn_exp : forall n : nat,\n S n = n + 1.\nProof.\n induction n.\n-auto.\n-simpl.\n rewrite IHn.\n auto.\nQed.\n \nLemma mult_distr_r : forall n m p : nat,\n n * (m + p) = n * m + n * p.\nProof.\n intros n m p.\n induction n.\n -auto.\n -simpl.\n rewrite IHn.\n ring.\nQed.\n\nLemma sum_helper : forall n : nat,\n sum (S n) = sum n + (n + 1)^2.\nProof.\n induction n.\n -auto.\n -rewrite IHn.\n simpl.\n ring.\nQed.\n\nLemma n_sum_helper : forall n : nat,\n S n * (S n + 1) * (2 * S n + 1) = n * (n + 1) * (2*n+1) + 6 * (n + 1)^2.\nProof.\n destruct n.\n -auto.\n -simpl. rewrite Sn_exp.\n ring.\nQed.\n \nTheorem sum_exp : forall n : nat,\n 6 * sum n = n * (n+1) * (2*n+1).\nProof.\n induction n.\n -auto.\n -rewrite sum_helper.\n rewrite mult_distr_r.\n rewrite IHn.\n rewrite n_sum_helper.\n auto.\nQed.\n", "meta": {"author": "Whu-Lambda", "repo": "Lambda-Cube", "sha": "6845929d9f816a350e65b33078657b14ae940693", "save_path": "github-repos/coq/Whu-Lambda-Lambda-Cube", "path": "github-repos/coq/Whu-Lambda-Lambda-Cube/Lambda-Cube-6845929d9f816a350e65b33078657b14ae940693/第一次分享会/Coq 小课堂/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.8991213853793453, "lm_q1q2_score": 0.8503901442141486}} {"text": "Inductive day : Type :=\n | monday : day\n | tuesday : day\n | wednesday : day\n | thursday : day\n | friday : day\n | saturday : day\n | sunday : day.\n\nDefinition next_weekday (d:day) : day :=\n match d with\n | monday => tuesday\n | tuesday => wednesday\n | wednesday => thursday\n | thursday => friday\n | friday => monday\n | saturday => monday\n | sunday => monday\n end. \n\nExample test_next_weekday:\n (next_weekday (next_weekday saturday)) = tuesday.\n\nProof. simpl. reflexivity. Qed.\n\n(* Booleans type *) \n\nInductive bool : Type :=\n | true : bool\n | false : bool.\n\n(* !函数 *)\nDefinition negb (b: bool) : bool :=\n\tmatch b with\n\t| true => false\n\t| false => true\n\tend.\n\n(* and *)\nDefinition andb (b1: bool) (b2: bool) : bool :=\n\tmatch b1 with\n\t| true => b2\n\t| false => false\n\tend.\n\nDefinition orb (b1: bool) (b2: bool) : bool :=\n\tmatch b1 with\n\t| true => true\n\t| false => b2\n\tend.\n\n(* 符号定义 宏定义方法 *)\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_andb_notation:\n true && true = true .\nProof. simpl. reflexivity. Qed.\n\n(* Compound Types *)\nInductive rgb : Type := \n | red : rgb\n | green : rgb\n | blue : rgb.\n\n\n(* 如果 p 属于集合 rgb, 则 primary p 属于集合 color *)\nInductive color : Type :=\n | black : color\n | white : color\n | primary : rgb -> color.\n\n\nCheck primary red. (* color 类型 *)\n\n\nDefinition monochrome (c : color) : bool := \n match c with\n | black => true\n | white => true\n | primary p => false\n end.\n\nExample test_monochrome1: (monochrome black) = true.\nProof. simpl. reflexivity. Qed.\nExample test_monochrime2: (monochrome white) = true.\nProof. simpl. reflexivity. Qed.\nExample test_monochrime3: (monochrome (primary red)) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition isred (c : color) : bool :=\n match c with\n | black => false\n | white => false\n | primary red => true\n | primary _ => false\n end.\n\nExample test_isred1: ( isred black ) = false.\nProof. simpl. reflexivity. Qed.\nExample test_isred2: ( isred white ) = false.\nProof. simpl. reflexivity. Qed.\nExample test_isred3: ( isred (primary red) ) = true.\nProof. simpl. reflexivity. Qed.\nExample test_isrea4: ( isred (primary blue) ) = false.\nProof. simpl. reflexivity. Qed.\n\n(* 定义自己的自然数,防止和libraries冲突 *)\nModule NatPlayground.\n\n(*\n1. O 是一个自然数\n2. S 提供一个自然数 n 可以产生下一个自然数,也就是说 n 是一个自然数的话, S n 也是一个自然数\n\nO => 0\nS O => 1\nS (S O) => 2\nS (S (S O)) => 3\nS (S (S (S O))) => 4\nS (S (S (S (S O)))) => 5\nS (S (S (S (S (S O))))) => 6\nS (S (S (S (S (S (S O)))))) => 7\nS (S (S (S (S (S (S (S O))))))) => 8\nS (S (S (S (S (S (S (S (S O)))))))) => 9\nS (S (S (S (S (S (S (S (S (S O))))))))) => 10\n*)\n\n\nInductive nat : Type :=\n | O : nat\n | S : nat -> nat.\n\n(*\n O 没有前置\n S n' 前置为 n'\n*)\nDefinition pred (n : nat) : nat :=\n match n with\n | O => O\n | S n' => n'\n end.\n\nExample test_pred1: ( pred O ) = O.\nProof. simpl. reflexivity. Qed.\nExample test_pred2: ( pred (S O) ) = O.\nProof. simpl. reflexivity. Qed.\nExample test_pred3: ( pred (S (S O)) ) = S O.\nProof. simpl. reflexivity. Qed.\nExample test_pred4: ( pred (S (S (S O))) ) = (S (S O)).\nProof. simpl. reflexivity. Qed.\n\nEnd NatPlayground.\nCheck (O).\nCheck (S (S (S O))).\n\n(* 定义一个自然数减2 *)\nDefinition minustwo (n : nat) : nat :=\n match n with\n | O => O\n | S O => O\n | S (S n') => n' (* S (S n') 减去 外面两层,得到内层 n' *)\n end.\n\nCompute (minustwo 7).\n\nCheck S.\nCheck pred.\nCheck minustwo.\n\n(* 偶数定义: 递归减2 *)\nFixpoint evenb (n : nat) : bool :=\n match n with\n | O => true\n | S O => false\n | S (S n') => evenb n'\n end.\n\nDefinition oddb (n : nat) : bool := negb (evenb n).\n\nExample test_oddb1 : oddb 1 = true.\nProof. simpl. reflexivity. Qed.\nExample test_oddb2 : oddb 4 = false.\nProof. simpl. reflexivity. Qed.\n\n\nModule NatPlayground2.\n (*\n 计算过程演算\n Compute plus (S (S( S O))) (S (S O))\n 1. (S plus (S (S O)) (S (S O)))\n 2. (S (S (plus (S O) (S (S O)))))\n 3. (S (S (S (plus O (S (S O)))))\n 4. (S (S (S (S (S O))))) 结束.\n *)\n Fixpoint plus (n : nat) (m : nat) :=\n match n with\n | O => m\n | S n' => S ( plus n' m )\n end.\n Compute (plus 3 2).\n\n (* 乘法:\n 3 * 4\n 4 + 2 * 4\n 4 + 4 + 1 * 4\n 4 + 4 + 4 + 0 * 4\n = 12\n *)\n Fixpoint mult (n m : nat) :=\n match n with\n | O => O\n | S n' => plus m ( mult n' m )\n end.\n\n Compute (mult 3 4).\n\n Fixpoint minus (n m : nat) :=\n match n, m with\n | O, _ => O\n | S _, O => n\n | S n', S m' => minus n' m'\n end.\n Example test_mult1: (mult 3 3) = 9.\n Proof. simpl. reflexivity. Qed.\n Example test_minus1: (minus 9 3) = 6.\n Proof. simpl. reflexivity. Qed.\n \nEnd NatPlayground2.\n\nFixpoint exp (base power : nat) : nat :=\n match power with\n | O => S O (* 任意自然数的一次方等于 1 *)\n | S p => mult base (exp base p)\n end.\n\nExample test_exp: (exp 2 2) = 4.\nProof. simpl. reflexivity. Qed. \n\nExample test_exp1: (exp 2 3) = 8.\nProof. simpl. reflexivity. Qed. \n\nFixpoint factorial (n : nat) : nat :=\n match n with\n | O => S O\n | S n' => mult n (factorial n')\n end.\n\nExample test_factorial1: (factorial 5) = (mult 10 12).\nProof. simpl. reflexivity. Qed.\n\nNotation \"x + y\" :=\n (plus x y)\n (at level 50, left associativity)\n : nat_scope.\n\nNotation \"x - y\" :=\n (minus x y)\n (at level 50, left associativity)\n : nat_scope.\n\nNotation \"x * y\" :=\n (mult x y)\n (at level 40, left associativity)\n : nat_scope.\n\nCheck ( (0 + 1) + 1 ).\n\nFixpoint beq_nat (n m : nat) : bool :=\n match n with\n | O => match m with\n | O => true\n | S m' => false\n end\n | S n' => match m with\n | O => false\n | S m' => beq_nat n' m'\n end\n end.\n\nCompute ( beq_nat 12 12 ).\n\nFixpoint leb (n m : nat) : bool :=\n match n with\n | O => true\n | S n' => match m with\n | O => false\n | S m' => leb n' m'\n end\n end.\n\nExample test_leb1: (leb 2 2) = true.\nProof. simpl. reflexivity. Qed.\nExample test_leb2: (leb 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_leb3: (leb 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\n(*Exercise: 1 star (blt nat)*)\nFixpoint blt_nat (n m : nat) : bool :=\n match n, m with\n | O, O => false\n | O, _ => true\n | _, O => false\n | S n', S m' => blt_nat n' m'\n end. \n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\n(*Proof by Simplification*) \n\nTheorem plus_0_n: forall n : nat, O + n = n.\nProof.\n intros n. simpl. reflexivity. Qed.\n\nTheorem plus_0_n': forall n : nat, 0 + n = n.\nProof.\n intros n. reflexivity. \nQed.\n\nTheorem plus_id_example: forall n m : nat,\n n = m ->\n n + n = m + m.\nProof.\n intros n m.\n intros H.\n rewrite <- H.\n reflexivity.\nQed.\n\nTheorem plus_id_exercise: forall n m o : nat,\n n = m -> m = o -> n + m = m + o .\nProof.\n intros n.\n intros m.\n intros o.\n intros H.\n intros I.\n rewrite -> H.\n rewrite -> I.\n simpl.\n reflexivity.\nQed.\n\nTheorem mult_0_plus: forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n rewrite -> plus_0_n.\n reflexivity.\nQed.\n\n\nTheorem mult_S_1: forall n m: nat,\n m = S n -> \n m * ( 1 + n) = m * m.\nProof.\n intros n m.\n intros H.\n rewrite -> H.\n simpl.\n reflexivity.\nQed.\n\nTheorem plus_1_neq_0_firsttry: forall n : nat,\n beq_nat (n + 1) 0 = false .\nProof.\n intros n. destruct n as [| n'].\n - simpl. reflexivity.\n - simpl. reflexivity.\nQed.\n\nTheorem andb_true_elim2: forall b c : bool,\n andb b c = true -> c = true .\nProof.\n intros [] [].\n - simpl. reflexivity.\n - intros H. rewrite <- H. simpl. reflexivity.\n - simpl. reflexivity.\n - intros H. rewrite <- H. simpl. reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1: forall n : nat,\n beq_nat 0 (n + 1) = false .\nProof.\n intros [].\n - simpl. reflexivity.\n - simpl. reflexivity.\nQed.\n\n\n\n\n\n\n\n\n\n\n \n ", "meta": {"author": "xiongxin", "repo": "software-foundations", "sha": "b4b641f35ca3c7f3a68aba17708b638f4eb8521c", "save_path": "github-repos/coq/xiongxin-software-foundations", "path": "github-repos/coq/xiongxin-software-foundations/software-foundations-b4b641f35ca3c7f3a68aba17708b638f4eb8521c/Basics/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871156, "lm_q2_score": 0.9099070115349837, "lm_q1q2_score": 0.8502127066157316}}